Python | sympy.subs () метод

Опубликовано: 12 Апреля, 2022

С помощью метода sympy.subs () мы можем заменить все экземпляры переменной или выражения в математическом выражении какой-либо другой переменной, выражением или значением.

Syntax: math_expression.subs(variable, substitute)

Parameters:
variable – It is the variable or expression which will be substituted.
substitute – It is the variable or expression or value which comes as substitute.

Returns: Returns the expression after the substitution.

Пример №1:

In this example we can see that by using sympy.subs() method, we can find the resulting expression after substituting a variable or expression with some other variable or expression or value. Here we use symbols() method also to declare a variable as symbol.

# import sympy
from sympy import *
  
x, y = symbols("x y")
exp = x**2 + 1
print("Before Substitution : {}".format(exp)) 
    
# Use sympy.subs() method
res_exp = exp.subs(x, y) 
    
print("After Substitution : {}".format(res_exp)) 

Выход:

 
Перед заменой: x ** 2 + 1
После замены: y ** 2 + 1


Пример №2:

In this example we see that if the substituted value is numerical then sympy.subs() returns the solution of the resulting expression.

# import sympy
from sympy import * 
  
x = symbols("x")
exp = cos(x) + 7
print("Before Substitution : {}".format(exp)) 
    
# Use sympy.subs() method
res_exp = exp.subs(x, 0
    
print("After Substitution : {}".format(res_exp)) 

Выход:

 
Перед заменой: cos (x) + 7
После замены: 8

Пример № 3:

In this example we see that we can do multiple substitutions if we pass a list of (old, new) pairs to subs.

# import sympy
from sympy import * 
  
x, y, z = symbols("x y z")
exp = x**2 + 7 * y + z
print("Before Substitution : {}".format(exp)) 
    
# Use sympy.subs() method
res_exp = exp.subs([(x, 2), (y, 4), (z, 1)]) 
    
print("After Substitution : {}".format(res_exp)) 

Выход:

 
Перед заменой: x ** 2 + 7 * y + z
После замены: 33

Внимание компьютерщик! Укрепите свои основы с помощью базового курса программирования Python и изучите основы.

Для начала подготовьтесь к собеседованию. Расширьте свои концепции структур данных с помощью курса Python DS. А чтобы начать свое путешествие по машинному обучению, присоединяйтесь к курсу Машинное обучение - базовый уровень.