Functions Assessment
Test your mastery of Python functions including definitions, arguments, scope, recursion, lambdas, higher-order functions, and closures.
Write a function greet(name, greeting="Hello") that returns a string in the format "{greeting}, {name}!". The greeting parameter should default to "Hello".
This function is supposed to append an item to a new list each time it is called without an explicit list. But calling it multiple times without a list accumulates items across calls. Fix the bug.
Read the code carefully and predict exactly what will be printed.
def show_args(*args):
print(type(args).__name__)
print(len(args))
print(args[1])
show_args(10, 20, 30)Write a function build_profile(name, **kwargs) that returns a dictionary with the key "name" set to name, plus every key-value pair from kwargs.
Read the code carefully and predict exactly what will be printed.
x = 10
def outer():
x = 20
def inner():
print(x)
inner()
print(x)
outer()
print(x)Write a recursive function factorial(n) that returns the factorial of a non-negative integer n. By definition, factorial(0) is 1.
This function is supposed to apply a discount and return the new price, but it always returns None. Fix it so it returns the discounted price as a float rounded to 2 decimal places.
Refactor the loop below into a single line using map() with a lambda. The variable squared should be a list of the squared values.
Read the code carefully and predict exactly what will be printed.
def make_counter(start=0):
count = start
def increment():
nonlocal count
count += 1
return count
return increment
c = make_counter(5)
print(c())
print(c())
print(c())Write a function compose(f, g) that returns a new function which, when called with an argument x, returns f(g(x)). In other words, it applies g first, then f to the result.
This code tries to filter a list to keep only even numbers, but it returns the odd numbers instead. Fix the lambda so it correctly keeps even numbers.
The recursive fib function below is slow for large inputs because it recalculates the same values. Write a memoize decorator function that caches results, then apply it to fib using @memoize. The decorator should work with any single-argument function.