Gotchas


In [ ]:
from sympy import *
init_printing()

For each exercise, fill in the function according to its docstring.

Symbols

What will be the output of the following code?

x = 3
y = symbols('y')
a = x + y
y = 5
print(a)

Replace ??? in the below code with what you think the value of a will be. Remember to define any Symbols you need!


In [ ]:
def symbols_exercise():
    """
    >>> def testfunc():
    ...     x = 3
    ...     y = symbols('y')
    ...     a = x + y
    ...     y = 5
    ...     return a
    >>> symbols_exercise() == testfunc()
    True
    """
    return ??? # Replace ??? with what you think the value of a is

In [ ]:
def testfunc():
    x = 3
    y = symbols('y')
    a = x + y
    y = 5
    return a

symbols_exercise() == testfunc()

Equality

Write a function that takes two expressions as input, and returns a tuple of two booleans. The first if they are equal symbolically, and the second if they are equal mathematically.


In [ ]:
def equality_exercise(a, b):
    """
    Determine if a = b symbolically and mathematically.

    Returns a tuple of two booleans. The first is True if a = b symbolically,
    the second is True if a = b mathematically.  Note the second may be False
    but the two still equal if SymPy is not powerful enough.

    Examples
    ========

    >>> x = symbols('x')
    >>> equality_exercise(x, 2)
    (False, False)
    >>> equality_exercise((x + 1)**2, x**2 + 2*x + 1)
    (False, True)
    >>> equality_exercise(2*x, 2*x)
    (True, True)
    """

In [ ]:
x = symbols('x')

In [ ]:
equality_exercise(x, 2)

In [ ]:
equality_exercise((x + 1)**2, x**2 + 2*x + 1)

In [ ]:
equality_exercise(2*x, 2*x)

^ and /

Correct the following functions


In [ ]:
def operator_exercise1():
    """
    >>> operator_exercise1()
    x**2 + 2*x + 1/2
    """
    x = symbols('x')
    return x^2 + 2*x + 1/2

In [ ]:
operator_exercise1()

In [ ]:
def operator_exercise2():
    """
    >>> operator_exercise2()
    (x**2/2 + 2*x + 3/4)**(3/2)
    """
    x = symbols('x')
    return (1/2*x^2 + 2*x + 3/4)^(3/2)

In [ ]:
operator_exercise2()