Code error from exercise in module 5

Hi all,

I am doing Mosh’s Python course and completing the exercise at the end of module 5. I am copying his code exactly as Mosh is and I keep getting this error. Anyone know why? Thanks in advance.

...line 5, in <module>
    if char in char_frequency:
TypeError: argument of type 'int' is not iterable

The code I am inputting is:

char_frequency = {}
for char in sentence:
    if char in char_frequency:
        char_frequency[char] += 1
    else:
        char_frequency = 1

Look closely at your last line.

if char in char_frequency:
    char_frequency[char] += 1
else:
    char_frequency[char] = 1

Ahh cheers! :sweat_smile: Was missing the [char]. Are you familiar with this problem? I actually solved it a totally different way. Mosh went and made “sentence” into a dictionary. Here is what I did:

list = []
for element in sentence:
    list.append(element)
x = max(list,key=list.count)
print(x)

I used an empty list and appended it with ‘max’. I can see the different procedures of these, but I am still unsure of the implications beyond this. Like what is the difference between doing what Mosh did (i.e. using a dictionary) and what I did (appending an empty list) ??

One difference between the two approaches is performance.

In the Mosh approach we:

  • Iterate through the sentence once to build up the char_frequency dictionary.
  • Iterate through the char_frequency dictionary once to find out which character was the most
    frequent.

In the list approach we:

  • Iterate through the sentence once to build up the list.
  • Iterate through the list once to call the list.count function for each item, which in turn must…
    • Iterate through the list to calculate the count of the item.

So with the list approach, if the sentence is ten characters long, then the list.count function will be run 10 times and each time must examine 10 items, i.e. in total it must examine 10 x 10 = 100 items. In other words, if the list is n items long, then we need to examine n x n items i.e. n2 items, and so the performance of this approach is proportional to the square of n. Compare to the Mosh approach, which is proportional to n i.e. as n increases, performance decreases, but only linearly, not squared. As n2 is usually larger and sometimes much larger than n, the performance of n2 algorithms is usually worse than the performance of n algorithms.

Whether the performance difference really matters here is another question.

1 Like