goughgough goughgough - 1 year ago 124
Python Question

Python 3: Finding word which appears the most times without using import or counter or dictionary, only simple tools like .split() and .lower()

I am currently learning Python and trying to solve a free tutorial question.

Here is the question.

A writer is working on their newest poem, Turing and the Machines. They have hired you to determine the word which appears the most times. You can access the lines of the poem by calling input() repeatedly, and the last line contains the three characters ###. All lines consist of words separated by single spaces; there are no digits or punctuation. Convert all the words to lower-case, and print the word that occurs the most times (we guarantee there will not be a tie).
For example, if the input is

Here is a line like sparkling wine

Line up fast or be the last

# # #

Then the output should be


since it appears twice and no other word appears twice.

..........Below is the closest thing to a solution I can get.

It still lacks , among other things, the facility to allow a user to call input() repeatedly.

And it only prints out the maximum number of the most used word , not the word itself that the question wants.

The poem is supplied by the website shell , at

Let's assume the user will input the poem one line at a time.

Please help. Thanks a million.


def poem(P):

P_lower = P.lower()

P_split = P_lower.split()

word_list = []

wordfreq = []

for i in P_split:

for i in P_split:


poem('Here is a line like line sparkling line wine')

Answer Source

This doesn't use any of the "restricted" tools but only lower(), split() and sort() to return the word with the most occurrences.

def  main():
    done = False
    P = ""
    while not done:
        new_line = input()
        if new_line != "###":
            P += new_line + " "
            done = True
    poem_words = P.lower().split()

    # Initialize variables
    temp = ""
    max_count = 0
    icount = 1
    max_word = ""

    # Do the loop
    for i in range(len(poem_words)):
        if temp == poem_words[i]:
            icount += 1
            temp = poem_words[i]
            icount = 1
        if icount > max_count:
            max_count = icount
            max_word = temp

if __name__ == "__main__":
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download