繁体   English   中英

如何在 Python 中使用运算符排列?

[英]How to use a permutation of operators in Python?

我在报纸上看到了这个谜题,你得到了 5 个数字(8、5、2、6、3)。 问题是您必须按什么顺序在数字之间放置运算符(+、-、*、/)以获得最大的结果。 您不能更改数字的顺序,您必须使用每个运算符一次。

这是我学习编码的第二周。 我在下面创建了解决方案。 它正在工作,但实际计算看起来并不干净。 你能帮我找到更清洁的方法吗?

另外,如果您对优化代码的 rest 有任何建议,请告诉我。 非常感谢您的帮助!

(PS:我知道这个解决方案不尊重运算符的数学顺序。它只是从左到右读取。但首先我试图清理简单的版本。然后我会尝试让它更复杂。 )

from itertools import permutations
import operator

ops = {'+' : operator.add, '-' : operator.sub, '*' : operator.mul, '/' : operator.truediv} #Dict necessary to make the formula work.
perm = permutations(["+","-","*","/"]) #Store all possible combinations of the four operators in a tuple.

getallen=[]

def input_split(getallen): #Split the string inputted by the user into separate integers.
    lijst_2=[]
    lijst = getallen.split(",")
    for i in lijst:
        lijst_2.append(int(i))
    return lijst_2

def determine_max (getallen, perm): #Test which order of operators returns the highest number.
    maximum=0
    for i in perm: 
        temp_max = ops[f"{i[3]}"](ops[f"{i[2]}"](ops[f"{i[1]}"](ops[f"{i[0]}"](getallen[0], getallen[1]), getallen[2]), getallen[3]), getallen[4])
        if temp_max > maximum:
            maximum = temp_max
        else:
            pass

    return maximum

getallen = input("Give 5 comma separated numbers\n")
getallen = input_split(getallen)
max_output = determine_max (getallen, perm)
print(max_output)

排列(可迭代,r=None)

返回可迭代中元素的连续 r 长度排列。

这是我的 get_maximum 代码

from itertools import permutations

def get_maximum(number):

    lst = list(map(list, permutations(operator, 4)))
    result = []
    for item in lst:
        item_list = [str(number[0])]
        for i in range(4):
            item_list.append(item[i])
            item_list.append(str(number[i+1]))
        expression = ''.join(item_list)
        result.append((expression, eval(expression)))

    solution = sorted(result, key=lambda x:x[1], reverse=True)

    return solution[0]

number = (8, 5, 2, 6, 3)
operator = ['+','-', '*', '/']
print(get_maximum(number))    # ('8*5-2/6+3', 42.666666666666664)

暂无
暂无

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

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