-1

There is a question like that:

1 X2 X 3 X 4 X 5 X 6 X 7 X 8 X 9 = 1942

X = must be x,+,-,÷ operators or nothing(89, 123 could be etc.)

How can i solve this problem with python?

Thanks.

ersan
  • 393
  • 1
  • 9
  • 1
    try this https://stackoverflow.com/questions/594266/equation-parsing-in-python – Dickens A S Mar 31 '20 at 10:53
  • 1
    How would you go about solving this in the first place? When you have an idea, translate that into Python. When you get stuck, you can ask here for help. Be sure to include code when asking your question. – Bart Kiers Mar 31 '20 at 10:54
  • Is this a challenge from Project Euler? – Yes Mar 31 '20 at 10:54
  • i am not sure @Yes . My friend asked me. He faced in a intelligence test challenge. – ersan Mar 31 '20 at 10:58

2 Answers2

2

You can start with something like this:

from itertools import product
target = 1942
test_str = "1{0[0]}2{0[1]}3{0[2]}4{0[3]}5{0[4]}6{0[5]}7{0[6]}8{0[7]}9"
for a in product(["*", "", "+", "/", "-", ""], repeat=8): # Iterate all posibilites
  result_str = test_str.format(a)
  if eval(result_str) == target:
    print(result_str)
    break

And optimize and make it more expandable to more numbers. But for your specific problem this works fine. I found this solution:

1*2/3+4*56*78/9

Take a look at eval if you need more information.

Raserhin
  • 2,516
  • 1
  • 10
  • 14
0

You can use parser module from python

import parser
formula = "1 + 2 + 3 + 4 + 5 * 6 * 7 * 8 * 9"
code = parser.expr(formula).compile()
print eval(code)
Dickens A S
  • 3,824
  • 2
  • 22
  • 45