Nonlocal and Environment Diagrams Practice Problems

Important! These are all exam-level problems. Do not attempt these problems without a solid foundation in the subject and use them for exam practice.

1. Fill out a full environment diagram for the the following block of code.

minions = [1,2,3,4]
minions.append(minions)
banana = lambda x, y: x ** y
def kevin(banana):
    tim = 2
    if banana > 5:
        tim += banana(3,4)
    else:
        tim += bob(5)()
    return tim
def bob(banana): 
    def scarlett():
        nonlocal banana
        if banana == 5:
            banana = max(banana, 12)
        return -1
    return scarlett
stuart = kevin(banana(5, minions[4][0]))
 
Toggle Solution

2. Implement a function which returns a function that applies a passed in f, which takes in one argument, son a true valued variable x everytime it is called. Return this new value of x or, if this value of x returns a false value, reset x to be what it began as so that the value of x is always true.

def always_true(f, x):
  """Implement a non generator function which will return a function which keeps outputting the value of f applied onto x, or reset x back to its original state if it turns false. 
  >>>new = always_true(lambda x: x-1, 3)
  >>>new()
  2
  >>>new()
  1
  >>>new()
  3
  """
  start = x
  def inner():
      nonlocal x
      x = f(x)
      if not x:
          x = start
      return x
  return inner
def always_true(f, x):
  """Implement a non generator function which will return a function which keeps outputting the value of f applied onto x, or reset x back to its original state if it turns false. 
  >>>new = always_true(lambda x: x-1, 3)
  >>>new()
  2
  >>>new()
  1
  >>>new()
  3
  """
  "YOUR CODE HERE"
Toggle Solution