Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

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)


Nope, 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_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.


Very 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.


Shouldn't that be

   print ((n-1)*n)/2


That'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.)


Ah 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'.


Probably much faster, but also doing half the work yourself. It'll depend on the situation which is the better solution.


you 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 :)


Correct answer should be $5050 as per Dr. Gauss: http://en.wikipedia.org/wiki/Carl_Friedrich_Gauss


"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.


reduce(lambda x, y: x+y, xrange(101))




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: