到目前为止我已经完成了:
import numpy as np
import random
#helper function no. 1
def seed_probabilities(i,j):
rand_num = random.random()
x = 1/(abs(i - j) + 2)
if rand_num < x:
y = 1
else:
y = 0
return(y)
def create_world(nr, nc):
#make array
values = np.empty((nr,nc), dtype=int)
#index array
for i in range(0,nr):
for j in range(0, nc):
seed_probabilities(i,j)
np.append(values, y)
return(values)
create_world(6,7)
输出看起来像这样
array([[ 4128860, 6029375, 3801155, 5242972, 7274610, 7471207,7143521],[ 6357060, 6357108, 6357084, 6357102, 7274595, 6553710,3342433],[ 4980828, 6422633, 7536732, 7602281, 2949221, 6357104,7012451],[ 6750305, 7536741, 4784220, 7929936, 6815860, 7209071,6488156],[ 7471215, 6029413, 7209065, 6619252, 6357106, 7602275,7733353],[ 7536741, 6619240, 7077996, 7340078, 121, 538976288,538976288]])
但我需要它是 1 和 0。
基本上,xr 是数组中的行数,xc 是列数。辅助函数 seed_probabilities 生成 0 或 1,概率取决于 i 和 j,它们是相关数组的索引。任何帮助将不胜感激。
两个简单的问题。您没有分配给
y
,并且您使用了错误的 API 来构建数组。这有效:
import numpy as np
import random
def seed_probabilities(i,j):
rand_num = random.random()
x = 1/(abs(i - j) + 2)
return rand_num < x
def create_world(nr, nc):
values = np.empty((nr,nc), dtype=int)
for i in range(nr):
for j in range(nc):
values[i,j] = seed_probabilities(i,j)
return values
print(create_world(6,7))
输出:
[[0 0 0 0 0 0 1]
[0 0 0 0 0 0 1]
[1 0 0 0 0 0 0]
[0 0 1 1 0 1 0]
[1 0 0 0 0 1 0]
[0 0 0 0 1 1 0]]