A simple basic Python3 question which I don't Understand - python-3.x

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.

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.

How do i display word with missing first letter?

i get a TypeError saying can't convert 'list' object to str implicitly
# list of words to choose from and get a random word using the random module's sample method
list_of_words = ['apple', 'banana', 'watermelon', 'kiwi', 'pineapple', 'mango']
word = random.sample(list_of_words,1)
# showcase to the player the random word with first letter missing
chosen_word = word[1:]
print('The answer so far is _' + chosen_word)
I expect the output to be for example: The answer so far is _anana
random.sample picks multiple random elements from the input sequence, according to the number given for the second argument. Because it is meant to return a variable number of elements, it returns them in a list, even if you specified that you only want one.
Therefore word is a list with one element and
word[1:]
is a sliced version of that list (the empty list), but still a list. The error message tells you, that you cannot add a list to a string by relying on an implicit conversion of the list to a string representation. What you actually want to apply [1:] to is not the list, but the element in it. So you need to select it first with word[0] (take the first element of word), then you can slice the string: word[0][1:].
If you always want only one element, you can also use random.choice instead of random.sample, which doesn't take the second argument and always returns only one randomly chosen element, not as list:
word = random.choice(list_of_words)
chosen_word = word[1:]

Doubts about string

So, I'm doing an exercise using python, and I tried to use the terminal to do step by step to understand what's happening but I didn't.
I want to understand mainly why the conditional return just the index 0.
Looking 'casino' in [Casinoville].lower() isn't the same thing?
Exercise:
Takes a list of documents (each document is a string) and a keyword.
Returns list of the index values into the original list for all documents containing the keyword.
Exercise solution
def word_search(documents, keyword):
indices = []
for i, doc in enumerate(documents):
tokens = doc.split()
normalized = [token.rstrip('.,').lower() for token in tokens]
if keyword.lower() in normalized:
indices.append(i)
return indices
My solution
def word_search(documents, keyword):
return [i for i, word in enumerate(doc_list) if keyword.lower() in word.rstrip('.,').lower()]
Run
>>> doc_list = ["The Learn Python Challenge Casino.", "They bought a car", "Casinoville"]
Expected output
>>> word_search(doc_list, 'casino')
>>> [0]
Actual output
>>> word_search(doc_list, 'casino')
>>> [0, 2]
Let's try to understand the difference.
The "result" function can be written with list-comprehension:
def word_search(documents, keyword):
return [i for i, word in enumerate(documents)
if keyword.lower() in
[token.rstrip('.,').lower() for token in word.split()]]
The problem happens with the string : "Casinoville" at index 2.
See the output:
print([token.rstrip('.,').lower() for token in doc_list[2].split()])
# ['casinoville']
And here is the matter: you try to ckeck if a word is in the list. The answer is True only if all the string matches (this is the expected output).
However, in your solution, you only check if a word contains a substring. In this case, the condition in is on the string itself and not the list.
See it:
# On the list :
print('casino' in [token.rstrip('.,').lower() for token in doc_list[2].split()])
# False
# On the string:
print('casino' in [token.rstrip('.,').lower() for token in doc_list[2].split()][0])
# True
As result, in the first case, "Casinoville" isn't included while it is in the second one.
Hope that helps !
The question is "Returns list of the index values into the original list for all documents containing the keyword".
you need to consider word only.
In "Casinoville" case, word "casino" is not in, since this case only have word "Casinoville".
When you use the in operator, the result depends on the type of object on the right hand side. When it's a list (or most other kinds of containers), you get an exact membership test. So 'casino' in ['casino'] is True, but 'casino' in ['casinoville'] is False because the strings are not equal.
When the right hand side of is is a string though, it does something different. Rather than looking for an exact match against a single character (which is what strings contain if you think of them as sequences), it does a substring match. So 'casino' in 'casinoville' is True, as would be casino in 'montecasino' or 'casino' in 'foocasinobar' (it's not just prefixes that are checked).
For your problem, you want exact matches to whole words only. The reference solution uses str.split to separate words (the with no argument it splits on any kind of whitespace). It then cleans up the words a bit (stripping off punctuation marks), then does an in match against the list of strings.
Your code never splits the strings you are passed. So when you do an in test, you're doing a substring match on the whole document, and you'll get false positives when you match part of a larger word.

Python Function with 2 values

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.

Pass a string and compare it to a list

I am passsing an argument through robot framework. The argument is a string. "Detroit".
I want the code to break down that string to "D", "De", "Det", "Detr", "Detro","Detroi", and "Detroit". Of course if another string is entered, say "Flint" it would only break it down into the 5 elements. F, Fl, Fli, Flin, Flint.
(Pseudo Code)
def checkCity (self, x):
(take x which is the string, and make it a list of elements containing the letters as above).
(Then take each element and check it against data provided by the device(using a loop for each iteration)
(Once any of the elements are matched to the data, return another function that acts as a key press)
I'm familiar enough with python (and programming) in general to have the theory, just don't know how to code it.
I'm not familiar with the programming language that you are using but I will help out as much as I can.
For breaking down the string, you could use a while loop or a for loop, whichever you prefer. The ending condition being the length of the string that you put into the second parameter. In the loop, you can use substring method to break down the string and store each element into an array list.
Then for checking if any of the elements are matched, you would (as you have said) use a loop for each iteration.
In python you can access individual parts of a string by using
string[5:7]
That would give the 5th and 6th characters
This function in python will return a list like the one you want
def toSubLists(string):
sublists = []
for i in range(1, len(string)+1):
sublists.append(string[0:i])
return sublists

Resources