0

I get this error. What am I doing wrong with the macro?

from sympy import *
var('y')
x=10
d=factorint(x)
print(d)
for k, v in d.items():
    y=y+str(k)+'^' +str(v)
print(y)

# {2: 1, 5: 1}
# Traceback (most recent call last):
#   File "C:/xxx/.PyCharmCE2018.2/config/scratches/soinsuu.py", line 9, in <module>
#     y=y+str(k)+'^' +str(v)
# TypeError: unsupported operand type(s) for +: 'Symbol' and 'str'
#
# Process finished with exit code 1

i want

10=2^1+5^1
10=2**1+5**1

2 Answers 2

1

var('y') is equivalent to y = symbols('y'), so y is a symbol. Then you do y+str(k), adding a symbol and a string. That's a type error.

The type of y should be a string. And you want that string to begin with 10=, so initialize it with that:

from sympy import *
x = 10
y = str(x) + '=' 
d = factorint(x)
print(d)
for k, v in d.items():
    y = y + str(k)+'^' +str(v)
print(y)

That said, you are missing the arithmetic operation... and it should be *, not +. 10 is definitely not equal to the sum of 2 and 5.

Also, Python has join string method for this purpose. Use it instead of a loop:

from sympy import *
x = 10
d = factorint(x)
y = str(x) + '=' + '*'.join([str(k)+'^' +str(v) for k, v in d.items()])
print(y)
0
def Myfactorint(x):
    return '+'.join([str(k)+'^' +str(v) for k, v in factorint(x).items()])
from sympy import *
x=10
print(x,'=',  factorint(x))
print(x,'=',Myfactorint(x))
# 10 = {2: 1, 5: 1}
# 10 = 2^1+5^1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.