我正在尝试通过将while循环替换为while循环来转换代码。
这是我要转换的代码
以下代码段中的代码功能。 @Sameer询问
from random import sample
def shuffle(s): return sample(s,len(s))
rBase = range(base)
base = 2
side = base*base
def pattern(r,c):
return (base*(r%base)+r//base+c)%side
我遇到问题的代码
rows = []
cols = []
data = []
for r in shuffle(rBase):
for g in shuffle(rBase):
rows.append(g*base+r)
for c in shuffle(rBase):
for g in shuffle(rBase):
cols.append(g*base+c)
nums = shuffle(range(1,side+1))
for r in rows:
for c in cols:
data.append(nums[pattern(r,c)])
这是我尝试输入的代码
rows = []
cols = []
data = []
s = shuffle(rBase)
i,j = 0,0
while i < len(s):
r = s[i]
while j < len(s):
s2 = shuffle(rBase)
g = s2[i]
rows.append(g*base+r)
j+=1
i += 1
i,j = 0,0
s = shuffle(rBase)
while i < len(s):
c = s[i]
while j < len(s):
s2 = shuffle(rBase)
g = s2[i]
cols.append(g*base+c)
j += 1
i += 1
nums = shuffle(range(1,side+1))
i,j =0,0
while i < len(rows):
r = rows[i]
while j < len(cols):
c = cols[i]
data.append(nums[pattern(r,c)])
j += 1
i += 1
由于隐私原因,省略了部分代码。
预期的输出,即for循环代码段的输出是一个列表,该列表的长度(基数** 4)包含从1到基数** 2的每个数字,正好是基数** 2倍。
例如:
如果基数是2:
预期的输出将像[3, 2, 1, 4, 4, 1, 3, 2, 1, 4, 2, 3, 2, 3, 4, 1]
实际输出是一个长度为base的列表,每个元素都是1到base ** 2之间的一个随机数(包括base ** 2)。 例如: 如果基数是2: 实际输出类似于[1,1]或[2,2]或[3,3]或[4,4]
答案 0 :(得分:0)
应在内部while循环之前定义变量j = 0。目前,您的内部仅运行“ len”次,并且在第二个循环中使用“ i”编制索引,因此您应该在其中使用j。
这应该有效
from random import sample
def shuffle(s): return sample(s,len(s))
base = 2
rBase = range(base)
side = base*base
def pattern(r,c):
return (base*(r%base)+r//base+c)%side
rows = []
cols = []
data = []
for r in shuffle(rBase):
for g in shuffle(rBase):
rows.append(g*base+r)
for c in shuffle(rBase):
for g in shuffle(rBase):
cols.append(g*base+c)
print(rows)
print(cols)
nums = shuffle(range(1,side+1))
for r in rows:
for c in cols:
data.append(nums[pattern(r,c)])
print(data)
rows = []
cols = []
data = []
s = shuffle(rBase)
s2 = shuffle(rBase)
i = 0
while i < len(s):
r = s[i]
j = 0
while j < len(s):
g = s2[j]
j = j + 1
rows.append(g*base+r)
i = i + 1
i = 0
s = shuffle(rBase)
s2 = shuffle(rBase)
while i < len(s):
c = s[i]
j = 0
while j < len(s):
g = s2[j]
cols.append(g*base+c)
j += 1
i += 1
nums = shuffle(range(1,side+1))
i =0
while i < len(rows):
r = rows[i]
j = 0
while j < len(cols):
c = cols[j]
data.append(nums[pattern(r,c)])
j += 1
i += 1
print(rows)
print(cols)
print(data)