Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have the following problem:

x=Symbol('x') 
book={1:2*x,2:3*x}
x=2
print(book) >>> {1:2*x,2:3*x}

I had hoped it would print {1:4,2:6}

But if I set book={1:2*x,2:3*x} just before the print statement, I get the wanted result.

The frustrating thing is, if I instead write book=book, which should be the same (right?), just before the print statement, I get {1:2*x,2:3*x} - why is that?

See Question&Answers more detail:os

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

1 Answer

You're dealing with two different values of x because you're talking about setting x to something other than Symbol('x') in one case but not the other. In one case:

x=Symbol('x') 
book={1:2*x,2:3*x}
x=2
print(book)

Result:

{1: 2*x, 2: 3*x}

x was Symbol('x') when you created book. It doesn't matter that you later set x to 2.

In your other case, if I understand you right:

x=Symbol('x')
x=2
book={1:2*x,2:3*x}
print(book) >>> {1:2*x,2:3*x}

Result:

{1: 4, 2: 6}

x is now 2 when you build book, so your result now has nothing to do with sympy. It's just regular Python arithmetic, and so you get computed values in your dict.

If what you want is {1: 4, 2: 6}, why are you using sympy at all?

To answer your final question, you're asking why adding the line book = book doesn't change the result. Why would it? That line doesn't do anything. book is the same value after that line is run that it was before.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...