我試圖制作一個程式,考慮一個變數的數量(隨機選擇)來決定下一個變數的值,我需要重復這 11 次(所以 n3 將取決于 n2、n3 的 n4 等。 ) 這個想法是這樣的代碼:
def rayuela_cuerpo():
n2 = random.choice([0,1])
if n2 == 0:
n3 = random.choice([1,3])
return n3
elif n2 == 1:
n3 = random.choice([0,2])
return n3
if n3 == 0 or n3 == 1:
n4 = random.choice([1,3])
return n4
elif n3 == 2 or n3 == 3:
n4 = random.choice([0,2])
return n4
if n3 == 0 or n3 == 1:
n4 = random.choice([1,3])
return n4
elif n3 == 2 or n3 == 3:
n4 = random.choice([0,2])
return n4
但它會起作用。
uj5u.com熱心網友回復:
你可以做你所說的一種方法是:
def random_simulation(entry_number): # generate a random number based on the input number given to the function
if entry_number == 0:
return random.choice([1,3]) # returns the value to where this function was called
elif entry_number == 1:
return random.choice([0,2]) # returns the value to where this function was called
def rayuela_cuerpo():
origin_number = 0
for _ in range(11): # run through the function 11 times and update the value for the next time the function is run
origin_number = random_simulation(origin_number)
return origin_number # return the last number to be generated from the for loop
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/517548.html
標籤:Python变量随机的
