4 ms·
I hate to look really amateurish, and please correct me if this is irrelevant to the thread, but would the following python code equal to the amount of money re
by colbyolson 17y ago
I hate to look really amateurish, and please correct me if this is irrelevant to the thread, but would the following python code equal to the amount of money received if each shirt was sold for one design?
(It's python, and I'm very new to programming. Criticism is welcome.)
a,b = 1,1
while a <= 100:
a = a + 1
b = b + a
print(b)
- unwind 17y agoNope, that ends up with $100 too much. The proper way is documented here: <http://wiki.answers.com/Q/What_is_the_sum_of_the_first_100_positive_integers> http://wiki.answers.com/Q/What_is_the_sum_of_the_first_100_p.... One way of computing it in Python, using a loop approach like you did, is like so: sum = 0 for p in xrange(101): sum += p print (sum) This uses better variable names, and a simpler looping construct. The reason for the 101 is because it starts at 0.
- colbyolson 17y agoVery neat, thank you for your reply. I knew of the shortcut to increment a variable, but I had no idea you didn't have to declare one for a loop. I also didn't not know of xrange, I will have to look that one up.
- jacquesm 17y agoShouldn't that be print ((n-1)*n)/2
- jeroen 17y agoThat's not entirely right. It should be: print ((n+1)*n)/2 (fold the sequence in half, which gives you 100 + 1 on one end and 50 + 51 on the other.)
- jacquesm 17y agoAh right, sure. I took the 'n' to be the 100, not the 101. A little too quick on the submit there, I should have run it :) But anyway, that seems to be a damn sight faster than to run a loop to add a bunch of numbers in a fixed interval. Especially for large 'n'.
- jeroen 17y agoProbably much faster, but also doing half the work yourself. It'll depend on the situation which is the better solution.
- derwiki 17y agoyou could use a list comprehension to do the same thing: print sum([x for x in xrange(101)]) although the n(n+1)/2 is probably the best, I'd just like to point that out because I wish someone would have pointed out list comprehensions to me earlier :)
- saurabh 17y agoreduce(lambda x, y: x+y, xrange(101))
- jey 17y ago"When in doubt, try it out!" You could easily verify the answer by hand for small numbers of shirts, then run your debugged code to compute the answer for 100 shirts.
- sireat 17y agoCorrect answer should be $5050 as per Dr. Gauss: http://en.wikipedia.org/wiki/Carl_Friedrich_Gauss http://en.wikipedia.org/wiki/Carl_Friedrich_Gauss