Date: Tuesday, November 7, 2023.
Due Date: Tuesday, November 14, 2023.
Goal: to use the in operator with a list and the function mapping in Python.
Create a Python file called lab10.py and add your name and the lab number as a comment at the top.
a. For loop
Write a function that receives a string as a parameter and returns another string representing the largest word in the string. We consider words as separated by spaces. The header of the function should be:
def largestWord(text):
For this, you can use the function maxIndex seen in class as a model.
Start by converting the text into a list of words by using the
built-in function split:
text.split()
then store the result of this call in a variable
called words. Then declare a variable maxx
initialized as 0.
Add a for loop using a range over the length of the list words. For each position i, compare the length of the element words[i] with the length of the element at position maxx, and if the current one is larger, update the value of maxx with the value of i.
Finally, after the loop, return the value of words[maxx].
Add a main function where you input a text from the user and store it in a variable, then you call the function largestWord and print the result. Then after the main, make a call to it.
b. Map
Copy the following function into your code:
def largestWord1(text): words = text.split() lengths = [len(e) for e in words] maxLen = max(lengths) idx = lengths.index(maxLen) return words[idx]
Add a print statement after each line in the function printing out the result of the operation (the variable just computed). We can call these debugging statements. Then in the main, make a call to this function to observe the different operations and their results.
Write a function with the following header:
def printCommon(a, b):
This function takes in two lists as parameters and should print out all the elements they have in common. For this, use a for loop that goes over the first list. For each element, if this element can also be found in the second list, print it out.
Add a test for this function in the main. Input two lists from the user and then call the function to print the common elements.
Upload the file lab10.py in Canvas, Assignments, Homework 10. You can wait until you finish the homework to upload all the files at the same time.