App Profile Recommendation 12/14

Screen Link: Learn data science with Python and R projects

My Code:

def freq_table(dataset, index):
    table = {}
    total = 0
    
    for row in dataset: 
        total += 1
        value = row[index]
        if value in table:
            table[value] += 1
        else: 
            table[value] = 1
     
    percentage_table = {}
    for key in table: 
        percentage = (table[key]/total)*100 
        percentage_table[key] = percentage
        
    return percentage_table 

def display_table(dataset, index):
    table = freq_table(dataset, index)
    table_display = []
    for key in table:
        key_val_as_tuple = (table[key], key)
        table_display.append(key_val_as_tuple)

    table_sorted = sorted(table_display, reverse = True)
    for entry in table_sorted:
        print(entry[1], ':', entry[0])

display_table(apple_free,11)

What I expected to happen: print solution

What actually happened:

error occurs

Replace this line with the output/error


IndexError Traceback (most recent call last)
in
----> 1 display_table(apple_free, 11)

in display_table(dataset, index)
19
20 def display_table(dataset, index):
—> 21 table = freq_table(dataset, index)
22 table_display =
23 for key in table:

in freq_table(dataset, index)
5 for row in dataset:
6 total += 1
----> 7 value = row[index]
8 if value in table:
9 table[value] += 1

IndexError: string index out of range

Thanks for your help!

I tried your code on my project and it runs without any error. The error that you get

implies that when the code tries to run row[index], index is out of range of a string. So, in your for loop -

row is somehow just a string and it’s not a list. It should be a list. So, that means your apple_free is not currently, a list of lists like it should be.

So, try to first check what apple_free is currently. Print it out to confirm.