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.
Related
I keep getting
Traceback (most recent call last):
File "/Applications/Xcode.app/Contents/Developer/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/xml/etree/ElementTree.py", line 1076, in _escape_attrib
if "&" in text:
TypeError: argument of type 'int' is not iterable
when I'm trying to write an XML file with some attributes I need to edit.
Here's my code:
import xml.etree.ElementTree as ET
tree = ET.parse('TM_GeneralSettings.xml')
root = tree.getroot()
for item in root.iter('Control'):
numX = int(((720/1080)*float(item.attrib.get('LocationX'))))
numY = int(((720 / 1080) * float(item.attrib.get('LocationY'))))
numW = int(((720 / 1080) * float(item.attrib.get('SizeW'))))
numH = int(((720 / 1080) * float(item.attrib.get('SizeH'))))
print(numX, ':', numY, ':', numW, ':', numH)
item.set('LocationX', numX)
item.set('LocationY', numY)
item.set('LocationW', numW)
item.set('LocationH', numH)
tree.write('TM_GeneralSettings2.xml')
I also get this errors when I run my code:
Traceback (most recent call last):
File "/Users/alessandrochiodo/PycharmProjects/pythonProject/main.py", line 17, in <module>
tree.write('TM_GeneralSettings2.xml')
File "/Applications/Xcode.app/Contents/Developer/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/xml/etree/ElementTree.py", line 772, in write
serialize(write, self._root, qnames, namespaces,
File "/Applications/Xcode.app/Contents/Developer/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/xml/etree/ElementTree.py", line 937, in _serialize_xml
_serialize_xml(write, e, qnames, None,
File "/Applications/Xcode.app/Contents/Developer/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/xml/etree/ElementTree.py", line 930, in _serialize_xml
v = _escape_attrib(v)
File "/Applications/Xcode.app/Contents/Developer/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/xml/etree/ElementTree.py", line 1099, in _escape_attrib
_raise_serialization_error(text)
File "/Applications/Xcode.app/Contents/Developer/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/xml/etree/ElementTree.py", line 1053, in _raise_serialization_error
raise TypeError(
TypeError: cannot serialize 0 (type int)
Can someone help me? I can't find a solution.
res_DE=differential_evolution(invSortino,bounds=bounds, disp=True)
where invSortino takes an iterable of length x ad returns a negative scalar.
bounds are defined by
lb=[1e-03]*data.shape[1]
ub=[.4]*data.shape[1]
bounds=Bounds(lb,ub)
Or
#bounds=[(0,.4)]*data.shape[1]
the length of bounds is correct,(method 2 above)
but iterable generated has a length 0
print('shapes: ',weights.shape,data.shape)
results in
shapes: (0,) (951, 65)
which results in the error
Traceback (most recent call last):
File "C:\Users\anaconda3\lib\site-packages\scipy\optimize\_differentialevolution.py", line 878, in _calculate_population_energies
parameters_pop[0:nfevs]))
File "C:\Users\anaconda3\lib\site-packages\scipy\optimize\_differentialevolution.py", line 1265, in __call__
return self.f(x, *self.args)
File "c:/Users/try.py", line 68, in invSortino
rets=data*weights
File "C:\Users\anaconda3\lib\site-packages\pandas\core\ops\__init__.py", line 695, in f
other = _align_method_FRAME(self, other, axis)
File "C:\Users\anaconda3\lib\site-packages\pandas\core\ops\__init__.py", line 644, in _align_method_FRAME
right = to_series(right)
File "C:\Users\anaconda3\lib\site-packages\pandas\core\ops\__init__.py", line 636, in to_series
msg.format(req_len=len(left.columns), given_len=len(right))
ValueError: Unable to coerce to Series, **length must be 65: given 0**
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
line 85, in <module>
res_DE=differential_evolution(invSortino,bounds=bounds, disp=True)
File "C:\Users\anaconda3\lib\site-packages\scipy\optimize\_differentialevolution.py", line 306, in differential_evolution
ret = solver.solve()
File "C:\Users\anaconda3\lib\site-packages\scipy\optimize\_differentialevolution.py", line 745, in solve
self.population[self.feasible]))
File "C:\Users\anaconda3\lib\site-packages\scipy\optimize\_differentialevolution.py", line 883, in _calculate_population_energies
raise RuntimeError("The map-like callable must be of the"
RuntimeError: The map-like callable must be of the form f(func, iterable), returning a sequence of numbers the same length as 'iterable'
There are some Chinese comments in my code. The pdb debugger will raise a UnicodeDecodeError only when some specific characters appear.
Here's the source file util.py:
"""代码清单 util.py"""
import json
def load_info(path):
"""读取json文件"""
with open(path) as f:
return json.load(f)
def print_info(info):
"""打印信息"""
for k, v in info.items():
print('{}: {}'.format(k, v))
def to_upper(info):
"""将键值中的字符串转为大写"""
for k, v in info.items():
if isinstance(v, str):
info[k] = v.upper()
return info
And here's the error message when I try to add a break point:
E:\10-写作\01-技术\01-Python\Python代码调试全面介绍\src
λ python -m pdb util.py
> e:\10-写作\01-技术\01-python\python代码调试全面介绍\src\util.py(1)<module>()
-> """代码清单 util.py"""
(Pdb) b print_info
Traceback (most recent call last):
File "D:\Python37\lib\pdb.py", line 648, in do_break
lineno = int(arg)
ValueError: invalid literal for int() with base 10: 'print_info'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "D:\Python37\lib\pdb.py", line 659, in do_break
code = func.__code__
AttributeError: 'str' object has no attribute '__code__'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "D:\Python37\lib\pdb.py", line 1701, in main
pdb._runscript(mainpyfile)
File "D:\Python37\lib\pdb.py", line 1570, in _runscript
self.run(statement)
File "D:\Python37\lib\bdb.py", line 585, in run
exec(cmd, globals, locals)
File "<string>", line 1, in <module>
File "e:\10-写作\01-技术\01-python\python代码调试全面介绍\src\util.py", line 1, in <module>
"""代码清单 util.py"""
File "e:\10-写作\01-技术\01-python\python代码调试全面介绍\src\util.py", line 1, in <module>
"""代码清单 util.py"""
File "D:\Python37\lib\bdb.py", line 88, in trace_dispatch
return self.dispatch_line(frame)
File "D:\Python37\lib\bdb.py", line 112, in dispatch_line
self.user_line(frame)
File "D:\Python37\lib\pdb.py", line 261, in user_line
self.interaction(frame, None)
File "D:\Python37\lib\pdb.py", line 352, in interaction
self._cmdloop()
File "D:\Python37\lib\pdb.py", line 321, in _cmdloop
self.cmdloop()
File "D:\Python37\lib\cmd.py", line 138, in cmdloop
stop = self.onecmd(line)
File "D:\Python37\lib\pdb.py", line 418, in onecmd
return cmd.Cmd.onecmd(self, line)
File "D:\Python37\lib\cmd.py", line 217, in onecmd
return func(arg)
File "D:\Python37\lib\pdb.py", line 667, in do_break
(ok, filename, ln) = self.lineinfo(arg)
File "D:\Python37\lib\pdb.py", line 740, in lineinfo
answer = find_function(item, fname)
File "D:\Python37\lib\pdb.py", line 100, in find_function
for lineno, line in enumerate(fp, start=1):
UnicodeDecodeError: 'gbk' codec can't decode byte 0xac in position 329: illegal multibyte sequence
Uncaught exception. Entering post mortem debugging
Running 'cont' or 'step' will restart the program
> d:\python37\lib\pdb.py(100)find_function()
-> for lineno, line in enumerate(fp, start=1):
(Pdb)
But when after I remove some Chinese characters, there won't be any errors. I removed some comments for to_upper function:
def to_upper(info):
"""将键值中"""
for k, v in info.items():
if isinstance(v, str):
info[k] = v.upper()
return info
Then the error just is gone:
(Pdb) b print_info
Breakpoint 2 at e:\10-写作\01-技术\01-python\python代码调试全面介绍\src\util.py:11
The source file is encoded in UTF-8 format. I don't know what's going on here.
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.
Suppose I am given the following traceback:
Traceback (most recent call last):
File "<wingdb_compile>", line 3, in <module>
File "C:\Python34\lib\ftplib.py", line 419, in login
resp = self.sendcmd('PASS ' + passwd)
File "C:\Python34\lib\ftplib.py", line 272, in sendcmd
return self.getresp()
File "C:\Python34\lib\ftplib.py", line 245, in getresp
raise error_perm(resp)
ftplib.error_perm: 530 Login incorrect.
I have managed to extract the Error details but what has stumped me is how would I extract the line:
File "<wingdb_compile>", line 3, in <module>
I was looking at methods in the trace back package but wondered if any one had experience with that here
The function traceback.format_exc is built primarily for this
This is like print_exc(limit) but returns a string instead of printing to a file.
>>> import traceback
>>> try:
... x = 2/0
... except:
... error = traceback.format_exc()
...
>>> error
'Traceback (most recent call last):\n File "<stdin>", line 2, in <module>\nZeroDivisionError: division by zero\n'
>>> linesoferror = error.split('\n')
>>> linesoferror
['Traceback (most recent call last):', ' File "<stdin>", line 2, in <module>', 'ZeroDivisionError: division by zero', '']
So now you wanted the first line then you can simply use
>>> linesoferror[1]
' File "<stdin>", line 2, in <module>'
Voila! You have what you want
ALERT - Valid for Python 2.4.1 and above