428-10 Most Common Apps by Genre: Part Two

Sorry for the comments in the code, but trying to solidify the knowledge. But I attempted to just run freq_table() function and ran into an error.

This was code taken from the solution so I’m not sure why “total = 0” because everything is always dividing against zero?

I presume “total = 0” should be a calculation of the total for all values in the key/value pairs within table dictionary. But the solution doesn’t have that?

I just used total = sum(table.values()). Let me know if that wasn’t the intended outcome.


#freq table checks the occurrence the same thing occurred 
#(i.e. ratings being the key and value being the iteration)

def freq_table(dataset, index): 
table = {}
total = 0

for row in dataset:
    value = row[index] #i.e. ratings in index # assigned to value
    if value in table: #i.e. checking ratings in table dictionary keys
        table[value] += 1 #table[value] is the key > if key exists, add 1 to the value
        table[value] = 1 #table[value] is the key > if key DOESN'T exists, add the key w/ value of 1

table_percentages = {}
for key in table: #looping over dictionary (table) is default over the dictionary keys
    percentage = (table[key] / total) * 100
    table_percentages[key] = percentage 

return table_percentages

What error did you get running freq_table() function? Can you share it here?

Also, the code of the function is not properly formatted, at least in your post.

I’m not sure how to format easily on here, but in any case, here is a screenshot of the format and error message.

This is right from the solutions example, but the variable total always remains at zero and never is used as a calculation in the code, from what I see. Of course mathematically, for the percentage to work we would just need the value / total values in the table.

You just missed one important line where value of total was changing…


Opps. Thanks. :slight_smile: