0

The goal of this code is to count the word that appears the most within the given list. I planned to do this by looping through the dictionary. If a word appeared a greater number of times than the value stored in the variable rep_num, it was reassigned. Currently, the variable rep_num remains 0 and is not reassigned to the number of times a word appears in the list. I believe this has something to do with trying to reassign it within a for loop, but I am not sure how to fix the issue.

def rep_words(novel_list):
    rep_num=0
    for i in range(len(novel_list)):
        if novel_list.count(i)>rep_num:
            rep_num=novel_list.count(i)
    return rep_num
novel_list =['this','is','the','story','in','which','the','hero','was','guilty']

In the given code, 2 should be returned, but 0 is returned instead.

1
  • you're counting an integer (i) which doesn't appear in your list at all. Commented Jun 28, 2019 at 16:09

3 Answers 3

1

In you for loop you are iterating over the numbers and not list elements themselves,

def rep_words(novel_list):
    rep_num=0
    for i in novel_list:
        if novel_list.count(i)>rep_num:
            rep_num=novel_list.count(i)
    return rep_num
Sign up to request clarification or add additional context in comments.

Comments

1

You're iterating over a numeric range, and counting the integer i, none of which values exist in the list at all. Try this instead, which returns the maximum frequency, and optionally a list of words which occur that many times.

novel_list =['this','is','the','story','in','which','the','hero','was','guilty']

def rep_words(novel_list, include_words=False):
    counts = {word:novel_list.count(word) for word in set(novel_list)}
    rep = max(counts.values())
    word = [k for k,v in counts.items() if v == rep]
    return (rep, word) if include_words else rep

>>> rep_words(novel_list)
2
>>> rep_words(novel_list, True)
(2, ['the'])
>>> rep_words('this list of words has many words in this list of words and in this list of words is this'.split(' '), True)
(4, ['words', 'this'])

Comments

0

You've an error in your function (you're counting the index, not the value), write like this:

def rep_words(novel_list):
    rep_num=0
    for i in novel_list:
        if novel_list.count(i)>rep_num:  #you want to count the value, not the index
            rep_num=novel_list.count(i)
    return rep_num

Or you may try this too:

def rep_words(novel_list):
    rep_num=0
    for i in range(len(novel_list)):
        if novel_list.count(novel_list[i])>rep_num:
            rep_num=novel_list.count(novel_list[i])
    return rep_num

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.