此函数始终返回nonetype()。蟒蛇

时间:2017-03-08 07:55:25

标签: python algorithm tuples

(3, 2)
(2, 1)
(1, 8)
(8, 6)
(8, 7)
(7, 4)
(4, 5)

这是元组列表。该函数接受参数source和destination。它应该返回列表中从一个数字到另一个数字所需的步数。假设source为2且dest为8,则该函数应返回2个步骤。第一步是从2到1,然后下一步是1到8。

roads=[]                         #the list of tuples
for i in range(n-1):
    j,o=input("").split()
    roads.append((int(j),int(o)))

def dist(self, s, d):
    count,z,cn=0,0,0
    if s==d:                    #if the source and dest are the same
        return int(0)
    while z<len(roads):         #iterating over each tuple
        if s in roads[z]:
            if s==roads[z][0]:               
                for p in range(len(roads)):   #iterating again to check other if other member appears elsewhere in the list
                    if roads[z][1] in roads[p]:
                        cn+=1
                if cn>1:               #checking if the other member is a dead end  
                    s=roads[z][1]
                    count+=1           #increasing count for each step
                cn=0
            elif s== roads[z][1]:      #same thing again 
                for j in range(len(roads)):      
                    if roads[z][0] in roads[j]:
                        cn+=1
                if cn>1:
                    s=roads[z][0]
                    count+=1
                cn=0
        else:
            pass
        z+=1         #wrapping around if the list reaches the end
        if s==d:
            break    #if source reaches dest, breaking out
        if z==len(roads):
            z=0

    return count

但该函数总是返回nonetype()而不是int。我知道代码看起来很乱。你能帮忙吗?

代码说明:首先,元组存储在名为roads的元组列表中。然后在函数dist中,我迭代每个元组以查看源s是否存在于内部。如果我找到它,我会检查元组的另一个成员是否会导致死胡同。如果没有,那么我继续并使其他成员成为源s并继续迭代,当我到达列表末尾时回绕。直到我到达目的地d,然后我休息并返回计数。

0 个答案:

没有答案