![](/img/trans.png)
[英]Replace some data with random generated number that follows the particular distribution
[英]How can I code a sample of random numbers from a list, so that each number generated follows some condition depending on the preceding number?
示例:如果樣本中的第一個數字是 1,則下一個數字只能是 2、4 或 5;如果第二個數字是 2,則下一個數字只能是 1、3、4、5 或 6。對於列表中的所有數字,這將繼續。
我嘗試使用這個:
import random
num_list = [1,2,3,4,5,6,7,8,9]
new_sample = random.sample(num_list, 5)
print (new_sample)
但是,我似乎無法操縱此代碼以使其符合我需要的條件。 任何幫助將不勝感激。
編輯:條件中的模式有點難以解釋。 數字 1 到 9 來自一個 3 x 3 網格點,按從左到右、從上到下的順序編號。 我正在嘗試模擬隨機模式,以便您只能連接相鄰的點。
如果前面的數字 (PN) = 1,則下一個數字 (NN) = 2、4 或 5,如果 PN = 2,則 NN = 1、3、4、5 或 6,如果 PN = 3,則 NN = 2 , 5, 6, 如果 PN = 4,則 NN = 1、2、5、7 或 8,如果 PN = 5,則 NN = 1、2、3、4、6、7、8 或 9,依此類推。
我認為這會起作用(在 Python 3 中):
import random
x_arr=[]
y_arr=[]
def addTolist(m,n):
x_arr.append(m)
y_arr.append(n)
grid = [[1,2,3],[4,5,6],[7,8,9]]
new_sample = random.sample(range(1,10), 5) # to generate random list of 5 numbers
current = random.choice(new_sample) # take random number from list of 5 numbers
for i in range(3): # to position of number in the grid
for j in range(3):
if current == grid[i][j]:
x = i
y = j
break
num = [current] # to store the unique random numbers
for i in range(4): # loop till we find the 5 th number
print('current:',current)
# every time empty the list
neighbours = []
x_arr=[]
y_arr=[]
# to choose the neighbours of current number (maximum 8 neighbours)
if y-1 >= 0:
neighbours.append(grid[x][y-1])
addTolist(x,y-1)
if x+1 < 3:
neighbours.append(grid[x+1][y-1])
addTolist(x+1,y-1)
if x-1 >= 0:
neighbours.append(grid[x-1][y-1])
addTolist(x-1,y-1)
if x-1 >= 0:
neighbours.append(grid[x-1][y])
addTolist(x-1,y)
if y+1 < 3:
neighbours.append(grid[x-1][y+1])
addTolist(x-1,y+1)
if y+1 < 3:
neighbours.append(grid[x][y+1])
addTolist(x,y+1)
if x+1 < 3:
neighbours.append(grid[x+1][y+1])
addTolist(x+1,y+1)
if x+1 < 3:
neighbours.append(grid[x+1][y])
addTolist(x+1,y)
current = random.choice(neighbours)
while current in num: # till unique random number is not generted
current = random.choice(neighbours)
num.append(current)
position = neighbours.index(current)
x = x_arr[position]
y = y_arr[position]
print("x position:",x_arr)
print("y position:",y_arr)
print("neighbours:",neighbours)
print("Final Number : ",current)
輸出:
current: 7
x position: [1, 1, 2]
y position: [0, 1, 1]
neighbours: [4, 5, 8]
current: 4
x position: [0, 0, 1, 2, 2]
y position: [0, 1, 1, 1, 0]
neighbours: [1, 2, 5, 8, 7]
current: 5
x position: [1, 2, 0, 0, 0, 1, 2, 2]
y position: [0, 0, 0, 1, 2, 2, 2, 1]
neighbours: [4, 7, 1, 2, 3, 6, 9, 8]
current: 8
x position: [2, 1, 1, 1, 2]
y position: [0, 0, 1, 2, 2]
neighbours: [7, 4, 5, 6, 9]
Final Number : 9
假設:網格是 3*3 並且您必須始終找到第 5 個唯一隨機數。
它有點長,但我必須檢查3*3
網格中的所有鄰居。 所以我采用grid
變量,它是grid
中的列表編號列表,類似於2D array 。 我認為所有剩余的代碼都是不言自明的。
希望這會幫助你。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.