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.

  • You and some friends want to see what is going on at Cal before the big game. They might be planning something suspicous. To investigate, you plan to fly a drone over the football stadium in the days leading up to the game.

    Like any responsible drone pilot, you have plotted the flight path by writing down the direction, or heading, of the plane at each turn. An hour before the first takeoff, however, you realize that you didn't account for the magnetic deviation, or the local magnetic fields created by technology on the drone that mess with its internal compass reading. You also forgot to account for magnetic variation, or the difference between true north and magentic north. To account for magnetic deviation and variation, you must add 22 degrees to all of your heading calculations. Recall that the compass wraps around at 360 degrees, so any new heading calculated must also be between 0 and 359 degrees.

    Along with exact headings, you have also calculated if each turn is generally towards the North, East, South or West using the following buckets:

    • North: 316-45 degrees
    • East: 46-135 degrees
    • South: 136-225 degrees
    • West: 226-316 degrees

    Your job is to write an expression that given a list like so:

                  
                    original_headings = [(30, 'N'), (359, 'N'), (340, 'N'), (270, 'W'), (124, 'E'), (149, 'S'), (219, 'S')]
                  
                

    Produces a new list with the updated headings and directions after correcting for magnetic variation and deviation. You may implement any helper functions you want, but your top-level expression should be one line of code.

  • The weather outside has been really beautiful lately, but when Juliette went for her morning walk this morning, she got stung by a bee! To take retaliation against their species, she's jumbled up the 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 vector (a list of numbers), return the result of performing a linear transformation on it. To perform the linear transformation, multiply each element of the vector by the given scale and add the given shift. For example, for vector a = [1, 2], scale = 5, and shift = 6, the function should return [1 * 5 + 6, 2 * 5 + 6] = [11, 16]. You may assume that the input vector only contains numbers and that the passed in scale and shfit values are also numbers. Use a lambda function to represent the transformation for each term of the vector and the map function to create the resulting vector.
  • Your friend, the chairman of the Kentucky Derby, has come to you with a problem: he has a list of times for the horses in terms of number of seconds for the 1.25 mile track, but now he wants the times in terms of how long it would take the horses to run a 100 yard dash. Write a function that takes the horses' times (in terms of # seconds / 1.25 miles) and returns the horses' 100 yard dash times (# seconds / 100 yards). Assume that the horses run at a constant speed and at the same pace as in their Kentucky Derby times. For reference, there are 1760 yards in 1 mile. Use your map lambda skills to fill in the convert_times(times) function.

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

Tweets Revisited

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.