-1

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
  • This is a simple logical error (the code in the top answer follows naturally from *thinking* about what needs to happen at the recursive step), and the question is not useful to most people who will stumble upon it. The title "flatten list of tuples" implies flattening after the fact. Alternately, this could be a duplicate of e.g. [How to collect results of recursive backtracking?](https://stackoverflow.com/questions/56917010/). – Karl Knechtel Sep 10 '22 at 09:10

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
  • 25,981
  • 9
  • 51
  • 65
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,495
  • 15
  • 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