【问题标题】:How to list all solutions in 24 game using Python如何使用Python列出24个游戏中的所有解决方案
【发布时间】:2020-04-09 04:51:12
【问题描述】:

最近我用 python 创建了一个 24 游戏求解器
如果您不知道 24 游戏是什么,请阅读此网站: https://www.pagat.com/adders/24.html

代码如下:

from itertools import permutations, product, chain, zip_longest
from   fractions  import Fraction as F

solutions = []

def ask4():
    num1 = input("Enter First Number: ")
    num2 = input("Enter Second Number: ")
    num3 = input("Enter Third Number: ")
    num4 = input("Enter Fourth Number: ")
    digits = [num1, num2, num3, num4]
    return list(digits)

def solve(digits, solutions):
    digit_length = len(digits)
    expr_length = 2 * digit_length - 1
    digit_perm = sorted(set(permutations(digits)))
    op_comb = list(product('+-*/', repeat=digit_length-1))
    brackets = ([()] + [(x,y)
    for x in range(0, expr_length, 2)
    for y in range(x+4, expr_length+2, 2)
    if (x,y) != (0,expr_length+1)]
                 + [(0, 3+1, 4+2, 7+3)])
    for d in digit_perm:
        for ops in op_comb:
            if '/' in ops:
                d2 = [('F(%s)' % i) for i in d]
            else:
                d2 = d
            ex = list(chain.from_iterable(zip_longest(d2, ops, fillvalue='')))
            for b in brackets:
                exp = ex[::]
                for insert_point, bracket in zip(b, '()'*(len(b)//2)):
                    exp.insert(insert_point, bracket)
                txt = ''.join(exp)
                try:
                    num = eval(txt)
                except ZeroDivisionError:
                    continue
                if num == 24:
                    if '/' in ops:
                        exp = [(term if not term.startswith('F(') else term[2])
                               for term in exp]
                    ans = ' '.join(exp).rstrip()
                    print("Solution found:", ans)
                    solutions.extend(ans)
                    return ans
    print("No solution found for:", ' '.join(digits))

def main():
    digits = ask4()
    solve(digits, solutions)
    print(len(solutions))
    print("Bye")

main()

现在,我的代码只显示给定数字的一种解决方案,即使显然有更多解决方案。
所以如果有人知道如何做到这一点,请帮助我
谢谢

【问题讨论】:

    标签: python math itertools


    【解决方案1】:

    在计算并列出所有解决方案之前,您不允许代码完成其任务。最好将解决方案保存在列表/数组中,而不是立即返回。

    【讨论】:

      【解决方案2】:

      一旦找到解决方案,您的函数就会返回。删除返回语句。在循环之后,您可以根据需要返回所有解决方案的列表。要检查是否没有解决方案,请查看列表的长度是否为零(这样您就知道什么时候说没有解决方案了)。

      我还建议将solutions 设为本地到solve,而不是全局。

      【讨论】:

        猜你喜欢
        • 2020-06-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-02-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多