PYTHON3, NO IMPORTS, NO PANDAS: Your challenge for this problem is to create a f
ID: 3713952 • Letter: P
Question
PYTHON3, NO IMPORTS, NO PANDAS:
Your challenge for this problem is to create a function process_book that takes in 2 arguments: book_name and mode.
book_name: the string that is the name of the file to open
mode: a string that is either "average" or "median"
return: the "average" word length in the book or the "median" word length in the file, depending on the second argument.
Hint: We got a median word length of 4 for War and Peace.
Function to create:
def(book_name, mode):
Given Dictionary from book_name:
{1: 14932, 2: 93387, 3: 141594, 4: 97791, 5: 57778, 6: 48342, 7: 42747, 8: 29986, 9: 17731, 10: 11155, 11: 4943, 12: 2986, 13: 1572, 14: 569, 15: 254, 16: 126, 17: 47, 18: 40, 19: 14, 20: 8, 21: 2, 23: 2, 26: 2, 27: 1}
Key is length of word
Value is how many words were that length key value.
Explanation / Answer
def process_book(book_name, mode): lst = [] with open(book_name, 'r') as f: for line in f: for word in line.strip().split(): lst.append(len(word)) if mode == 'average': return sum(lst) / len(lst) else: if len(lst) % 2 == 0: return (lst[len(lst)//2] + lst[(len(lst)//2)-1]) / 2 else: return lst[len(lst) // 2]
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.