Section #7: Lambda, Map, & Sorted


Written by Elyse Cornwall


Using map Around the Globe

You and your freshman year roommate grew up in different countries. You often have trouble trying to explain the current temperature outside as one of you is familiar with degrees Celsius and the other is used to using degrees Fahrenheit. Fortunately, you're taking 106A and can help!

Given a list of temperatures in degrees Farenheit like so:

              
                temps_f = [45.7, 55.3, 62.1, 75.4, 32.0, 0.0, 100.0]
              
            

We're going to use map to produce a list of those same temperatures, converted to degrees Celsius. First we'll use map with a helper function, and then we'll use map with a lambda function. To convert Farenheit to Celsius, you first subtract 32 and then multiply by 59.

Def

Write a helper function def to_celcius(temp_f) that takes in a float representing a temperature in Fahrenheit temp_f, and returns that temperature in Celcius. Once you've written your helper function, write a map statement to apply this helper function to every item in our list temps_f and create a new list temps_c that contains the temperatures in Celcius.

Lambda

Now, write a map statement using a lambda function and create your new temps_c list this way. Don't use your helper function this time - write all the code inside the map!

You can write your code in using_map.py in the PyCharm project, and test it by running python3 using_map.py. Hint: If you're running this and getting something like map object at 0x7fe8201bddf0, cast your map expression to a list like so: list(map(... )).


Sorting, Min, and Max with Lambdas

Given a list of tuples that represent houses for rent, the number of bedrooms, and their prices, like so:
              
                houses = [('main st.', 4, 4000), ('elm st.', 1, 1200), ('pine st.', 2, 1600)]
              
            

Sort the list in the following ways:

  1. In ascending order by number of rooms
  2. In descending order of price
  3. In ascending order of price-per-room
  4. Least expensive price-per-room (use min function)
  5. Most number of rooms (use max function)

A good way to quickly test your code is by running it in the terminal. Open a new terminal and type either python3 or py to start the Python interpreter. Then you can enter code line-by-line and see the results:

          
$ python3
>>> houses = [('main st.', 4, 4000), ('elm st.', 1, 1200), ('pine st.', 2, 1600)]   # define houses list
>>> list(sorted(houses, reverse=True))                                              # sort in reverse alphabetical order
[('pine st.', 2, 1600), ('main st.', 4, 4000), ('elm st.', 1, 1200)]                # see sorted result
          
        

Grocery Dictionaries, Revisited

Let's take a look at one of the inner nested dictionaries from last week's section, where each key is an item name and each value is how many of that item we need to buy at the store:

          
counts = {'eggs': 3, 'coconut milk': 6, 'flour': 1, 'M&Ms': 5, 'croissant': 12, 'coffee': 2}
            
        

Reverse Keys

Recall the dictionary functions keys() and values() that return a list of keys or values respectively:

            
>>> counts.keys()
dict_keys(['eggs', 'coconut milk', 'flour', 'M&Ms', 'croissant', 'coffee'])

>>> counts.values()
dict_values([3, 6, 1, 5, 12, 2])
              
          

Write a function reverse_keys(counts) that prints the items in a counts dictionary in reverse alphabetical order (note how uppercase letters come after lowercase ones, this is just how alphabetical sorting works):

            
flour
eggs
croissant
coffee
coconut milk
M&Ms         
              
          

Test your implementation by running python3 groceries_revisited.py -reverse long-list.txt in the terminal.

Top 5 Items

In Python, there's a dictionary function items() that returns a list of key-value tuples:

            
>>> counts.items()
dict_items([('eggs', 3), ('coconut milk', 6), ('flour', 1), ('M&Ms', 5), ('croissant', 12), ('coffee', 2)])
              
          

Now, with help from the items() function, implement a function, most_used(counts), which given a counts dictionary, prints the 5 foods we need the most of with their counts, in order. For example, most_used(counts) for the counts dictionary shown above would print:

            
croissant 12
coconut milk 6
M&Ms 5
eggs 3
coffee 2
              
          

Test your implementation by running python3 groceries_revisited.py -most long-list.txt in the terminal.