[Tutor] Data persistence problem

Wolfgang Maier wolfgang.maier at biologie.uni-freiburg.de
Fri Jun 21 16:32:21 CEST 2013


Arijit Ukil <arijit.ukil <at> tcs.com> writes:

> 
> I have following random number generation
> function
> def
> rand_int ():
>     rand_num = int(math.ceil
> (random.random()*1000))
>     return
> rand_num
> I like to make the value of rand_num
> (return of rand_int) static/ unchanged after first call even if it is called
> multiple times. If x=  rand_int () returns 45 at the first call, x
> should retain 45 even in multiple calls.

Sifting through the random module documentation a bit:

def rand_int(update=False):
    if update:
        dummy = random.random()
    oldstate=random.getstate()
    rand_num = random.randint(0,1000)
    random.setstate(oldstate)

    return rand_num

This will return a constant number when called with a False value for update
(the default), but will switch to returning a new number when called
with a True value once.

>>> rand_int()
644
>>> rand_int()
644
>>> rand_int(True)
120
>>> rand_int()
120
>>> rand_int()
120

Best, Wolfgang






More information about the Tutor mailing list