Hello,
Doing guided project ‘Exploring Hacker News Posts’ and have a question.
My Code:
# Create a table that contains the hours of day and the average number of posts
avg_by_hour = []
for hour in counts_by_hour:
num_posts = counts_by_hour[hour]
num_comments = comments_by_hour[hour]
average = num_comments / num_posts
avg_by_hour.append([hour, average])
# Print the result
output = "For hour {} the average number of comments per post is {:.1f}"
for row in avg_by_hour:
print (output.format(row[0], row[1]))
That works as such, as I get this result:
For hour 9 the average number of comments per post is 5.6
For hour 13 the average number of comments per post is 14.7
For hour 10 the average number of comments per post is 13.4
For hour 14 the average number of comments per post is 13.2
For hour 16 the average number of comments per post is 16.8
For hour 23 the average number of comments per post is 8.0
For hour 12 the average number of comments per post is 9.4
For hour 17 the average number of comments per post is 11.5
For hour 15 the average number of comments per post is 38.6
For hour 21 the average number of comments per post is 16.0
For hour 20 the average number of comments per post is 21.5
For hour 2 the average number of comments per post is 23.8
For hour 18 the average number of comments per post is 13.2
For hour 3 the average number of comments per post is 7.8
For hour 5 the average number of comments per post is 10.1
For hour 19 the average number of comments per post is 10.8
For hour 1 the average number of comments per post is 11.4
For hour 22 the average number of comments per post is 6.7
For hour 8 the average number of comments per post is 10.2
For hour 4 the average number of comments per post is 7.2
For hour 0 the average number of comments per post is 8.1
For hour 6 the average number of comments per post is 9.0
For hour 7 the average number of comments per post is 7.9
For hour 11 the average number of comments per post is 11.1
Now there is two things that I would like to change though:
- The sequence seems random. I would rather get this in the sequence hour 0, hour 1, hour 2 etc. I don’t know how to impact the sequence of a for-loop though. (Or if that’s not how to do this, how to do this then.)
- (less important, but still) For readability, I would want to pad with leading zeroes, so e.g. ‘hour 08’, hour 09’, then followed by ‘hour 10’
For neither I was sure how to do this, and could not easily find it.
So my question is two-fold actually:
-
Do you know solutions for these two things?
-
More in general, what do you see as an efficient way of figuring out such things?
Just type what you are trying to achieve in a google search bar?
Start searching in the official documentation https://docs.python.org/3/
…?