-1

Here's my python code. Could someone show me what's wrong with it? I try to learn an algorithm on solving 24 - point game. But I really don't know why this program has an error.

from __future__ import division
import itertools as it
__author__ = 'linchen'

fmtList=["((%d%s%d)%s%d)%s%d", "(%d%s%d)%s(%d%s%d)", 
"(%d%s(%d%s%d))%s%d", "%d%s((%d%s%d)%s%d)", "(%d%s(%d%s(%d%s%d))"]
opList=it.product(["+", "-", "*", "/"], repeat=3)


def ok(fmt, nums, ops):
    a, b, c, d=nums
    op1, op2, op3=ops
    expr=fmt % (a, op1, b, op2, c, op3, d)
    try:
        res=eval(expr)
    except ZeroDivisionError:
        return
    if 23.999< res < 24.001:
        print expr, "=24"

def calc24(numlist):
    [[ok(fmt, numlist, op) for fmt in fmtList] for op in opList]


for i in set(it.permutations([3,3,8,8])):
    calc24(i)

And Here's what happens:

Traceback (most recent call last):
  File "D:\Program Files\JetBrains\PyCharm 4.0.5\helpers\pydev\pydevd.py", line 2217, in <module>
    globals = debugger.run(setup['file'], None, None)
  File "D:\Program Files\JetBrains\PyCharm 4.0.5\helpers\pydev\pydevd.py", line 1643, in run
    pydev_imports.execfile(file, globals, locals)  # execute the script
  File "C:/Users/linchen/PycharmProjects/untitled/calc24.py", line 26, in <module>
    calc24(i)
  File "C:/Users/linchen/PycharmProjects/untitled/calc24.py", line 22, in calc24
    [[ok(fmt, numlist, op) for fmt in fmtList] for op in opList]
  File "C:/Users/linchen/PycharmProjects/untitled/calc24.py", line 15, in ok
    res=eval(expr)
  File "<string>", line 1
    (8+(3+(3+8))
               ^
SyntaxError: unexpected EOF while parsing

Could anyone told me how to fix this problem?

Tobbe
  • 1,825
  • 3
  • 21
  • 37
Moses Lin
  • 1
  • 1

1 Answers1

2

You're last fmtList item has unbalanced parenthesis:

"(%d%s(%d%s(%d%s%d))"

should be:

"(%d%s(%d%s(%d%s%d)))"

And that explains the traceback -- Python is looking for a closing parethesis -- instead it encounters and end of line (when using eval, the end of line is interpreted as "End Of File" or EOF) and so you get the error.

mgilson
  • 300,191
  • 65
  • 633
  • 696