Map in Python

Just like in Snap, Python allows us to operate on all of the items of a list by using Higher Order Functions (HOFs). In python we can perform a map operation that squares all of the numbers in a list by using the following syntax:


>>> my_list = [1, 2, 3]
                    

>>> [x * x for x in my_list]                          
[1, 4, 9]
                    

Above you can see that the python code is very similar to the Snap code. Instead of having a multiply function with two blanks, as in the Snap version of map, we have x * x and we then specify that x in my_list. As a result, we see that we multiply each element of my_list by itself, producing the effect of squaring each number. Note: In both Snap and Python, map returns a new list and does not modify the old list.

To generalize this map-like functionality (also know as a list comprehension) we can use the following syntax to apply any function to the items of our list:


>>> [function(x) for x in my_list]
        

Keep in Python

In Python, keep has syntax that is similar to Python's map:


>>> my_list = [1, 1, 2, 3, 5, 9]
                    

>>> [x for x in my_list if x < 3]
[1, 1, 2]
                    

Just like Python's map, we can also generalize keep to be used with any function:


>>> [x for x in my_list if function(x)]
        

Using Map and Keep Together

Python also has some nice syntax that allows us to perform map and keep at the same time (you can also do this in Snap, but it's a little bit messy as shown to the right):


>>> my_list = [1, 1, 2, 3, 5, 9]
                    

>>> [x + 5 for x in my_list if x <  3] 
[6, 6, 7]
                    

Exercise 3.1: Substitute Base

Write the helper function substitute_base that takes as input a string representing a DNA sequence, a base to be substituted (old), and a base that is to take the place of the base being substituted (new). Old and New could be any letter, so make sure to keep your code general! This function should return a string with the proper base substituted:


>>> substitute_base("AAGTTAGTCA", "A", "C")
"CCGTTCGTCG"
        

Exercise 3.2: Substitue Sequences

Now imagine that we have a list of DNA sequences and we want to make a base substitution in all of them. Write the function substitute_sequences that takes as input a list of strings representing DNA sequences, a base to be substituted (old), and a base that is to take the place of the base being substituted (new). This function should return a list of DNA sequences with the proper base substituted in each sequence (make sure to use HOFs here):


>>> sequences = ["AAGTTAGTCA", "CTCGAGTCCGAAAGC", "AAGTTCCGACTG"]
>>> substitue_sequence(sequences, "A", "C")
["CCGTTCGTCC", "CTCGCGTCCGCCCGC", CCGTTCCGCTG"]
        

You can test these functions using the same command as in previous exercises, just replace the fucntion number with either 3.1 or 3.2