Python Function with 2 values - python-3.x

Homework Question I am struggling with
Specification:
The third function you will write should be called ‘excelPrep’. Your function should take one (1) argument:
a string that will contain the Excel formula. The function should return two (2) values: first, a string
containing the modified Excel formula; and second an integer containing the number of dollar signs
removed.
Example Test Case:
excelPrep(‘=SUM($A$4:$A$12)’)
returns
=sum(a4:a12)
and
4

I will not write the entire code since this is stackoverflow and not homework helper so I think you should complete with your own mind.
The function should be something like:
Remove the $ by checking every letter in the string with for loop, at the same time add a number counter so that you can know how many $s you’ve removed. Making the input from =SUM($A$4:$A$12) into =SUM(A4:A12).
You could return the value now however if the assignment specified to make the letters in to lowercase. Make a new string variable and append all the letters from the function returned variable =SUM(A4:A12) check if the letter is a number if not .lower(). Which leaves you with =sum(a4:a12).
To return two values, in the end of your function type return stringVariable, integerVariable. Just be careful when ever you are calling the function, you will need to variables to store the outputs. Like: a, b = excelPrep(“=SUM($A$4:$A$12) which for your information a = “=sum(a4:a12)”, b = 4.
Hope that helps.

Related

Inner workings of map() in a specific parsing situation

I know there are already at least two topics that explain how map() works but I can't seem to understand its workings in a specific case I encountered.
I was working on the following Python exercise:
Write a program that computes the net amount of a bank account based a
transaction log from console input. The transaction log format is
shown as following:
D 100
W 200
D means deposit while W means withdrawal. Suppose the following input
is supplied to the program:
D 300
D 300
W 200
D 100
Then, the output should be:
500
One of the answers offered for this exercise was the following:
total = 0
while True:
s = input().split()
if not s:
break
cm,num = map(str,s)
if cm=='D':
total+=int(num)
if cm=='W':
total-=int(num)
print(total)
Now, I understand that map applies a function (str) to an iterable (s), but what I'm failing to see is how the program identifies what is a number in the s string. I assume str converts each letter/number/etc in a string type, but then how does int(num) know what to pick as a whole number? In other words, how come this code doesn't produce some kind of TypeError or ValueError, because the way I see it, it would try and make an integer of (for example) "D 100"?
first
cm,num = map(str,s)
could be simplified as
cm,num = s
since s is already a list of strings made of 2 elements (if the input is correct). No need to convert strings that are already strings. s is just unpacked into 2 variables.
the way I see it, it would try and make an integer of (for example) "D 100"?
no it cannot, since num is the second parameter of the string.
if input is "D 100", then s is ['D','100'], then cm is 'D' and num is '100'
Then since num represents an integer int(num) is going to convert num to its integer value.
The above code is completely devoid of error checking (number of parameters, parameters "type") but with the correct parameters it works.
and map is completely useless in that particular example too.
The reason is the .split(), statement before in the s = input().split(). This creates a list of the values D and 100 (or ['D', '100']), because the default split character is a space ( ). Then the map function applies the str operation to both 'D' and '100'.
Now the map, function is not really required because both values upon input are automatically of the type str (strings).
The second question is how int(num) knows how to convert a string. This has to do with the second (implicit) argument base. Similar to how .split() has a default argument of the character to split on, so does num have a default argument to convert to.
The full code is similar to int(num, base=10). So as long as num has the values 0-9 and at most 1 ., int can convert it properly to the base 10. For more examples check out built in int.

A simple basic Python3 question which I don't Understand

Question:
Fill in the function body for the Python3 function longestWord (you should leave the function header as it appears).
The function takes a single input argument which we assume is a list of strings, with each string forming one English word. The output should be a word from the list which has the greatest number of letters.
You must use a for loop to write this function.
Answer:
def longestWord(listOfWords):
biggestWord = listOfWords[0]
biggestNum = len(biggestWord)
for word in listOfWords:
num = len(word)
if num>biggestNum:
biggestNum=num
biggestWord=word
return biggestWord
print(longestWord(["Hello", "Goodbye"]))
I understand the first three lines. It takes the first value in the list and saves the length of the word inputted. However i don't understand the rest of the code. How does it compare the two inputted words to output the longest one. What is num and word?. Thank you.
I'd like to inform you that this question is about Python3 and not C++. Anyways, what the code is doing is it's taking the first word and stores it in a variable called biggestWord. and storing the length of biggestWord in a variable called biggestNum. Then for each word in listOfWords, it stores the word in a variable called word and stroing the length of it in variable called num. Then it compares num and biggestNum. If the length of some word i.e. num is bigger than the biggest length up until now, i.e. biggestNum, then it puts num in biggestNum to indicate that that's the biggest number up until now. and puts word in biggestWord replacing the old word. Then it returns the word with the biggest length, i.e. biggestWord.

Trying to compare a string to an array and return string, instead of a value

I'm trying to write a function that looks at the string in a cell and depending on the first 2-3 letters write a string in the cell next to it.
For example:
"LSH T1402A" should return "High-Level Safety"
"FI P1402A" should return "Flow Indicator"
(I know in the second case there are only 2 symbols, but in the array I would include the space in the string so that shouldn't give any problems)
At first I was thinking of using an IF function, but quickly abandoned the idea because it would become too lengthy.(many different strings/types of sensors)
Currently I've broken down my problem in 4 steps
Read String
Return first 3 symbols
Compare to array/matrix
Write string corresponding.
The first two parts I think I can solve by using "=LEFT(TRIM([CEL]);3) but I am stuck on how to compare it to an array. The MATCH function comes close but only returns a value for which position the cell is on I believe?
Does anyone have an idea how I should continue solving this problem? Many thanks!
If your array was say in G1:H10 then you could
lookup your 3 character code in G1:G10 using MATCH
return the corresponding value from H1:H10 using INDEX
example
=INDEX(H1:H10,MATCH(LEFT(A1,3),G1:G10,0))
Function will return a #N/A if no match is found

Extracting a specific word and a number of tokens on each side of it from each string in a column in SAS?

Extracting a specific word and a number of tokens on each side of it from each string in a column in SAS EG ?
For example,
row1: the sun is nice
row2: the sun looks great
row3: the sun left me
Is there a code that would produce the following result column (2 words where sun is the first):
SUN IS
SUN LOOKS
SUN LEFT
and possibly a second column with COUNT in case of duplicate matches.
So if there was 20 SUN LOOKS then it they would be grouped and have a count of 20.
Thanks
I think you can use functions findw() and scan() to do want you want. Both of those functions operate on the concept of word boundaries. findw() returns the position of the word in the string. Once you know the position, you can use scan() in a loop to get the next word or words following it.
Here is a simple example to show you the concept. It is by no means a finished or polished solution, but intended you point you in the right direction. The input data set (text) contains the sentences you provided in your question with slight modifications. The data step finds the word "sun" in the sentence and creates a variable named fragment that contains 3 words ("sun" + the next 2 words).
data text2;
set text;
length fragment $15;
word = 'sun'; * search term;
fragment_len = 3; * number of words in target output;
word_pos = findw(sentence, word, ' ', 'e');
if word_pos then do;
do i = 0 to fragmen_len-1;
fragment = catx(' ', fragment, scan(sentence, word_pos+i));
end;
end;
run;
Here is a partial print of the output data set.
You can use a combination of the INDEX, SUBSTR and SCAN functions to achieve this functionality.
INDEX - takes two arguments and returns the position at which a given substring appears in a string. You might use:
INDEX(str,'sun')
SUBSTR - simply returns a substring of the provided string, taking a second numeric argument referring to the starting position of the substring. Combine this with your INDEX function:
SUBSTR(str,INDEX(str,'sun'))
This returns the substring of str from the point where the word 'sun' first appears.
SCAN - returns the 'words' from a string, taking the string as the first argument, followed by a number referring to the 'word'. There is also a third argument that specifies the delimiter, but this defaults to space, so you wouldn't need it in your example.
To pick out the word after 'sun' you might do this:
SCAN(SUBSTR(str,INDEX(str,'sun')),2)
Now all that's left to do is build a new string containing the words of interest. That can be achieved with concatenation operators. To see how to concatenate two strings, run this illustrative example:
data _NULL_;
a = 'Hello';
b = 'World';
c = a||' - '||b;
put c;
run;
The log should contain this line:
Hello - World
As a result of displaying the value of the c variable using the put statement. There are a number of functions that can be used to concatenate strings, look in the documentation at CAT,CATX,CATS for some examples.
Hopefully there is enough here to help you.

Cl0sed Functions in Druid

I'm trying to write a function that takes an 8-character binary string s and a positive number as an integer n, and prints a sequence of n binary numbers that increase according to my increment function.
How to I edit my function so that I can print these?
Assuming all of your other code is correct, there are five problems in your recursive code.
First, you're trying to use the value returned by the recursive call to count. But you have no return statements anywhere, so what could that value possibly be? So that inc*cnt is just going to try to multiply a string by None and raise a TypeError. If you look at your code, you have no need to return anything upward; count just takes some values, prints something, and calls itself again. So just ignore the None that it returns.
Next, you're trying to increment s[-1]. But s is a string, so that's just going to be the last character. You want to "increment" the whole string, right? So just pass s.
Next, you're trying to call yourself with s[:-1]. Again, s is a string; this is going to try to increment the first 7 digits of that string, then the first 6, and so on. Why would you want that? What you want to increment is the value you just incremented. That is, the same thing you just stored in inc. So just pass inc.
Next, you're doing the print after the recursive call. This means you're going to call the function that prints the second and later values, then print the first value. And so on. So they're going to show up in reverse order. If you want the first value first, print before the recursive call.
Finally, you clearly want the original value and the next 4 to get printed, not the next 5 without the original value. So you have to print out the pre-incremented value, not the post-incremented one.
So, the minimal change to your code is:
def count(s, n):
if n == 0:
return
else:
inc = increment(s)
print(s)
count(inc, n-1)

Resources