Gotchas Solutions

Boilerplate to make the doctester work. Run this cell first.


In [1]:
import sys
import os
sys.path.insert(1, os.path.join(os.path.pardir, "ipython_doctester"))
from sympy import *
from ipython_doctester import test
# Work around a bug in IPython. This will disable the ability to paste things with >>>
def notransform(line): return line
from IPython.core import inputsplitter
inputsplitter.transform_classic_prompt = notransform

For each exercise, fill in the function according to its docstring. Execute the cell to see if you did it right.

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 [2]:
@test
def symbols_exercise():
    """
    (This tests that your output is correct)

    >>> def testfunc():
    ...     x = 3
    ...     y = symbols('y')
    ...     a = x + y
    ...     y = 5
    ...     return a
    >>> symbols_exercise() == testfunc()
    True
    """
    y = symbols('y')
    return 3 + y


Success!

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 [3]:
@test
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)
    """
    return (a == b, simplify(a - b) == 0)


Success!

^ and /

Correct the following functions


In [4]:
@test
def operator_exercise1():
    """
    >>> operator_exercise1()
    x**2 + 2*x + 1/2
    """
    x = symbols('x')
    return x**2 + 2*x + Rational(1, 2)


Success!


In [5]:
@test
def operator_exercise2():
    """
    >>> operator_exercise2()
    (x**2/2 + 2*x + 3/4)**(3/2)
    """
    x = symbols('x')
    return (x**2/2 + 2*x + Rational(3, 4))**Rational(3, 2)


Success!


In [5]: