Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 FilesJetBrainsPyCharm 4.0.5helperspydevpydevd.py", line 2217, in <module>
    globals = debugger.run(setup['file'], None, None)
  File "D:Program FilesJetBrainsPyCharm 4.0.5helperspydevpydevd.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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
175 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...