Python .seed和.randrange if-else语句设置

时间:2012-11-23 22:05:30

标签: python random random-seed

我的程序非常复杂,我在下面提供了一个更简单的版本:

while True:#This first part asks the user if he wants to run in deterministic mode(explained later) If he does then deterministic is given a value of 1, else, it is given a value of two.
    mode= input("Would you like to start the program in deterministic mode?(y/n)")
    for i in mode:
        if i not in ('yYnN'):
            print('Please enter either a \'y\' or an \'n\', Please try again')
            break
    else:
        break

if mode=='y' or mode== 'Y':
    deterministic= 1
elif mode=='n' or mode=='N':
    deterministic= 2

现在,下面是一些使用上述代码的代码。这是一个if-elif语句,如果确定性是== 1则函数将运行,如果确定性= = 2则将运行不同的函数。

        if deterministic==2:#position,time, and energy variables will come from the function updateDisplayAllVar(....)

            position,time,energy=updateDisplayAllVar(selection,position,time,energy)
        elif deterministic==1:#position,time, and energy variables will come from the function deterministic(....)

            position,time,energy=deterministic(selection,position,time,energy)

现在我将向您展示上述代码中的两个函数。我相信问题在于他们。第一个函数给出一个随机数,每次都可能有一个不同的随机数。第二个函数使用.seed每次将随机数限制为SAME“随机”数字。

def updateDisplayAllVar(选择,位置,时间,能量):

if selection=='w' or selection =='W':
    energy= energy
    position= position+1
    time=time+1
elif selection=='j' or selection =='J':
    energy= energy-1
    position= position+2
    time=time+1 
elif selection=='r' or selection =='R':
    energy= energy-random.randrange(1,2+1)
    position= position+random.randrange(1,4+1)
    time=time+1
elif selection=='f' or selection =='F':
    energy= energy- random.randrange(3,5+1)
    position= position+random.randrange(3,8+1)
    time=time+1



def deterministicMode(selection,position,time,energy):

    if selection=='w' or selection =='W':
        energy= energy
        position= position+1
        time=time+1
    elif selection=='j' or selection =='J':
        energy= energy-1
        position= position+2
        time=time+1 
    elif selection=='r' or selection =='R':
        random.seed(1)
        energy= energy-random.randrange(1,2+1)
        position= position+random.randrange(1,4+1)
        time=time+1
    elif selection=='f' or selection =='F':
        random.seed(3)
        energy= energy- random.randrange(3,5+1)
        position= position+random.randrange(3,8+1)
        time=time+1

现在我的问题是......用这个代码,即使我不选择确定性(无随机数)模式,我仍然得到非随机的数字,并且基于第二个函数。也就是说,即使有两个函数,我要求每个函数根据用户输入运行...它总是运行deterministicMode(selection,position,time,energy)。有没有人知道修复。如果有任何不清楚的地方,请告诉我,我会解决它。

1 个答案:

答案 0 :(得分:1)

使用当前系统时间重新种子RNG,使其再次“随机”:

def deterministicMode(selection,position,time,energy):
    random.seed()  # <-- Add this line right here

    if selection=='w' or selection =='W':
        energy= energy
        position= position+1
        time=time+