【问题标题】:Print all paths from origin to destination on board using recursion - Python使用递归打印从起点到目的地的所有路径 - Python
【发布时间】:2018-12-05 10:20:43
【问题描述】:

我有一些问题需要在不使用任何模块的情况下递归解决,请您指导我。

你被放置在原点 (0, 0) 的格子板上,你想到达目的地 n,k(即 n 向右移动,k 向上移动)。我们一次只能向右或向上移动一步。实现一个函数,接收两个数字 n, k 并打印所有到达目的地 n, k 的路径,仅通过向右或向上步进。向上一步用“u”表示,向右用“r”表示。每条路径都必须是一系列字符 u、r,并且每条路径都必须打印在一行中。

我已经尝试过做某事:

def paths_ur(n, k):
    paths_ur_helper(n, k, 0, 0)

def paths_ur_helper(n, k, right_moves, up_moves):
    if right_moves == n and up_moves == k: #If we reach the destination there is nothing to return
        return []
    if right_moves < n and up_moves < k: #Check that we are in range of the board
        return 'r' + paths_ur_helper(n, k, right_moves + 1, up_moves) + 
        \ +'u' + paths_ur_helper(n, k, right_moves, up_moves + 1)

但它出错了,可能是因为我没有正确想象递归的工作方式......

谢谢。

【问题讨论】:

    标签: python-3.x recursion combinations recursive-backtracking


    【解决方案1】:

    我能想到的最简单的逻辑:

    1. 确定目的地的 x、y 坐标。起始坐标为 (0,0)
    2. 创建一个字符串,其中 'u' 和 'r' 分别代表垂直和水平距离。
    3. 使用 itertools.permutations 查找上述字符串的所有可能排列并附加到以前的空白列表中。
    4. 打印列表中的每个唯一元素。

    实现代码:

    from itertools import permutations
    from more_itertools import unique_everseen
    
    x = (0,0)  # start point tuple
    y = (1,2)  # End point tuple // You can also get this dynamically via user input, if needed
    h = y[0] - x[0]  # horizontal distance (difference of x-coordinates of DST, SRC
    v = y[1] - x[1]  # vertical distance (difference of y-coordinates of DST, SRC
    plist = [] # blank list to store permutation result
    path = 'u'*h + 'r'*v  # gives result as 'uur' (two up and one right, in this case)
    for  subset in (permutations(path, h+v)): # use permutations on the path string
        plist.append(subset)                  # append each result to the plist
    # print (plist)                           // Optional to verify the code
    for item in list(unique_everseen(plist)):
        print ("{}\n".format(item))           # Print unique values from plist in a new line
    

    由于某种原因,permutations 模块正在返回重复项。因此使用了“unique_everseen”。 希望这是你想要的。

    【讨论】:

    • 在使用非常远的点时请小心,因为它会返回一个巨大的列表并在这样做时占用太多内存。
    • 我明白了,这很酷。对不起,我没有提到它,但我不能使用某些模块来解决问题。我怎样才能克服模块?谢谢!
    • 如果不是模块,您可以使用函数定义对您的代码进行排列。请参阅文档:docs.python.org/3/library/itertools.html#itertools.permutations 对于唯一值,如果需要,可以使用更简单的解决方法。
    • 顺便说一句,您能否在问题中针对社区中的其他顾客提出该规定?
    • 已编辑。我没有学习yield的方法,所以我不明白您发送的代码,但我会尝试一下。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2019-01-04
    • 2017-04-03
    • 2018-01-29
    • 1970-01-01
    • 2021-05-16
    • 1970-01-01
    • 2021-03-15
    • 1970-01-01
    相关资源
    最近更新 更多