Guided project : Exploring Hacker News Posts, Step 4: I am not getting logical answers, also where can I find the notebook solutions

Screen Link:
https://app.dataquest.io/m/356/guided-project%3A-exploring-hacker-news-posts/4/calculating-the-average-number-of-comments-for-ask-hn-and-show-hn-posts

My Code:

 from csv import reader
opened_file = open('hacker_news.csv')
read_file = reader(opened_file)
hn= list(read_file)
hn = hn[1:5]

ask_posts=[]
show_posts=[]
other_posts=[]
for row in hn:
    title=row[1]
    if title.lower().startswith('ask hn'):
        ask_posts.append(row)
    elif title.lower().startswith('show hn'):
        show_posts.append(row)
    else:
        other_posts.append(row)
        
print(len(ask_posts))
print(len(show_posts))
print(len(other_posts))

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



What I expected to happen:

What actually happened:

Replace this line with the output/error

Hi @mouazsamman, welcome to the community!

This part of your code is causing a problem for me:

hn = hn[1:5]

It looks like you’re only saving 4 of the rows to hn, so then later there are no ask and show posts. If you just want to eliminate the header row, you could use hn[1:] so that it includes all but the header row.

After I made that change, I noticed that the results for the averages weren’t as expected. The problem is with the len in the calculations for each average. For example, len(ask_posts[4]) will give the length of the row at index 4, instead of the length of the list (the number of rows ask_posts has).

I hope that helps! Let me know if I doesn’t make sense.

In the DQ Jupyter interface, at the top, there’s a button with a key symbol on it. This is the link to the solutions notebook.
image

1 Like