Section #7: Lambda, Map, & Sorted

November 7th, 2021


Written by Juliette Woodrow, Brahm Capoor, Anna Mistele, and John Dalloul


Using map

Solve each of these problems using the map function described in lecture.

  • 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, one of you is 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]
                  
                

    Write an expression to produce a list of those same temperatures, measured in degrees Celsius. As a reminder, to convert Farenheit to Celsius, you first subtract 32 and then multiply by 59.

  • Here is the jumbled up script of the Bee Movie:
                    
                    
    s = """
    gnidroccA ot lla nwonk swal fo ,noitaiva ereht si on yaw a eeb dluohs eb 
    elba ot .ylf stI sgniw era oot llams ot teg sti taf elttil ydob ffo eht 
    .dnuorg ehT ,eeb fo ,esruoc seilf yawyna esuaceb seeb t'nod erac tahw snamuh 
    kniht si .elbissopmi
    """
                    
                  
    Juliette took every word in the script, and reversed it! Write an expression to fix this, returning the first few lines of the Bee Movie script, in the correct order.
  • Given a list of integers called nums, write an expression that creates a new list which has all of the numbers in the original list but tripled.
  • Given a list of strings called strs, write an expression that creates a new list which has all of the strings in the original list but each char is duplicated. For example, strs = ['cs106a', 'python'] would turn into strs = ['ccss110066aa', 'ppyytthhoonn']. Recall the double_char function we did earlier this quarter as you complete this problem.
  • Given a list of strings that are all numbers called num_strs, write an expression that creats a new list which has the int verions of all of the strings in the original list.

Sorting with lambdas

Solve each of the following challenges in one line of Python, using the lambda technique:

  1. Given a list of strings strs, sort the list case-insensitively (i.e. ignoring whether the word is upper or lower case).
  2. Given a list of strings strs, sort the list according to the last character of each string, case-insensitively.
  3. Given a list of integers nums, sort the list according to the absolute difference between each number and 3.14. Python has an abs function, which takes as input a number and returns its absolute value, and which you might find helpful in this problem.
  4. Given a list of tuples that represents houses for rent, the number of bedrooms and their prices, like so:
                  
                    [('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 ascending 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)

Tweets Revisited

You will need Friday's lecture to complete this problem :) Recall the Big Tweets Data problem from last week, in which we worked with a user_tags dictionary whose keys were twitter usernames and whose values were additional nested dictionaries keeping track of the frequencies of Hashtag usage, like so:

            
          
user_tags = {'@alice': {'#apple': 1, '#banana': 2}, '@bob': {'#apple': 1}}
            
        

One of the suggested extensions for this problem was to implement a function called flat_counts, which takes in a user_tags and returns a dictionary that counts the number of times each Hashtag is used, across all users. For example, calling flat_counts and passing the user_tags dictionary in as a parameter would lead to the following behaviour:

            
          
>>> flat_counts(user_tags)
{'#apple': 2, '#banana': 2}
            
        

In Python, dictionaries have a built-in items() function that returns a list of (key, value) tuples.

  1. First, armed with the .items() function and your new toolkit for sorting, implement a function, reverse_alpha_keys(flat_counts), which given a flat_counts dictionary, prints out the hashtags in reverse aplphabetical order. Note that the sorted function will break ties using the next consecutive character in the string.
  2. Second, implement the following function: def most_used(flat_counts) which takes in a 'flat' dictionary as described above, and prints the 10 most frequently used hashtags in the dataset. With a solid understanding of how lambdas can be used in sorting, you should be able to solve this in just a few lines of code.