[Tutor] A file containing a string of 1 billion random digits.

Dave Angel davea at ieee.org
Sat Jul 17 22:56:52 CEST 2010


Richard D. Moores wrote:
> That's the goal of the latest version of my script at
> <http://tutoree7.pastebin.com/5XYaaNfp>. The best I've been able to do
> so far is a file with 800 million digits.
>
> But it seems the writing of 800 million digits is the limit for the
> amount of memory my laptop has (4 GB). So my question is, how can I do
> this differently? I'm pretty brand new to opening and writing files.
> Here, I can't write many shorter lines, because the end result I seek
> is one long string. But am I correct?
>
> I'd appreciate any advice.
>
> BTW line 29 was added after getting the outputs noted at the bottom of
> the script. Using close() does seem to shorten the time it takes for
> my laptop to become usable again, but it's not decisive. Sometimes I
> have to reboot in order to get healthy again. (64-bit Vista).
>
> BTW2 It's probably not obvious why the list comprehension (line 19)
> has random.choice(d) where d is '0123456789'. Without that, the random
> ints of 1000 digits would never begin with a '0'. So I give them a
> chance to by prefixing one random digit using choice(d), and cutting
> the length of the rest from 1000 to 999.
>
> Dick
>
>   
Your code is both far more complex than it need be, and inaccurate in 
the stated goal of producing random digits.

There's no need to try to have all the "digits" in memory at the same 
time.  As others have pointed out, since you're using write() method, 
there's no newline automatically added, so there's no problem in writing 
a few bytes at a time.

Your concern over a leading zero applies equally to two leading zeroes, 
or three, or whatever.  So instead of using str() to convert an int to a 
string, use string formatting.  Either the % operator or the format() 
method.  Just use a format that guarantees zero-filling to the same 
width field as the size limit you supplied.

So generate a number between 0 and 9999999999, or whatever, and convert 
that to a fixed width string possibly containing leading zeros.  Write 
the string out, and loop back around.

DaveA



More information about the Tutor mailing list