Skip to content Skip to sidebar Skip to footer

Applying Arithmetic Operations On List Of Numbers Without Repetition In Python

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 opera

Solution 1:

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

Solution 2:

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

defpowerset(iterable):
  xs = list(iterable)
  return chain.from_iterable(permutations(xs,n) for n inrange(len(xs)+1) )

lst_expr = []
for operands inmap(list, powerset(['1','2','3','10'])):
    n = len(operands)
    #print operandsif n > 1:
        all_operators = map(list, permutations(['+','-','*','/'],n-1))
        #print all_operators, operandsfor operators in all_operators:
            exp = operands[0]
            numbers = (operands[0],)
            i = 1for 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 notin numbers_sets andeval(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')

Post a Comment for "Applying Arithmetic Operations On List Of Numbers Without Repetition In Python"