[Tutor] Data persistence problem
Wolfgang Maier
wolfgang.maier at biologie.uni-freiburg.de
Fri Jun 21 12:47:56 CEST 2013
Alan Gauld <alan.gauld <at> btinternet.com> writes:
>
> On 21/06/13 07:21, Arijit Ukil wrote:
> > I have following random number generation function
> >
> > def*rand_int* ():
> > rand_num = int(math.ceil (random.random()*1000))
> > returnrand_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.
>
> The simple solution is to store the value in a global variable.
>
> rand_num = None
>
> def rand_int():
> global rand_num
> if not rand_num:
> rand_num = int(math.ceil (random.random()*1000))
> return rand_num
>
> Or if you really don't like globals you could create
> a generator function:
>
> def rand_int():
> rand_num = int(math.ceil (random.random()*1000))
> while True:
> yield rand_num
>
> Incidentally, any reason why you don't use the random.randint() function
> rather than the int(ceil(...) stuff?
>
> HTH
a more general solution for random number generation is to use random.seed()
with a fixed argument:
def rand_int (seed=None):
random.seed(seed)
rand_num = int(math.ceil (random.random()*1000))
return rand_num
then call this with the same argument to obtain the same number. But as Alan
said using random.seed and random.randint is a much simpler choice.
Wolfgang
More information about the Tutor
mailing list