0

I am using a recursive function to create a flow path through a maze. The function returns the correct path tuples (row,col), but I need it in the form of a List of tuples. For example I need to create this form

[(0,0),(1,1),(2,2),(3,3),(4,3)]

However the function returns this:

[(0, 0), [(1, 1), [(2, 2), [(3, 3), (4, 3)]]]]

Here is the function:

def FlowPathAt(fdir,row,col):
    lItem = FlowOut(fdir,row,col)
    if not lItem:
        return (row,col)
    else:
        r,c = lItem
        return [(row,col) ,  FlowPathAt(fdir,r,c)]

FlowOut(fdir,row,col) is a function that returns the next cell address starting at (row,col)

Is there any way to flatten this list during the build?

Similar: How to flatten a list of tuples into a pythonic list

Community
  • 1
  • 1

2 Answers2

6

Try this:

def FlowPathAt(fdir,row,col):
    lItem = FlowOut(fdir,row,col)
    if not lItem:
        return [(row,col)] # More convenient base case
    else:
        r,c = lItem
        return [(row,col)] + FlowPathAt(fdir,r,c) # Append list to list instead of nesting

(This always returns a list of tuples, too, which just seems like a better idea than sometimes returning a list and sometimes returning a single tuple. If that's not acceptable, you'll need to do some post-processing.)

Cairnarvon
  • 23,682
  • 9
  • 49
  • 64
4

That's alot of memory management for list growth, why not refactor it into a generator function:

def FlowPathAt(fdir, row, col):
    while True:
        yield row, col
        lItem = FlowOut(fdir, row, col)
        if lItem is None: break
        row, col = lItem
mtadd
  • 2,415
  • 14
  • 18
  • Thank you for the input, I will try this approach. Have only been working with Python for a couple of weeks but I really like this language. Also, this site is really helpful to get answers. Thanks to all of you who help others learn. – user2278537 Apr 14 '13 at 04:38