Python Q&A – Functional Programming

Question 1: Writing Lambda Functions
A lambda function is an anonymous function. The syntax for writing a lambda function is straightforward enough:
variable_name = lambda argument_one, argument_two: return_value

For example, we could write a simple lambda function which increments its argument:
increment = lambda x: x + 1

We can then call this in exactly the same way as a normal function:
increment(3)  # -> 4
increment(4.5)  # -> 5.5

Task: Write square(x), is_odd(x), and add(x, y) using lambda functions.

Tests to Satisfy:

Answer:

Question 2: List Comprehension
List comprehension is typically used to filter and transform lists.

Task: Write the function square_odds that takes a list of integers nums and returns the squares of the odd numbers in the list nums. You must use list comprehension. 

Tests to Satisfy:

Answer:

Question 3: Add Functions
We often use lambda functions as arguments to other functions. For example, if persons is a list of Person objects with a .name attribute, we could sort the list by name using:
persons.sort(key=lambda p: p.name)

In this question, we want you to write a function add_functions(f, g) which returns a function that accepts a single argument and returns f(x) + g(x)

In other words, we would use your function something like this:
f = add_functions(lambda x: x*2, lambda x: x + 1)
f(2)  # returns (2*2) + (2 + 1) = 7

Task: Write add_functions(f, g).

Tests to Satisfy:

Answer:

Question 4: Repeated Function Application
Task: Write a recursive function repeatedly_apply that takes as arguments a function f of one argument and a positive integer n. The result of repeatedly_apply is a function of one argument that applies f to that argument n times. 

Tests to Satisfy:

Answer:

, , ,

No comments yet.

Leave a Reply

Powered by WordPress. Designed by WooThemes

Free WordPress Themes