Section #7 Solutions


Written by Juliette Woodrow, Brahm Capoor, Anna Mistele, John Dalloul, and 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)
                
            

Big Tweets, Revisited

                    
def reverse_keys(counts):
    """
    Takes in a 'flat' counts dictionary and prints the
    keys of the dictionary in reverse alphabetical order.
    """
    tags = counts.keys()
    tags_reversed = sorted(tags, reverse=True)
    for tag in tags_reversed:
        print(tag)
                    
                
                
def most_used(counts):
    """
    Takes in a 'flat' counts dictionary and prints the 5 most
    frequently used hashtags in the dataset.
    """
    count_tuples = counts.items()  # [('#cs106a', 9), ('#Stanford', 2), ... ]
    tuples_sorted = sorted(count_tuples, key=lambda t: t[1], reverse=True)  # sort by count descending
    top_5 = tuples_sorted[:5]  # slice first 5 tuples

    for tup in top_5:
        print(tup[0], tup[1])