Skip to content
Advertisement

How to convert ‘+’ into + in Python

I’m willing to make a program that evaluates all possible combinations of operations ( + , – , * , / ) on a set of positive integers of length 6 (eg : [1, 6, 3, 9, 2, 9] ).

To do so, I am using the list

symbols = ['+', '-', '*', '/']

and wrote a nested loop to create all possibilities

+ + + + +
+ + + + -
.
.
.
/ / / / *
/ / / / /

by calling each row (eg : + – + * / ) a motif, and M the set of all motifs where

M[0] = ['+', '+', '+', '+', '+']
M[1] = ['+', '+', '+', '+', '-']

and so on. My goal now would be to write a function

evaluate_expression(motif, a, b, c, d, e, f)

that spits out the result of the expression a motif[0] b motif[1] c motif[2] d motif[3] e motif[4] f

my idea was to try converting ‘+’ into the symbol + but I couldn’t find a way to do it, I hope some of you guys here would know how to do that, I’m open to any suggestion of modification to make this cleaner.

Advertisement

Answer

The operator library gives you functions for the basic operators (e.g. add(), sub())

So, you could replace your symbols = ['+', '-', '*', '/'] with:

from operator import add, sub, mul, truediv
symbols = [add, sub, mul, truediv]

and now your motif-generating function should make lists of functions instead of lists of strings.

Then, assuming you have a motif list, as you call it (check out itertools.combinations_with_replacement() for a function to generate all motifs), you can apply it by doing something like:

motif = [add, add, sub]
values = [5, 6, 7, 8]
 
result = values[0]
for i, current_func in enumerate(motif):
    result = current_func(result, value[i+1])

print(result)

Note: this method will not respect order of operations, it will apply the functions in order, left to right.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement