Generate formula for (a+b)^2 in python

Question:

Is it possible to write a program in Python that generates formula for (a+b)^2 (display it).
I mean if I provide input as (a+b)^2 the program should generate the output as a*a + b*b + 2*a*b The program itself should generate the formula for (a+b)^2.

Asked By: shrinidhi kulkarni

||

Answers:

If the symbolic computing is what you want, you should have a look at the SymPy project. See the example at the related wiki page (copied from http://en.wikipedia.org/wiki/SymPy#Expansion):

>>> from sympy import init_printing, Symbol, expand
>>> init_printing()
>>>
>>> a = Symbol('a')
>>> b = Symbol('b')
>>> e = (a + b)**5
>>> e
       5
(a + b) 
>>> e.expand()
 5      4         3  2       2  3        4    5
a  + 5⋅a ⋅b +  10⋅a ⋅ b  + 10⋅a ⋅b  + 5⋅a⋅b  + b
Answered By: pepr

First of all download sympy package by going to cmd and Type : pip install sympy
Then Open Python 3.7 or version >>3

Now Type the Following Code to the Python idle

n = int(input("Enter the Power of (a+b) "))
from sympy import init_printing , Symbol ,expand
init_printing()
 a = Symbol('a')
 b = Symbol('b')
 e = (a+b)**n
print( expand(e) )

Save as What you Want and Run !!!!
It will 100000000% work and no errors will be seen to you
it is the code what you want

Answered By: Aman kumar
a = int(input("enter a "))
b = int(input ("enter b "))
formula = (a**2 + b**2 + 2*a*b)
print("(" , a ,"+" , b , ")**2 =" , formula)
Answered By: Farid jafari

Type this code:

def formula(a,b):
    print((a+b)*(a+b))
    
formula(5,2)

In this, you have to type the a and b in your code yourself like I did ( a and b are 5 and 2 respectively)

The output will be the answer:

49 

this is the output for my code. As you change the values a and b and run the program again, the output will be changed again.

Answered By: Shiva Bommera
    a = 2
    b = 5

    print ((a+b)**2)
    print ((a+b)*(a+b))
    print (a**2+b**2+2*a*b)
    #3 types can written answer will be same
Answered By: Rakesha N
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.