Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

Python Help

Name: Anonymous 2008-12-04 2:04

Ok /prog/, so I've been awfully busy learning python lately and I was wondering if you could help me.I've been working on my side project lately and I came across this interesting little math problem and was hoping that some skilled /prog/grammers could help me out with an elegant solution.

People can rate cheeseburgers on my website with a star rating of 0-5 stars in whole stars. Five would be mighty tasty and zero would be disgusting. I want to show the average of everyone’s ratings of a single cheeseburger to the closest half star. I have already calculated the average rating as a float (star_sum) and the total number of people that rated the particular cheeseburger (num_raters). The result would then be stored as a float in a variable named “stars.”

here is my python code:

# round to one decimal place and
# separate into whole and fractional parts
parts = str(round(star_sum/num_raters, 1)).split('.')
whole = int(parts[0])
frac = int(parts[1])
if frac < 3:
___frac = 0
elif frac > 7:
___frac = 0
___whole += 1
else:
___frac = 5
# recombine for a star rating rounded to the half
stars = float(str(whole)+’.'+str(frac))


Does anybody have a better solution for me?

Name: Anonymous 2008-12-04 7:43

I’ve updated my solution to:

stars = round(star_sum*2/num_raters)/2

I knew there was a way to do this mathematically, I just couldn’t remember how. I suppose the same trick would work for rounding to thirds, fourths, etc. Thanks so much to r, Christopher Finke, and Bob for the better approach.

lol

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List