List into 2d List - "Triangle"
This is simple but I cannot figure out an elegant way to do this...
list = [1,2,3,4,5,6,7,8,9,10]
triangle = [[1],[2,3],[4,5,6],[7,8,9,10]]
What shape of loop is required to get from 'list' to 'triangle'. Assuming I want to do it to a list with thousands of values...
Posted Apr 2, 2013, 3:01 PM UTC
76
Let's take it step by step. What do we want? A list of slice of the original list with the slice length increasing by 1 for each iteration. Recursion is always fun for such problems.
[] if len(l) < iThe base case is when the slice lent is greater then the list lenght, so we return an empty list if the index is out of bounds.
Next we take the actual slice.
[l[:i]]We slice of the list by slicing a length i of the start of the list. To this we add the resulting list of the recursive call we will be doing next.
triangle(l[i:], i + 1)We pass two arguments to the recursive call. First the new list with the front sliced off, next the new slice length.
Some notes about this implementation. Recursion is not always the fastest way in python, so for more performance you might want to change it into a regular loop. For me this gave reasonable speed up to a list of 100,000 values.
Also, in this example I cut-off all the values not fitting in the triangle. If you don't like this simple change the base case to
[l] if len(l) < ito add the rest of the list to the end.This works perfectly. I will try and study it further to understand it fully. And possibly try a method which doesn't involve the recursive function ( just for practice)...
Here's a regular loop. In each pass you're adding a slice of the source list to the destination list, the starting index for the subsequent slice increases by the length, and the length for the subsequent slice increases by one. When the index reaches the end of the source list, the loop stops.
Here's a generator which accomplishes the same thing.