Ask your own question, for FREE!
Computer Science 7 Online
OpenStudy (anonymous):

Why does this not find the sum of multiples of 3 and 5 that go up to 1000? sum, three_multiple, five_multiple = 0, 1, 1 while True: if 3 * three_multiple >= 1000: break sum += 3 * three_multiple three_multiple += 1 while True: if 5 * five_multiple >= 1000: break sum += 5 * five_multiple five_multiple += 1 print sum

OpenStudy (anonymous):

You're counting every multiple of 15 (3*5) twice.

OpenStudy (anonymous):

Thank you!

OpenStudy (anonymous):

This gets the correct answer, but I don't know why I should add the 1 in the for loop. sum, three_multiple, five_multiple = 0, 1, 1 for three_multiple in range(1, 1000/3 + 1): #decimal is truncated sum += 3 * three_multiple for five_multiple in range(1, 1000/5): if (5 * five_multiple) % 3 != 0: sum += 5 * five_multiple print sum print 233168

OpenStudy (anonymous):

1000 / 3 = 333, and the range function goes up to *but not including* the second number. So since you want to include 333, you actually need that number to be 334. For the record, you can do this in one loop. total = 0 for x in range(1,1001): if x%3==0 or x%5==0: total += x print total

OpenStudy (anonymous):

Wow, much nicer. Why does it not work when I make it be 201 for my second for loop?

OpenStudy (anonymous):

Do you want to include 1000 or not? My code actually includes 1000 as a possibility, yours does not. If you changed it to 201, then it would count 1000 and give 234168 as an answer instead of 233168. If you don't want to include 1000, then my code should say "for x in range(1,1000)" instead.

OpenStudy (anonymous):

IC, silly me.

OpenStudy (anonymous):

Thanks; and your solution is really elegant.

OpenStudy (anonymous):

Gracias, but for beginning comp sci students, you should feel proud that you got something up and running that works. "Short and sweet" comes later, and Python is full of short and sweet functions.

OpenStudy (anonymous):

Like this one: print sum( [ i for i in range( 1000 ) if not i % 3 or not i % 5 ] )

OpenStudy (anonymous):

This problem is from Project Euler by the way.

Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!
Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!