我在不使用任何模块的情况下需要递归解决一些问题,请您指导我。
您被放置在原点(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)
但是它出错了,可能是因为我无法正确想象递归的工作方式...
谢谢。
答案 0 :(得分:1)
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”。
希望这就是您想要的。