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

JavaScript

and wrote a nested loop to create all possibilities

JavaScript

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

JavaScript

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

JavaScript

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:

JavaScript

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:

JavaScript

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