简体   繁体   中英

Modifying a recursive function that counts no. of paths, to get sequence of all paths

I've written a simple recursive Python program to find the number of paths in a triangle of characters.

Btw, this is an attempt to solve Project Euler's P18.

triangle = """\
75
95 64
17 47 82
18 35 87 10
20 04 82 47 65
19 01 23 75 03 34
88 02 77 73 07 63 67
99 65 04 28 06 16 70 92
41 41 26 56 83 40 80 70 33
41 48 72 33 47 32 37 16 94 29
53 71 44 65 25 43 91 52 97 51 14
70 11 33 28 77 73 17 78 39 68 17 57
91 71 52 38 17 14 91 43 58 50 27 29 48
63 66 04 68 89 53 67 30 73 16 69 87 40 31
04 62 98 27 23 09 70 98 73 93 38 53 60 04 23"""

grid = triangle.split("\n")
grid[:] = [[int(n) for n in (line.split())] for line in grid]

def find_paths(x,y):

    n = 0
    if x == 14:
        return 1

    n += find_paths(x+1,y+1)
    n += find_paths(x+1,y)

    return n


print find_paths(0, 0)

This successfully prints 16384. However, how can I modify this same function to simply get a list of all the paths for eg. [[(0,0),(1,0)...(14,0)],[(0,0),(1,0)...]] ? Or if it takes too much memory, simply print each path instead of storing them in a list..

Thanks!

The idea is exactly the same as your function, except that you return a tuple of coordinates instead of increasing a counter by 1 when you reach the bottom. By making it a generator you only create the paths as you need them.

def generate_paths(depth, x=0, y=0):
    if x == depth:
        yield ((x, y),)
    else:
        for path in generate_paths(depth, x+1, y):
            yield ((x, y),) + path
        for path in generate_paths(depth, x+1, y+1):
            yield ((x, y),) + path

Examples.

>>> for path in generate_paths(3):
...    print(path)

((0, 0), (1, 0), (2, 0), (3, 0))
((0, 0), (1, 0), (2, 0), (3, 1))
((0, 0), (1, 0), (2, 1), (3, 1))
((0, 0), (1, 0), (2, 1), (3, 2))
((0, 0), (1, 1), (2, 1), (3, 1))
((0, 0), (1, 1), (2, 1), (3, 2))
((0, 0), (1, 1), (2, 2), (3, 2))
((0, 0), (1, 1), (2, 2), (3, 3))
>>> print(len(tuple(generate_paths(14))))
16384

This generates all the paths in less than a second. However, just as the problem suggests, you're encouraged to find a more efficient because the complexity is exponential and for longer depths this will be infeasible.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM