[Tutor] OverflowError in lucky numbers script

Alan Gauld alan.gauld at btinternet.com
Sun Jan 22 19:24:16 CET 2012


On 22/01/12 11:37, Shreesh bhat wrote:

> Steven wrote:
> " Scale your numbers from time to time, to avoid them getting too big "
> What does this mean?

It could be done in various ways but one simple example is,

low = 10000000000
hi =  10000000010

for n in range(low,hi):
     ... code uses n ...

could also be written

span = hi-low
for n in range(span)  # ie. range(10)
     val = low + n
     .... code uses val ...

Now the value given to range is a very small number...
Of course if low is zero and hi is large you need to think
again, so maybe you can break the range into chunks (eg. what
about using the square root?)? And process each chunk as above?

As I say there are lots of ways to do it, you need to think of one that 
works for your data.

> inp refers to the sample input test case I have given at first.Its a
> string containing two numbers,

ok, so it contains the lo-hi pair?
Why not call it lo_hi

lo_hi = raw_input('Enter the low and high numbers')

Can you see how the combination of variable name and prompt string tells 
the reader what is going on?


> The program has to handle large numbers till 10**18 and also has to
> execute considerably fast (within 16 CPU time).

I can promise you it will never run in 16 clock cycles...

> Is writing my own generator only solution? Or is there another way in
> which i can generate big numbers and in considerably fast manner?

Your problem is to avoid generating very big numbers wherever possible.
Construct them for output as needed but do the processing using smaller 
ones. Just because Python supports arbitrarily large integers does not 
mean you should use them in every case...

HTH,

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/



More information about the Tutor mailing list