Act fast, special offers end soon! Up to $294 is savings when you get Premium today.
Get offer codes

Most Common Apps by Genre: Part Two

Please I need explanation on why my code didn’t work. I am trying hard to code the solutions myself and understand the concepts instead of looking up the solution to the project. Thanks.

# function to generate frequency tables that show percentage

def freq_table(dataset, index):
    new_dict = {}
    new_dict_proportions = {}
    new_dict_percentages = {}
    sum_list = 0
    for element in dataset[index]:
        sum_list += element

    for value in dataset[index]:
        if value in new_dict:
            new_dict[value] += 1
            new_dict[value] = 1
    for value in new_dict:
        proportion = new_dict[value] / sum_list
        print('Key:', value)
        print('Proportion value:', proportion)
        new_dict_proportions[value] = proportion
    for value in new_dict_proportions:
        percentage = new_dict_proportions[value] * 100
        new_dict_percentages[value] = percentage

    return new_dict_percentages

This was the error prompt I got:

TypeErrorTraceback (most recent call last)
<ipython-input-21-cb51637b2553> in <module>()
---> 45 display_table(apple_final, -5)
     46 display_table(gplay_final, 1)
     47 display_table(gplay_final, -4)

<ipython-input-21-cb51637b2553> in display_table(dataset, index)
     33 def display_table(dataset, index):
---> 34     table = freq_table(dataset, index)
     35     table_display = []
     36     for key in table:

<ipython-input-21-cb51637b2553> in freq_table(dataset, index)
      9     for element in dataset[index]:
---> 10         sum_list += element
     12     for value in dataset[index]:

TypeError: unsupported operand type(s) for +=: 'int' and 'str'

The error states that you’re trying to sum an integer and a string in the following line:

sum_list += element

As sum_list is set to 0, the problem should be on the element variable. Keep in mind that dataset is a list of lists, therefore dataset[index] is a list. What you are doing is o sum all the elements in this list, but some of them are strings and that’s why you get the error.

1 Like

Ohhh yess… The code I wrote would have worked for integers but I was using it for strings. I understand now, Thank you @otavios.s

1 Like