Traversal如何在python中解决这个问题?

问题描述

  • 编写一个函数traverse(),该函数接受tb列表,其中包含n个字符串,每个字符串包含n个小写字符 (a-z)。
  • tb表示具有n行和n列的方形表。该函数返回由下面的过程生成的字符串st,该字符串从左上角的单元格开始一直到右下角的单元格遍历网格。
  • 在每个步骤中,该过程将在水平方向上向右移动或在垂直方向上向下移动,具体取决于两个单元格中哪个具有“较小”字母(即,字母以字母顺序出现在较早的位置)。
  • 然后将已访问单元格中的字母添加到st。如果是平局,可以选择任何一个方向。
  • 到达表格的右边缘或底边缘时,显然只有一个唯一的下一个单元格要移动。例如,traverse(["veus","oxde","oxlx","hwuj"])返回"veudexj"

因此表将如下所示:

v  o  o  h
e  x  x  w
u  d  l  u
s  e  x  j

我是python的新手,我写了这段代码...但它只显示"veuexj",我想说问题出在这if new_list[a - 1][b - 1] == new_list[a - 1][-2]:上,这迫使参数跳过{{1} }字符。 #而且我不知道如何解决

'd'

解决方法

您可以尝试这样的操作(解释添加为注释):

def traverse(tb_list):
    lst = tb_list.copy() #Takes a copy of tb_list
    lst = list(zip(*[list(elem) for elem in lst])) #Transposes the list
    final = lst[0][0] #Sets final as the first element of the list
    index = [0,0] #Sets index to 0,0

    while True:
        x = index[0] #The x coordinate is the first element of the list
        y = index[1] #The y coordinate is the second element of the list

        if x == len(lst) - 1: #Checks if the program has reached the right most point of the table
            if y == len(list(zip(*lst))) - 1: #Checks if program has reached the bottommost point of the table
                return final #If both the conditions are True,it returns final (the final string)
            else:
                final += lst[x][y+1] #If the program has reached the right most corner,but not the bottommost,then the program moves one step down
                index = [x,y+1] #Sets the index to the new coordinates

        elif y == len(list(zip(*lst))) - 1: #Does the same thing in the previous if condition button in an opposite way (checks if program has reached bottommost corner first,rightmost corner next)
            if x == len(lst) - 1:
                return final
            else:
                final += lst[x + 1][y] #If the program has reached the bottommost corner,but not the rightmost,then the program moves one step right
                index = [x + 1,y]

        else: #If both conditions are false (rightmost and bottommost)
            if lst[x+1][y] < lst[x][y+1]: #Checks if right value is lesser than the bottom value
                final += lst[x+1][y] #If True,then it moves one step right and adds the alphabet at that index to final
                index = [x+1,y] #Sets the index to the new coords
            else: #If the previous if condition is False (bottom val > right val)
                final += lst[x][y+1] #Moves one step down and adds the alphabet at that index to final
                index = [x,y+1] #Sets the index to the new coords

lst = ["veus","oxde","oxlx","hwuj"]
print(traverse(lst))

输出:

veudexj

我已将解释添加为注释,请花一些时间进行解释。如果您仍然不清楚代码的任何部分,请随时问我。欢迎提供任何优化/缩短我的代码的建议。