[英]Only the first array inside a 2D array being updated by function
我在下面編寫了這段代碼來創建一個隨機數獨拼圖網格:
import time
import random
import math
sudoLine = [0,0,0,0,0,0,0,0,0]
#Creating mainGrid, this is a blank sudoku grid which I will place the contents of the possibleNums array into in a random order for each line.
mainGrid = [
[0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0],
]
possibleNums = [1,2,3,4,5,6,7,8,9]
i = 0
#Grabbing the length of the possibleNums array and reducing it by 1 to get the index position of the last element.
length = len(possibleNums) - 1
def LineFill(line,nums,count):
length = len(nums) - 1
i = 0
while length > 0:
length = len(nums) - 1
r = random.randint(0,length)
line[i] = nums[r]
nums.pop(r)
i += 1
return line
n=0
然后這個 while 循環在其下方,並循環通過mainGrid
,每次都更改正在填充的數組:
while n in range(0,len(mainGrid)):
mainGrid[n] = LineFill(mainGrid[n],possibleNums,i)
n += 1
print(mainGrid)
當我運行它時,只有數獨網格的第一行被填充,這意味着只有列表中的第一個數組被更新,即使 while 循環應該循環遍歷它們。
有人可以指出我的邏輯錯誤嗎?
謝謝。
您的nums.pop()
行是問題所在。 您將possibleNums
作為LineFill
參數nums
傳遞。 所以nums
只是對possibleNums
的引用。 填完一行后, possibleNums
是一個空列表。
如果您的意圖是在任何給定行上隨機填充沒有重復的數字網格,這里有一個更簡單的方法:
In [1]: import random
In [2]: [random.sample(range(1, 10), 9) for _ in range(9)]
Out[2]:
[[3, 9, 8, 1, 2, 5, 6, 4, 7],
[6, 7, 3, 9, 2, 5, 8, 1, 4],
[4, 1, 9, 2, 7, 3, 5, 6, 8],
[3, 5, 9, 4, 2, 1, 7, 8, 6],
[7, 2, 8, 6, 1, 9, 4, 5, 3],
[1, 8, 5, 9, 4, 6, 2, 7, 3],
[8, 7, 1, 9, 2, 5, 3, 4, 6],
[7, 6, 1, 5, 4, 2, 9, 3, 8],
[7, 8, 4, 2, 5, 1, 6, 3, 9]]
請注意,這種方法不會產生有效的數獨解決方案(理論上是可能的,但可能性是......對你不利)——但無論如何,這似乎不是你想要做的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.