Thu, 27 Mar 2008

Something like Subsets

This is the first entry in what I'm calling my "list cookbook". When you deal with sets of things, you sometimes need to transform the sets to do something nifty with them. Here's the example that started me off on the cookbook idea.

Summary

Problem

Given a list {a, b, c, d, e}, what Mathematica commands will turn that into {{a}, {a, b}, {a, b, c}, {a, b, c, d}, {a, b, c, d, e}}?

Solution

Thanks to Mike Pilat of Wolfram Research:

In[1]:= list = {a, b, c, d, e}
Out[1]= {a, b, c, d, e}

In[2]:= Reverse[NestList[Most, list, Length[list] - 1]]
Out[2]= {{a}, {a, b}, {a, b, c}, {a, b, c, d}, {a, b, c, d, e}}

Variations

The beauty of Mike's solution is that by tweaking bits of it you can arrive at other possibly useful list transformations. Change Most to Rest and don't Reverse the list and you get:

In[3]:= NestList[Rest, list, Length@list - 1]
Out[3]= {{a, b, c, d, e}, {b, c, d, e}, {c, d, e}, {d, e}, {e}}

Similarly, but Reverse-ing the list before processing it:

In[4]:= NestList[Most, Reverse@list, Length@list - 1]
Out[4]= {{e, d, c, b, a}, {e, d, c, b}, {e, d, c}, {e, d}, {e}}

which is equivalent to swapping Rest for Most and Reverse-ing each element of the resulting list:

In[5]:= Reverse /@ NestList[Rest, list, Length@list - 1]
Out[5]= {{e, d, c, b, a}, {e, d, c, b}, {e, d, c}, {e, d}, {e}}

One more variation:

In[6]:= NestList[Rest, Reverse@list, Length@list - 1]
Out[6]= {{e, d, c, b, a}, {d, c, b, a}, {c, b, a}, {b, a}, {a}}

which is equivalent to:

In[7]:= Reverse /@ NestList[Most, list, Length@list - 1]
Out[7]= {{e, d, c, b, a}, {d, c, b, a}, {c, b, a}, {b, a}, {a}}