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?
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.
Related
I'm trying to convert a list of string into SymPy expression objects using the sympy.sympify() function. However, it doesn't take double backslashes.
May I know how to solve this?
list_of_strings = ['\\phi G \\rightarrow H', '\\phi ( A )', '\\alpha _ { 0 } , \\ldots , \\alpha _ { m - 1 } \\in F']
expr = sympy.sympify(list_of_strings[0])
ValueError: Error from parse_expr with transformed code: "\\Symbol ('phi' )Symbol ('G' ) \\Symbol ('rightarrow' )Symbol ('H' )"
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/Users/dennislau/Desktop/GoodNotes/Math/math_data_collection/venv/lib/python3.8/site-packages/sympy/core/sympify.py", line 496, in sympify
expr = parse_expr(a, local_dict=locals, transformations=transformations, evaluate=evaluate)
File "/Users/dennislau/Desktop/GoodNotes/Math/math_data_collection/venv/lib/python3.8/site-packages/sympy/parsing/sympy_parser.py", line 1101, in parse_expr
raise e from ValueError(f"Error from parse_expr with transformed code: {code!r}")
File "/Users/dennislau/Desktop/GoodNotes/Math/math_data_collection/venv/lib/python3.8/site-packages/sympy/parsing/sympy_parser.py", line 1092, in parse_expr
rv = eval_expr(code, local_dict, global_dict)
File "/Users/dennislau/Desktop/GoodNotes/Math/math_data_collection/venv/lib/python3.8/site-packages/sympy/parsing/sympy_parser.py", line 907, in eval_expr
expr = eval(
File "<string>", line 1
\Symbol ('phi' )Symbol ('G' ) \Symbol ('rightarrow' )Symbol ('H' )
^
SyntaxError: unexpected character after line continuation character
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/code.py", line 90, in runcode
exec(code, self.locals)
File "<input>", line 2, in <module>
File "/Users/dennislau/Desktop/GoodNotes/Math/math_data_collection/venv/lib/python3.8/site-packages/sympy/core/sympify.py", line 498, in sympify
raise SympifyError('could not parse %r' % a, exc)
sympy.core.sympify.SympifyError: Sympify of expression 'could not parse '\\phi G \\rightarrow H'' failed, because of exception being raised:
SyntaxError: unexpected character after line continuation character (<string>, line 1)
I tried replace the double backslahes into single backslash but still doesn't work.
The following code:
eng = matlab.engine.start_matlab()
eng.eval('i=1;', nargout=0)
eng.eval('while i<10', nargout=0)
eng.eval('i=i+1', nargout=0)
eng.eval('end;', nargout=0)
eng.quit()
always shows the following error:
Traceback (most recent call last):
File "while.py", line 13, in <module>
main()
File "while.py", line 7, in main
eng.eval('while i<10', nargout=0)
File "/Library/Python/2.7/site-packages/matlab/engine/matlabengine.py", line 84, in __call__
_stderr, feval=True).result()
File "/Library/Python/2.7/site-packages/matlab/engine/futureresult.py", line 68, in result
return self.__future.result(timeout)
File "/Library/Python/2.7/site-packages/matlab/engine/fevalfuture.py", line 82, in result
self._result = pythonengine.getFEvalResult(self._future,self._nargout, None, out=self._out, err=self._err)
SyntaxError: Error: At least one END is missing: the statement may begin here.
as if the 'end;' statement is not executed in the Matlab workspace. Why? What is the solution ?
The eval() needs to complete on its own. Try this (UNTESTED):
eng = matlab.engine.start_matlab()
eng.eval('i=1; while i<10; i=i+1; end', nargout=0)
eng.quit()
I am trying to understand how to use the pdb.post_mortem() method.
for this given file
# expdb.py
import pdb
import trace
def hello():
a = 6 * 9
b = 7 ** 2
c = a * b
d = 4 / 0
print(c)
tracer = trace.Trace()
Command prompt
'''
# first Try
λ python -i expdb.py
>>> pdb.post_mortem()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Program Files\Anaconda3\lib\pdb.py", line 1590, in post_mortem
raise ValueError("A valid traceback must be passed if no "
ValueError: A valid traceback must be passed if no exception is being handled
'''
'''
# Second Try
λ python -i expdb.py
>>> pdb.post_mortem(traceback=tracer.run('hello()') )
--- modulename: trace, funcname: _unsettrace
trace.py(77): sys.settrace(None)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Program Files\Anaconda3\lib\trace.py", line 500, in run
self.runctx(cmd, dict, dict)
File "C:\Program Files\Anaconda3\lib\trace.py", line 508, in runctx
exec(cmd, globals, locals)
File "<string>", line 1, in <module>
File "expdb.py", line 8, in hello
d = 4 / 0
ZeroDivisionError: division by zero
>>>
The post_mortem method wants a traceback object, not a Trace object. Traceback objects can be acquired from sys.exc_info()[2] inside of an except block, or you can simply call pdb.post_mortem() with no arguments directly (in the except block).
But either way, you must catch the exception before you can debug it.
I have a problem with the following function in python (where swap is a function that I have previously created and that works fine):
def swap (cards):
"""
>>> swap('FBFFFBFFBF')
'BFBBBFBBFB'
>>> swap('BFFBFBFFFBFBBBFBBBBFF')
'FBBFBFBBBFBFFFBFFFFBB'
>>> swap('FFBFBFBFBFBFBFBBFBFBFBFBBFBFBBFBF')
'BBFBFBFBFBFBFBFFBFBFBFBFFBFBFFBFB'
"""
invert=""
for i in cards:
if i is "B":
invert+="F"
else:
invert+="B"
return (invert)
def swap2 (cards):
"""
>>> next('FBFFFBFFBF')
'FFBBBFBBFF'
>>> next('BFFBFBFFFBFBBBFBBBBFF')
'FBBFBFBBBFBFFFBFFFFFF'
>>> next('FFBFBFBFBFBFBFBBFBFBFBFBBFBFBBFBF')
'FFFBFBFBFBFBFBFFBFBFBFBFFBFBFFBFF'
"""
indices=""
for pos, i in enumerate(cards):
if i =="B":
indices+=str(pos)
first= int(indices[0])
last= int(indices[-1])
prefix= cards [:first]
middle= cards [first:last+1]
suffix= cards [last+1:]
middle2=swap(middle)
return (prefix+middle2+suffix)
def turns (cards):
"""
>>> turns('FBFFFBFFBF')
3
>>> turns('BFFBFBFFFBFBBBFBBBBFF')
6
>>> turns('FFBFBFBFBFBFBFBBFBFBFBFBBFBFBBFBF')
14
"""
turn=0
while cards != 'F'*len(cards):
cards=swap2(cards)
turn+=1
return (turn)
if __name__ == '__main__':
import doctest
doctest.testmod()
when I run this function it works fine but if I use doctest to see if there are mistakes it tells me:
TypeError: 'str' object is not an iterator
I don't know where this error comes from.
Can anyone help me?
complete output of the doctest:
File "C:\Users\manuel\Documents\Gent MaStat\programming and algorithms\workspace_python\homeworks\Week 5\looking_up.py", line 25, in __main__.swap2
Failed example:
next('FBFFFBFFBF')
Exception raised:
Traceback (most recent call last):
File "C:\Users\manuel\Anaconda3\lib\doctest.py", line 1321, in __run
compileflags, 1), test.globs)
File "<doctest __main__.swap2[0]>", line 1, in <module>
next('FBFFFBFFBF')
TypeError: 'str' object is not an iterator
**********************************************************************
File "C:\Users\manuel\Documents\Gent MaStat\programming and algorithms\workspace_python\homeworks\Week 5\looking_up.py", line 27, in __main__.swap2
Failed example:
next('BFFBFBFFFBFBBBFBBBBFF')
Exception raised:
Traceback (most recent call last):
File "C:\Users\manuel\Anaconda3\lib\doctest.py", line 1321, in __run
compileflags, 1), test.globs)
File "<doctest __main__.swap2[1]>", line 1, in <module>
next('BFFBFBFFFBFBBBFBBBBFF')
TypeError: 'str' object is not an iterator
**********************************************************************
File "C:\Users\manuel\Documents\Gent MaStat\programming and algorithms\workspace_python\homeworks\Week 5\looking_up.py", line 29, in __main__.swap2
Failed example:
next('FFBFBFBFBFBFBFBBFBFBFBFBBFBFBBFBF')
Exception raised:
Traceback (most recent call last):
File "C:\Users\manuel\Anaconda3\lib\doctest.py", line 1321, in __run
compileflags, 1), test.globs)
File "<doctest __main__.swap2[2]>", line 1, in <module>
next('FFBFBFBFBFBFBFBBFBFBFBFBBFBFBBFBF')
TypeError: 'str' object is not an iterator
def swap2 (cards):
"""
>>> next('FBFFFBFFBF')
'FFBBBFBBFF'
>>> next('BFFBFBFFFBFBBBFBBBBFF')
'FBBFBFBBBFBFFFBFFFFFF'
>>> next('FFBFBFBFBFBFBFBBFBFBFBFBBFBFBBFBF')
'FFFBFBFBFBFBFBFFBFBFBFBFFBFBFFBFF'
"""
# …
The function is called swap2 but within the doctests, you are using next which happens to be a built-in function that does something completely different. That’s why you are seeing that error.
At times like this, it’s really important to actually look at the error messages. It clearly told you what was called:
File "<doctest __main__.swap2[0]>", line 1, in <module>
next('FBFFFBFFBF')
So if you don’t know where that was supposed to come from, then check out the error message. Doctest will tell you what it is executing: swap2[0], swap2[1], etc. tells you the function name the docstring that is being executed is by doctest and which test case it is (0 is the first, 1 the second etc.). It even gives you the line number (within the doctest case) where the error appeared, and of course the line that was causing the error. So use that information to go to the problematic code, and figure out what the problem is.
Keeping it simple:
----------------------------------
from mpmath import *
from scipy.integrate import *
mp.dps=30
def F(x):
return Q**(x)
Q=735
print fixed_quad(F,0,1,n=1)[0]
print fixed_quad(F,0,1,n=2)[0]
print fixed_quad(F,0,1,n=3)[0]
--------------------
returns
27.1108834235
93.1213589089
109.673420158
However, if I change F(x) from “Q**(x)” to even just a simple function—e.g., “cos(x)”—I get
--------------------
Traceback (most recent call last):
File "Test.py", line 7, in <module>
print fixed_quad(F,0,1,n=1)[0]
File "/usr/lib/python2.7/dist-packages/scipy/integrate/quadrature.py", line 67, in fixed_quad
return (b-a)/2.0*sum(w*func(y,*args),0), None
File "Test.py", line 5, in F
return cos(x)
File "/usr/lib/pymodules/python2.7/mpmath/ctx_mp_python.py", line 984, in f
x = ctx.convert(x)
File "/usr/lib/pymodules/python2.7/mpmath/ctx_mp_python.py", line 662, in convert
return ctx._convert_fallback(x, strings)
File "/usr/lib/pymodules/python2.7/mpmath/ctx_mp.py", line 614, in _convert_fallback
raise TypeError("cannot create mpf from " + repr(x))
TypeError: cannot create mpf from array([ 0.5])
Is this some known bug? Or is “fixed_quad” only meant for certain uses, not general integration (like “trapz”)?
All of the other regulars (“quad”, “dblquad”, “tplquad”, “nquad”) donʼt seem to have that problem/error.