我下面的代码被一个随机点卡住了:
import functions
from itertools import product
from random import randrange
values = {}
tables = {}
letters = "abcdefghi"
nums = "123456789"
for x in product(letters, nums): #unnecessary
values[x[0] + x[1]] = 0
for x in product(nums, letters): #unnecessary
tables[x[0] + x[1]] = 0
for line_cnt in range(1,10):
for column_cnt in range(1,10):
num = randrange(1,10)
table_cnt = functions.which_table(line_cnt, column_cnt) #Returns a number identifying the table considered
#gets the values already in the line and column and table considered
line = [y for x,y in values.items() if x.startswith(letters[line_cnt-1])]
column = [y for x,y in values.items() if x.endswith(nums[column_cnt-1])]
table = [x for x,y in tables.items() if x.startswith(str(table_cnt))]
#if num is not contained in any of these then it's acceptable, otherwise find another number
while num in line or num in column or num in table:
num = randrange(1,10)
values[letters[line_cnt-1] + nums[column_cnt-1]] = num #Assign the number to the values dictionary
print(line_cnt) #debug
print(sorted(values)) #debug
正如您所看到的,它是一个使用两个字典生成随机数独方案的程序:包含完整方案的值和包含每个表的值的表。你知道吗
示例:
5th square on the first line = 3
|
v
values["a5"] = 3
tables["2b"] = 3
那么问题是什么呢?我错过什么了吗?你知道吗
当我们可以在自己的计算机上执行代码来测试它时,这很好。换言之,在本例中,最好用固定值替换“table\u cnt”(在这里,一个简单的字符串就足够了)。你知道吗
没那么重要,但这更优雅:
现在,问题的核心是:
这是你永远循环的地方。所以,你在尝试生成一个随机数独。根据您的代码,以下是生成随机列表的方法:
这种方法的问题是你不知道程序需要多长时间才能完成。这可能需要一秒钟或一年的时间(不过,这不太可能)。这是因为无法保证程序不会不断地挑选一个已经接受的号码,一遍又一遍。你知道吗
不过,在实践中,它仍然需要相对较短的时间来完成(这种方法效率不高,但列表非常短)。然而,在数独的情况下,你可能会在一个不可能的设置结束。例如:
其中,它们是第一行(或任何实际行)和最后一列。当算法试图为第[8]行找到一个值时,它总是会失败,因为7被
column
阻塞。你知道吗如果你想保持这种方式(又名暴力),你应该发现这样的情况,并重新开始。同样,这是非常不够的,你应该看看如何正确地生成数独(我天真的方法是从一个已解决的数独开始,随机交换行和列,但我知道这不是一个好方法)。你知道吗
相关问题 更多 >
编程相关推荐