因为循环卡在Python中

2024-04-23 14:08:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我下面的代码被一个随机点卡住了:

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

那么问题是什么呢?我错过什么了吗?你知道吗


Tags: theinimportfortablesiflinetable
1条回答
网友
1楼 · 发布于 2024-04-23 14:08:29
import functions
...
        table_cnt = functions.which_table(line_cnt, column_cnt) #Returns a number identifying the table considered

当我们可以在自己的计算机上执行代码来测试它时,这很好。换言之,在本例中,最好用固定值替换“table\u cnt”(在这里,一个简单的字符串就足够了)。你知道吗

for x in product(letters, nums):
    values[x[0] + x[1]] = 0

没那么重要,但这更优雅:

values = {x+y: 0 for x, y in product(letters, nums)}

现在,问题的核心是:

while num in line or num in column or num in table:
    num = randrange(1,10)

这是你永远循环的地方。所以,你在尝试生成一个随机数独。根据您的代码,以下是生成随机列表的方法:

nums = []
for _ in range(9):
    num = randrange(1, 10)
    while num in nums:
        num = randrange(1, 10)
    nums.append(num)

这种方法的问题是你不知道程序需要多长时间才能完成。这可能需要一秒钟或一年的时间(不过,这不太可能)。这是因为无法保证程序不会不断地挑选一个已经接受的号码,一遍又一遍。你知道吗

不过,在实践中,它仍然需要相对较短的时间来完成(这种方法效率不高,但列表非常短)。然而,在数独的情况下,你可能会在一个不可能的设置结束。例如:

line = [6, 9, 1, 2, 3, 4, 5, 8, 0]
column = [0, 0, 0, 0, 7, 0, 0, 0, 0]

其中,它们是第一行(或任何实际行)和最后一列。当算法试图为第[8]行找到一个值时,它总是会失败,因为7被column阻塞。你知道吗

如果你想保持这种方式(又名暴力),你应该发现这样的情况,并重新开始。同样,这是非常不够的,你应该看看如何正确地生成数独(我天真的方法是从一个已解决的数独开始,随机交换行和列,但我知道这不是一个好方法)。你知道吗

相关问题 更多 >