Practice Problems

Work in progress! Check out Albert Wu's practice problems and the CS61A wiki for more practice.

Environment Diagrams!

For answers, check python tutor

Question 1

def apple(sauce):
    pear = 2
    return lambda: sauce - 5

def pear(jam):
    pear = 4
    return jam(pear)

apple_sauce = pear(apple)
apple_sauce()

Question 2

def wow(how):
    return lambda wow: lambda bow: how + wow * bow

def how(wow):
    def mow():
        return wow
    return mow

howie = how(5)
wowie = wow(howie())
bowie = wowie(how(7)())
bowie(2)

Question 3

def meow(cat):
    def dog(bark):
        nonlocal cat
        cat += 'meow'
        return bark(cat)
    return dog

hank = lambda: 'rawr'
noise = meow('mew')
noise(lambda animal: animal)

Question 4

def shocker(n):
    charge = lambda f: lambda: f() * 2
    thunder = lambda: n
    def shock(power):
        nonlocal charge, thunder
        if power:
            thunder = charge(thunder)
        return thunder()
    return shock

pikachu = shocker(120)
damage = pikachu('PIKACHUUUUUUU!')

Question 5, courtesy of DJFOOOTE

# Do you want to know what it schwas?

def hashmeer(schwiggity):
    def cannot_heer_yuo(my_ear):
        my_pants = my_ear[::7]
        return my_pants

    def cant_do_it(schwoggity):
        nonlocal cant_do_it
        cant_do_it = schwoggity(schwiggity)
        return cant_do_it(schwiggity + "WHAT YOU SAY? ")

    return cannot_heer_yuo, cant_do_it

schfifty, five = hashmeer('pff. ')
scheven = five(lambda schfourteen: lambda teen: schfifty)
scheven('poopty peupty pants.')

List Comprehensions

Remember that list comprehensions are created in this format:

[<expression> for <value> in <sequence>]

Question 1

Using list comprehensions, create a list that contains all the odd numbers from 1 to n

Question 2

Using list comprehensions, create a list that contains all the numbers from 1 to n that are prime numbers, given an isPrime(x) function

Question 3

Using list comprehensions, create a list that returns a list with numbers after it goes through the do_something(x) function

Question 4

Using list comprehensions, create a list that returns a list with numbers after it goes through the do_something(x) function only if the number is divisible by 3

HOF List Comprehensions using the reduce function

What Would Python Output?

>>> from functools import reduce
>>> tup = (1, 2, 3)

>>> reduce(lambda x, y: x + y, tup, 100)


>>> reduce(lambda x, y: (x, y), tup)


>>> reduce(lambda x, y: y + x, "hello world!")


>>> reduce(lambda x, y: x + y, map(lambda x: x**2, tup))



Create the reduce function

Implement a function reduce that acts just like the built-in reduce. (taken from Albert's website)

def reduce(combiner, seq):
    """Acts just like the built-in reduce function.

    >>> seq = (1, 2, 3, 4, 5, 6)
    >>> reduce(lambda x, y: x + y, seq)
    21
    >>> reduce(lambda x, y: x * y, (1, 2, 3, 4))
    24
    """
    "*** YOUR CODE HERE ***"