在Python中对数字列表应用算术运算而不重复

2024-06-03

我们有以下 python 列表:[1,2,3,10]我想完成以下任务:创建一个函数,该函数接受列表并从算术运算列表中计算出来:['+', '-', '/','*']哪些组合给出的答案是 6。我们不想重复,所以我们不想2*3 and 3*2在我们的解决方案中。我们确实想列出我们没有使用过的数字(这里是 1 和 10)。同样适用于2/1*3=6.0, 2*3/1=6.0, 3/1*2=6.0, 3*2/1=6.0都被认为是等价的,因为无论操作如何,我们都使用相同的数字,并且没有使用 10。我希望该函数足够通用,以便我可以从那里使用它来处理从 1 到 9 的数字。 感谢您的帮助。我尝试使用 itertools 和排列来获取所有可能组合的列表,但这似乎没有必要并产生以下问题:2/1*3=6.0, 2*3/1=6.0, 3/1*2=6.0, 3*2/1=6.0包含在列表中,并且很难过滤掉。

我使用 itertools 的示例:


from itertools import chain, permutations

def powerset(iterable):
  xs = list(iterable)
  return chain.from_iterable(permutations(xs,n) for n in range(len(xs)+1) )

lst_expr = []
for operands in map(list, powerset(['1','2','3','10'])):
    n = len(operands)
    #print operands
    if n > 1:
        all_operators = map(list, permutations(['+','-','*','/'],n-1))
        #print all_operators, operands
        for operators in all_operators:
            exp = operands[0]
            i = 1
            for operator in operators:
                exp += operator + operands[i]
                i += 1

            lst_expr += [exp]

lst_stages=[]

for equation in lst_expr:
    if eval(equation) == 6:
        lst_stages.append(equation)
        eq = str(equation) + '=' + str(eval(equation))
        print(eq)

我喜欢 sanyash 的解决方案,但我认为通过使用操作数组合并进行排列可以更优雅地完成,直到找到第一个具有正确值的值:

from itertools import chain, permutations, combinations


def powerset(iterable):
    xs = list(iterable)
    return chain.from_iterable(combinations(xs, n) for n in range(len(xs) + 1))

def get_first_perm_with_value(operands, operators, expected_value):
    if len(operands) == 0 or len(operands) == 0:
        return []

    all_operators = list(map(list, permutations(operators, len(operands) - 1)))
    all_operands = list(map(list, permutations(operands, len(operands))))

    for operator in all_operators:
        for operand in all_operands:
            result = [""] * (len(operand) + len(operator))
            result[::2] = operand
            result[1::2] = operator
            eq = ''.join(result)
            if int(eval(eq)) == expected_value:
                return [(f'{eq}={expected_value}', operands)]
    return []


lst_expr = []
for operands in map(list, powerset(['1', '2', '3', '10'])):
    lst_expr += get_first_perm_with_value(operands, ['+','-','*','/'], 6)

print(lst_expr)

Returns:

[('2*3=6', ['2', '3']), ('2*3/1=6', ['1', '2', '3']), ('1+10/2=6', ['1', '2', '10']), ('2*10/3=6', ['2', '3', '10']), ('2*3+1/10=6', ['1', '2', '3', '10'])]
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在Python中对数字列表应用算术运算而不重复 的相关文章

随机推荐