Avoiding a Counter

I would like feedback about my code. There must be an issue, as I am calculating the same average for both ask and show posts.
I am trying to optimize my Python so I no longer need a counter.

total_show_comments = 0
for item in show_posts:
    row_total = row[4]
    counter = 0
    total_show_comments += int(row_total)
    counter += 1
    average_show_comments = total_show_comments / counter
total_ask_comments = 0
for item in ask_posts:
    num_comments = int(row[4])
    total_ask_comments += num_comments
    #caclulate average
avg_ask_comments = (total_ask_comments) / num_ask_posts

My code is computing to 58 for average show and ask comments.

Hi @hunter.kiely

If you look at the iterating variable you’re using and from where you are getting num_comments, you might get the right answer.

Also, I believe that you have used num_ask_posts = len(ask_posts)

Is there something incorrect about using num_ask_posts = len(ask_posts)? Does there need to be an iterated counter for posts and comments?

Hi @hunter.kiely

Your iterating variable is item but you are assigning value to num_comments from row[4]

Also, there is nothing wrong with num_ask_posts = len(ask_posts). I just wanted to confirm that since I couldn’t find the value of num_ask_posts in your code.

By adding a second variable, I get the same answer and the code is more complex.

1 Like