Practice Problems

Lecture 11

Answer each number in a separate cell

Rename this notebook with your last name and the lecture

ex. CychB_11

Turn-in this notebook on TritonEd by the end of class

1. Lambda functions

  • Write a regular function s that takes one argument and returns the square of that argument
  • Write a lambda function called square that squares the input parameter
  • Call your function s with the value 4. Print the output
  • Call your function square with the value 4. Print the output

2. map( )

  • create a list of values from 0 to 300 in intervals of 10
  • create a list of values from 0 to 90 in intervals of 3
  • write an anonymous function that calculates the difference betwen two values
  • apply map( ) and the anonymous function to the two lists you defined
  • print the results of the map( ) function - remember to use list( ) to make a list from the list generator made by map( )

3. filter( )

  • Copy the following dictionary into a code cell:

    lastEruption = {"Mt.Etna": 2017, "Mt. St. Helens" :1980, "Mt. Erebus": 2017, "Mount Teide" : 1909, "Mt. Hood": 1800}

  • Define an anonymous function active that returns a boolean. It should return True if a volcano has erupted in the last 5 years

  • use the function filter( ), the function active, and the dictionary of volcanoes to determine which volcanoes have erupted in the last 5 years.
  • Print the names of the recently active volcanoes

4. reduce( )

  • write an anonymous function that finds multiples of 7
  • write a different anonymous function that returns the greater of two numbers
  • use your two anonymous functions with filter( ) and reduce( ) to find the greatest multiple of 7 in this list: [234, 55, 40, 100, 450, 335, 308, 693, 333, 405, 303, 109, 321, 565, 891]
  • print the final value

5. List comprehensions

  • The following dictionary, atomicNumbers, has the atomic number of an element as the key and the element name as the value

    atomicNumbers = {1:'H', 2:"He", 3: "Li", 4:"Be", 5:"B", 6:"C", 7: "N", 8:"O", 9:"F", 10:"Ne", 11:"Na", 12:"Mg", 13:"Al", 14:"Si", 15:"P", 16:"S", 17:"Cl", 18:"Ar"}

  • The following list, lifeElements, contains the atomic numbers essential for life

    lifeElements = [6,1, 8,7,15,16]

  • use a list comprehension to print out the names of the elements that are essential for life.

6. Dictionary comprehensions

  • The following list - elements- is a list of the first 18 elements in the periodic table

    elements = ["H", "He", "Li", "Be", "B", "C", "N", "O", "F", "N", "Na", "Mg", "Al", "Si", "P", "S", "Cl", "Ar"]

  • Create a dictionary comprehension of the elements and their atomic number. The key is the element name while the value is the atomic number
  • print the dictionary