Posted by Jason Polak on 18. February 2018 · Write a comment · Categories: computer-science · Tags: , ,

Let’s look at Python’s map function. What does this function do? Here is the syntax:

It takes a function called function and applies it to each element of iterable, returning the result as an iterable. For example:

The output of this program is:

If you want to convert the returned iterable back into a list, that’s easy:

The output here is “[1, 4, 9, 16]”. Using map is cleaner and easier than writing a loop. What are some uses of this feature? Let’s look at a real-world example using Sage, that often comes up in mathematical programming.

Let’s suppose you have a list containing all the elements of a finite set $S$. Say for concreteness your list is [a,x,0,y,m]. You permute this list to [x,m,y,a,0]. What is the corresponding permutation in cycle notation?

Sage has a function PermutationGroupElement that takes a permuted list of positive integers and returns the corresponding permutation in cycle notation. For instance:

Here, I’ve indicated the output of the function with an angle bracket. But this function only takes lists of positive integers. Here is how to use the map function to quickly convert a custom permuted list to a list of positive integers so that it works with the function PermutationGroupElement:

This code prints “(1,2,5,3,4)”, which is exactly the cycle notation for the permutation that takes originalList to permutedList. Notice that we had to add one to the index, because indices in Python start at zero, whereas permutation groups in Sage canonically operate on finite sets of positive integers, starting at one.

In general, if you need to make a new list (or just iterate over the elements of a new list) from an old one, chances are you should use map instead of writing a loop.

Leave a Reply

Your email address will not be published. Required fields are marked *