Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
181 views
in Technique[技术] by (71.8m points)

Python unexpected EOF while parsing (python2.7)

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...