繁体   English   中英

Python:简单的 4 数求解器?

[英]Python: Simple 4 number Solver?

我正在尝试制作一个简单的 4 个数字的数字求解器。 求解器将“0”替换为 1-4 之间的数字。 一个分层网格中的所有数字必须是唯一的。

开始[2, 0, 3, 0]

最终结果应该是[2, 1, 3, 4][2, 4, 3, 1]

我需要知道如何创建一个循环来做到这一点? 循环应该检查 0 并用正确的数字替换它们,循环 1-4,然后打印正确的网格列表。

import numpy as np

grid = [2, 0, 3, 0]
        
#checks that the number is not the same as existing number 
def possible(y,n):
    if grid[y] == n:
        return False
    else:
        return True

# loop that checks all 4 numbers and then replaces the 0's with the correct number    
for num in grid:  
    if possible == False:
        for n in grid(1,4):
            print(grid)

这将为 output 提供一个有效的解决方案:

grid = [2, 0, 3, 0]
all_nums = {1,2,3,4}
for i in range(len(grid)):
    if grid[i] == 0:
        non_zero_numbers_already_taken = set()
        for j in range(len(grid)):
            if grid[j] != 0:
                non_zero_numbers_already_taken.add(grid[j])
        # assigns an available number to replace the 0 at index i
        grid[i] = (all_nums - non_zero_numbers_already_taken).pop()
print(grid) 
# output : [2, 1, 3, 4]

您可以将逻辑调整为 output 所有可能的解决方案。

这是另一种选择

    def replace_zeros(plist):
        numbers = [4,3,2,1]
        outcome = []
        for num in plist:
            if num in numbers:
                numbers.remove(num)

        print(f'these are the missing numbers: {numbers}')
        for num in plist:
            if num == 0:
                outcome.append(numbers.pop())
            else:
                outcome.append(num)
        return outcome

    new_grid = replace_zeros([1,0,3,0])
    print(new_grid)
    #these are the missing numbers: [4,2]
    # [1,2,3,4]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM