1

I saw some examples of getting combinations of "operations" and "numbers" as well as "functions" and "numbers". But I was unable to combine all of them together.

import operator
import itertools 

numbers = [9, 0, 1]
operators = ['+', '-']
funcs = [math.log, math.exp]

for v1, v2 in itertools.permutations(numbers, 2):
    for op, fn  in itertools.product(operators, funcs):
        print(f"{op}({v1}, {fn}({v2})) =", op(v1, fn(v2)))

The above is an example code to get combinations for a value and a function but this is not what I want.

Combinations of Numbers and Operators - This link provides a suitable method to combine all numbers and operators.

Now, how do I combine everything and get output like:

9 + log(1)
0 + exp(9)
1 - exp(9) + log(0)
1 + log(9+0)
9 - exp(0+1)
...

Note: Operators can be re-used but not the 'numbers'.

All possible combinations need to be listed.

Any solutions will be greatly appreciated :) I am stuck in solving this!!

Ravi
  • 11
  • 3

1 Answers1

0

Firstly, Note that log(0) is Undefined!

Try this one, using eval function.

import itertools 
import math

numbers = ['9', '0', '1']
operators = ['+', '-']
funcs = ['math.log', 'math.exp', '']

for n1, n2 ,n3 in itertools.permutations(numbers, 3):
  for op1, op2 in itertools.product(operators,operators): 
    for f1, f2, f3 in itertools.product(funcs,funcs,funcs):
      expresion=f"{f1}({n1}) {op1} {f2}({n2}) {op2} {f3}({n3})"
      if not "math.log(0)" in expresion:
        result=eval(expresion)
        print(f"{expresion} = {result}")

[Output]

math.log(9) + math.exp(0) + math.log(1) = 3.1972245773362196
math.log(9) + math.exp(0) + math.exp(1) = 5.915506405795265
math.log(9) + math.exp(0) + (1) = 4.19722457733622
math.log(9) + (0) + math.log(1) = 2.1972245773362196
math.log(9) + (0) + math.exp(1) = 4.915506405795265
math.log(9) + (0) + (1) = 3.1972245773362196
math.exp(9) + math.exp(0) + math.log(1) = 8104.083927575384
...
AziMez
  • 2,014
  • 1
  • 6
  • 16
  • Thank you for responding AziMez. But this wouldn't give me combinations just for 2 at a time like 9+0; 1-9; 9 + log(1) etc. All the lists can be of any number of elements. – Ravi Oct 14 '22 at 19:37