Functional python

Skip to end of metadata
Go to start of metadata

In this lab your goal is to get used to some of the constructs we looked at in Functional programming in Python.

Lambdas

 

  • Define the equivalent of the following function as a lambda

Iterators

  • Write an iterator class that, given a string via the constructor, returns a sequence of characters.  It should return 1 character for each next() invocation. Tested out with a for loop that prints out the characters.

List comprehensions

Assume the following data:

  • Using a list comprehension, create an array containing the words from names array whose length is greater than 3.
  • Create an array containing all uppercase versions of the elements in names array.
  • Create an array of tuples with the upper and lower case versions like [('PARRT','parrt'), ('KSB','ksb'), ...]
  • Create a list of tuples containing the index of the name and the name from names like [(1, 'parrt'), ...]. You will need the enumerate(names) function that returns a sequence of index,value pairs.

Generators

  • Create a generator function that recursively walks a list (it does not as we normally would iterate through it... you must use recursion) and yields the elements one by one. the code to do the recursive walk exists in the lecture notes but you must convert it to a generator function.

Higher-order functions

  • Write your own map(fun,list) function that takes a function and a list as arguments and then returns a list with fun applied to each element of list.

Write a function const(x) that returns a (nested) function that always returns x.

Labels: