How can I get Python to expand a term as much as possible?

I used the normal Python preset and want to ask here:

How can I get Python to expand a term as much as possible?

The term is



(binomial formula)

So my question is: How would you write this in Python? How do I make Python see n as a variable that's initially set to 1, and how do I make it so that I don't have to define a and b , so that it then calculates with a and b as variables, so to speak?

My current code:

 n = 0 print(("a" + "b") ** n) n = n + 1

Perhaps you could explain to me how, once he has done that once, I can repeat the second and third steps five times, for example.

I would be extremely grateful if you could help me.

Kind regards

(1 votes)
Loading...

Similar Posts

Subscribe
Notify of
12 Answers
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Hsk108385
1 year ago

I don’t think it’s possible to use character strings in Python, for example, “a” or “b” not directly for computational operations.

for that there is a special library called “,sympy” the importer then, (important: from sympy import * you can also write import sympy, but you have to write that instead, “symbols” sympy.symbols etc.)

if you have imported it, you will use the method , symbol()” to generate symbolic variables (as in math, e.g. x, y).

Initializes the variable n and shows him Value 2 yes then you define your expression and store it under the variable, task”.

Then you use the “expand()” method that simplifies, expands, clamps, etc.

and then simply give it out;)


from sympy import *

a, b = symbols("a b")

n = 2
aufgabe = ((a+b)**n)
aufgabe_n = expand(aufgabe)
print(aufgabe_n)

If you want to repeat this, you can or need to use loops (if you want to work effectively);)

e.g.

For schleife:


from sympy import *
a, b = symbols("a b")
for n in range(11): 
		# Wichtig: Da steht eigentlich range(0,11), also bei der Schleife wird für n = 0 bis n = 10 ausgeführt, die 11 zählt nicht dazu
		aufgabe = (a + b)**n
		aufgabe_n = expand(aufgabe)
		print(aufgabe_n)


Hsk108385
1 year ago
Reply to  Digi1304

jo so you can also make it

Hsk108385
1 year ago

There are dozens of other possibilities btw:

e.g.

from IPython.display import display
from sympy import *
a, b = symbols("a b")
for n in range(11): 
		# Wichtig: Da steht eigentlich range(0,11), also bei der Schleife wird für n = 0 bis n = 10 ausgeführt, die 11 zählt nicht dazu
		aufgabe = (a + b)**n
		aufgabe_n = expand(aufgabe)
		display(aufgabe_n)

Hsk108385
1 year ago

:).. which compiler do you use btw?

Hsk108385
1 year ago

hm.. with me this works. try with “import pprint” but then you have to write pprint.pprint()

Hsk108385
1 year ago

Na print usually automatically generates a line break, but can do that anyway so that a line always remains free

Hsk108385
1 year ago

Then you can write instead of “print()”, “pprint()” which embellished the output