Python的24点


def permutations(array):
    permutations_list = []
    for first_num in array:
        array2 = array[:]
        array2.remove(first_num)
        for second_num in array2:
            array3 = array2[:]
            array3.remove(second_num)
            for third_num in array3:
                array4 = array3[:]
                array4.remove(third_num)
                forth_num = array4[0]
                permutations_list.append([first_num, second_num, third_num, forth_num])
    return permutations_list


def calc(lst):
    result = permutations(lst)
    operators = ["+", "-", "*", "/"]
    list2 = []

    for list1 in result:
        number1 = list1[0]
        number2 = list1[1]
        number3 = list1[2]
        number4 = list1[3]
        for operator1 in operators:
            for operator2 in operators:
                for operator3 in operators:
                    expression = [
                        "(({0}{1}{2}){3}{4}){5}{6}".format(number1, operator1, number2, operator2, number3,
                                                           operator3, number4),
                        "({0}{1}{2}){3}({4}{5}{6})".format(number1, operator1, number2, operator2, number3,
                                                           operator3, number4),
                        "(({0}{1}({2}{3}{4})){5}{6})".format(number1, operator1, number2, operator2, number3,
                                                             operator3, number4),
                        "{0}{1}(({2}{3}{4}){5}{6})".format(number1, operator1, number2, operator2, number3,
                                                           operator3, number4),
                        "{0}{1}({2}{3}({4}{5}{6}))".format(number1, operator1, number2, operator2, number3,
                                                           operator3, number4),
                        "{0}{1}{2}{3}{4}{5}{6}".format(number1, operator1, number2, operator2, number3,
                                                       operator3, number4)
                    ]

                    for e in expression:
                        try:
                            if round(eval(e), 2) == 24:
                                list2.append(e)
                        except ZeroDivisionError:
                            pass

    list3 = list(set(list2))
    return list3


num1 = int(input("请输入第1个数字:"))
num2 = int(input("请输入第2个数字:"))
num3 = int(input("请输入第3个数字:"))
num4 = int(input("请输入第4个数字:"))
num_list = [num1, num2, num3, num4]
result_list = calc(num_list)
if not result_list:
    print("无解")
else:
    for num3 in result_list:
        print("求解结果:", num3)


本站作者已申明原创,禁止转载!

文章内容属作者个人观点,不代表本站立场,如有侵权立删。

   口袋儿题库-青少儿编程自测题库