Python-在具有重复操作数的数字列表上应用算术,但列表中没有数字

问题描述 投票:1回答:1

简而言之,我想:

  • 获取5个数字的列表,例如[40、1、3、4、20]
  • 具有所需的输出编号,例如42
  • 检查是否可以对5个数字的列表进行算术运算以提供所需的输出
  • [如果为true,则输出YES,如果为false,则输出NO,例如[4 * 20-40 + 3-1 = 42]因此应输出YES

我尝试从此处应用一些内容:Applying arithmetic operations on list of numbers without repetition in python

但是,我正在为允许重复的运算符]而苦苦挣扎,但是不允许列表中的值被多次操作

import sys

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(['40','1','3','4','20'])):    
    n = len(operands)
    if n > 1:
        all_operators = map(list, permutations(['+','-','*','/'],n-1))
        #print all_operators, operands
        for operators in all_operators:
            exp = operands[0]
            numbers = (operands[0],)
            i = 1
            for operator in operators:
                exp += operator + operands[i]
                numbers += (operands[i],)
                i += 1

            lst_expr += [{'exp': exp, 'numbers': tuple(sorted(numbers))}]

lst_stages=[]
numbers_sets = set()

for item in lst_expr:
    equation = item['exp']
    numbers = item['numbers']
    if numbers not in numbers_sets and eval(equation) == 42:
        lst_stages.append(equation)
        eq = str(equation) + '=' + str(eval(equation))
        print(eq, numbers)
        numbers_sets.add(numbers)

Output:
40-1+3=42 ('1', '3', '40')
40-3+20/4=42.0 ('20', '3', '4', '40')
40-1*3+20/4=42.0 ('1', '20', '3', '4', '40')

显然,我没有应用必须使用列表中所有值的度量,也没有更改它以允许单个运算符的多次使用。

简而言之,我想:抓取5个数字的列表,例如[40、1、3、4、20]具有所需的输出数字,例如42检查是否可以对5个数字的列表进行算术运算以给出所需的信息...

python python-3.x math itertools
1个回答
0
投票

permutations方法将不会返回重复的元素。您必须改用product

© www.soinside.com 2019 - 2024. All rights reserved.