356-4 Hacker News Average no comments , ask_posts, show_posts

Hello, I have calculated the average of ask_posts and show-posts comments, I have divided the total number of comments by len(ask_posts), which is the number of items in the entire list. I think it should be divided by the number of comments in the column.

Any guidance would be appreciated

total_ask_comments = 0
num_ask_posts = len(ask_posts)
num_ask_posts = int(num_ask_posts)
for row in ask_posts:
    num_comments = int(row[4])
    total_ask_comments += num_comments
avg_ask_comments = total_ask_comments/num_ask_posts
print(avg_ask_comments)

Why do you need to convert to integer?
len returns an integer.

Overall, the logic looks good.

You can reduce

    num_comments = int(row[4]) 
    total_ask_comments += num_comments

to

    total_ask_comments +=  int(row[4]) 

Or use a generator comprehension to sum the total comments.

total_ask_comments = sum(int(row[4]) for row in ask_posts)
num_ask_posts = len(ask_posts)
avg_ask_comments = total_ask_comments/num_ask_posts
print(avg_ask_comments)
1 Like

Thanks for the advice