How do I find and set as variables for finding the longest word in a text file for MapReudce

19 Views Asked by At

Required output is "The longest word has 13 characters. The result includes: word1 word2"

I am required to use the terminal to write python '''.py < .txt''' and I am stuck after the following codes I have written and have no idea how I should use the max function for it. Need some help desparetely. It is for MapReduce

import sys
results = {}
for line in sys.stdin:
    line=line.strip().split()
    for word in line:
        results[word] = len(word)
1

There are 1 best solutions below

0
B Remmelzwaal On

You could keep track of the longest words like this:

import sys

longest = 0  # not *necessary* but more readable
results = []

for line in sys.stdin:
    line = line.strip().split()
    for word in line:
        if len(word) > longest:    # new longest
            longest = len(word)    # update record
            results.clear()        # remove previous records
            results.append(word)   # add the word
        elif len(word) == longest: # also add these words
            results.append(word)

print(f"The longest word has {longest} characters. The result includes: {results}")