Applying arithmetic operations on list of numbers without repetition in python

核能气质少年 提交于 2019-12-10 22:18:01

问题


We've got the following python list: [1,2,3,10] I would like to accomplish the following: Create a function that takes in the list and figures out from the list of arithmetic operations: ['+', '-', '/','*'] which combinations give us 6 as the answer. We don't want repetition so we don't want 2*3 and 3*2 in our solution. We do want to list the numbers we haven't used so that's (1 and 10 here). Same for 2/1*3=6.0, 2*3/1=6.0, 3/1*2=6.0, 3*2/1=6.0 are all considered equivalent since we use the same numbers regardless of operations and have not used 10. I want the function to be general enough so that I can use it from there for numbers from 1 to 9. Your help is appreciated. I tried using itertools and permutation to get a list of all possible combinations but this seems unnecessary and produces the problem that 2/1*3=6.0, 2*3/1=6.0, 3/1*2=6.0, 3*2/1=6.0 are included in the list and this is difficult to filter out.

Example where I got using 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)

回答1:


Here is possible solution. We need to keep a sorted tuple of used numbers to avoid duplicates like 2*3 and 3*2.

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]
            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) == 6:
        lst_stages.append(equation)
        eq = str(equation) + '=' + str(eval(equation))
        print(eq, numbers)
        numbers_sets.add(numbers)

Output:

2*3=6 ('2', '3')
1+10/2=6.0 ('1', '10', '2')
2/1*3=6.0 ('1', '2', '3')



回答2:


I like sanyash's solution, but I think it can be done more elegantly, by using combinations of operands and than taking permutations, until the first with the right value is found:

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'])]


来源:https://stackoverflow.com/questions/58078750/applying-arithmetic-operations-on-list-of-numbers-without-repetition-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!