Section #7 Solutions


Written by Elyse Cornwall

Using map Around the Globe

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

# Helper Function
def to_celcius(temp_f):
    return (temp_f - 32) * 5 / 9

temps_c = list(map(to_celcius, temps_f))



# Lambda Function
temps_c = list(map(lambda temp_f : (temp_f - 32) * 5 / 9, temps_f))
                    
                

Sorting, Min, and Max with Lambdas

                
                    
# A.
>>> sorted(houses, key=lambda tup:tup[1])
[('elm st.', 1, 1200), ('pine st.', 2, 1600), ('main st.', 4, 4000)]
# B.
>>> sorted(houses, key=lambda tup:tup[2], reverse=True)
[('main st.', 4, 4000), ('pine st.', 2, 1600), ('elm st.', 1, 1200)]
# C.
>>> sorted(houses, key=lambda tup:tup[2]/tup[1])
[('pine st.', 2, 1600), ('main st.', 4, 4000), ('elm st.', 1, 1200)]
# D. 
>>> min(houses, key=lambda tup:tup[2]/tup[1])
('pine st.', 2, 1600)
# E.
>>> max(houses, key=lambda tup: tup[1])
('main st.', 4, 4000)
                
            

Grocery Dictionaries, Revisited

                    
def reverse_keys(counts):
    """
    Takes in a counts dictionary and prints the
    keys of the dictionary in reverse alphabetical order.
    """
    foods = counts.keys()
    foods_reversed = sorted(foods, reverse=True)
    for food in foods_reversed:
        print(food)
                    
                
                
def most_used(counts):
    """
    Takes in a counts dictionary and prints the 5
    highest count foods in the dictionary.
    """
    count_tuples = counts.items()  # [('eggs', 3), ('coconut milk', 6) ...
    tuples_sorted = sorted(count_tuples, key=lambda t: t[1], reverse=True)  # sort tuples by count descending
    top_5 = tuples_sorted[:5]  # slice first 5 tuples
    
    for food, count in top_5:  # unpack tuple with loop
        print(food, count)
    """
    can also do:
    for tup in top_5:
        print(tup[0], tup[1])
    """