Python - 使用矩阵和文本文件检查字符串路径是否有效

时间:2016-11-06 14:37:06

标签: python file matrix graph

我是初学者的第一年编程课程,我们使用Python编写代码。上一次,我们已经了解了文本文件,图形和邻接矩阵。我被困在一次练习中,我真的不知道从哪里开始......

根据已经提供给我们的图表,我们构建了一个邻接矩阵。练习要求我们打开文本文件,在里面写入不同的数字字符串,然后编写代码来测试这些路径在图表上是否有效或不使用我们构建的矩阵(例如,1245,12345是有效路径, 135 isn&t; t)。

我完全失去了,并且真的不知道如何解决这个问题。我接受了编程,因为我觉得它很有趣(它确实如此),但我之前并不知道它,而且我有时候很难解决这些问题。你能告诉我一下该做什么吗?当然,我不需要完整的答案(这会适得其反),但我至少知道如何开始...

这是我的矩阵和我的文本文件,如果有任何帮助的话:

newfile = open("textexercise.txt", "r+")
newfile.write("12345\n")
newfile.write("1245\n")
newfile.write("15432\n")
newfile.write("35421\n")
newfile.write("512\n")
newfile.write("354\n")
newfile.write("135\n")
newfile.write("134\n")
newfile.write("415\n")
newfile.write("5234\n")


myList = []
myList.append([])
myList.append([])
myList.append([])
myList.append([])
myList.append([])
myList[0] = [False,True,False,False,True]
myList[1] = [True,False,True,True,False]
myList[2] = [False,True,False,True,True]
myList[3] = [False,True,True,False,True]
myList[4] = [True,False,True,True,False]
如果这是一个愚蠢的问题,我道歉。我对这一切都很陌生。祝你有愉快的一天!

1 个答案:

答案 0 :(得分:0)

对不起,长时间的谈话。我需要一段时间才能理解您的代码块中包含的内容。这是一段帮助的代码片段。代码的本质如下:

  • 将路径字符串转换为0到4
  • 的索引列表
  • 为路径的每个步骤创建一对开始和结束节点
  • 每个步骤对的第一个元素是行索引,第二个是邻接矩阵的列索引。
  • 检查每一步,如果它达到False值,请停止并返回False
# define a function to text the path
def test_path(adj_m, path_str):
    # turn the node number into a list index.  need to 
    # subtract 1 from each element since python is zero-indexed
    path = [int(x)-1 for x in list(path_str.strip())]

    # create pairs of nodes uzing zip.  this will turn the path 0,1,2,4
    # into (0,1), (1,2), (2,4)
    for a,b in zip(path, path[1:]):
        # check the row and column of the adjacency matrix, stopping if
        # path is forbidden, return False
        if not adj_m[a][b]:
            return False
    # if the we make it through the entire for-loop, then all paths are
    # valid, return True
    return True