performance problem in python 2.2

Paul Rubin phr-n2002b at NOSPAMnightsong.com
Fri Jul 26 17:04:25 EDT 2002


Jeff Davis <jdavis at empires.org> writes:
> c = long(sys.argv[1],10)
> 
> for i in range(1,c):
>     n = (n * (p-i)) / p
> print 1-n

The problem is range(1,c) builds up a c-element list in memory.  Use
xrange instead, which makes an object holding only the current
iteration value.

For extra credit, solve the problem without a computer.  E.g., suppose
you want to know the sum 1+2+3+...+999+1000.  You can add it up with a
program or you can do it without a computer with a little cleverness.

Solving your birthday paradox problem needs a little bit more math
than 1+2+3+...+1000, and the answer you get will be a close
approximation rather than exact, but with similar cleverness you
should be able to get a fairly simple formula.



More information about the Python-list mailing list