Let's say we have dictionary = ['a':x*2,'b':x*3]
, and we set x
to 2. When I print out the dictionary after this assignment, I get the one shown above, and not ['a':4,'b':6]
. Why is that? I am currently trying to come up with a solution to Project Euler exercise 69 ( https://projecteuler.net/problem=69 ) for which I have made the following:
import math
from sympy import Symbol
magic_book={1:1,2:1}
maximum=0
for n in range(3,10**6+1):
print(magic_book)
print(n)
if n in magic_book:
if (n/magic_book[n])>maximum:
maximum=n/magic_book[n]
continue
Phi=0
x = Symbol('x')
for m in range(1,n):
if math.gcd(n,m)==1:
magic_book[n*m]=x*magic_book[m]
Phi+=1
x=Phi
if n/Phi>maximum:
maximum=n/Phi
print(maximum)
When I set x
equal Phi
, magic_book
does not update - why is this?
When you edit an object in Python, it does not go back and change what you previously stated using it. See for example:
x = 1
double_x = 2*x
x = 10
Your question is basically asking why double_x
is not 20.
In order to substitute symbolic values with other values (like numeric values), .subs()
is usually the best option if you are dealing with SymPy objects. However, a dictionary is not a SymPy object and it does not have a .subs()
method. You must then loop through the dictionary and substitute its values like so:
for k, v in magic_book.items():
maximum[k] = v.subs(x, Phi) # assuming v is a SymPy object
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.