supergravity

파이썬 - 재귀에서 return 이랑 아닌거 차이 본문

개발중 기억해야 할만한 것들/파이썬

파이썬 - 재귀에서 return 이랑 아닌거 차이

supergravity 2021. 8. 13. 17:29

아래 꺼는 안됨

위에 꺼는 됨

 

아래 꺼 같은 경우 return을 감싸고 있는 forloop가 돌다가 말음

리턴이 있는경우 진짜 끝나면 함수 자체를 리턴 시키고 종료해버림

def DFS(v, coms, parant, tw):
    print("new")
    print(str(v)*8)
    adj = coms[v]
    for i in range(len(adj)):
        # print(i)
        # print(parant)
        # print(i not in parant)
        # print(adj[i])
        tw += str(i)
        print(i not in parant and adj[i] == 1)
        if i not in parant and adj[i] == 1:
            parant.add(i)
            print("ok?")
            DFS(i, coms, parant, tw)
    # for vertex,is_connected in enumerate(coms[v]):
    #     print(vertex)
    #     if vertex not in parant and is_connected == 1:
    #         parant.add(vertex)
    #         print(vertex)
    #         print(parant)
    #         print("~~~")
    #         return DFS(vertex, coms, parant)
        
def solution(n, computers):
    answer = 0
    parant =set()
    tw = ''
    
    for ver in range(n):
        print(parant)
        if ver not in parant:
            print("start")
            parant.add(0)
            DFS(ver, computers, parant, tw)
            answer += 1
            
    return answer

print(solution(3, [[1, 1, 0], [1, 1, 0], [0, 0, 1]]), 2)
print(solution(3, [[1, 1, 0], [1, 1, 1], [0, 1, 1]]), 1)
print(solution(3, [[1, 0, 1], [0, 1, 0], [1, 0, 1]]), 2)
print(solution(4, [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]), 4)
print(solution(4, [[1, 1, 0, 1], [1, 1, 0, 0], [0, 0, 1, 1], [1, 0, 1, 1]]), 1)
def DFS(v, coms, parant, tw):
    print("new")
    print(str(v)*8)
    adj = coms[v]
    for i in range(len(adj)):
        # print(i)
        # print(parant)
        # print(i not in parant)
        # print(adj[i])
        tw += str(i)
        print(i not in parant and adj[i] == 1)
        if i not in parant and adj[i] == 1:
            parant.add(i)
            print("ok?")
            return DFS(i, coms, parant, tw)
    # for vertex,is_connected in enumerate(coms[v]):
    #     print(vertex)
    #     if vertex not in parant and is_connected == 1:
    #         parant.add(vertex)
    #         print(vertex)
    #         print(parant)
    #         print("~~~")
    #         return DFS(vertex, coms, parant)
        
def solution(n, computers):
    answer = 0
    parant =set()
    tw = ''
    
    for ver in range(n):
        print(parant)
        if ver not in parant:
            print("start")
            parant.add(0)
            DFS(ver, computers, parant, tw)
            answer += 1
            
    return answer

print(solution(3, [[1, 1, 0], [1, 1, 0], [0, 0, 1]]), 2)
print(solution(3, [[1, 1, 0], [1, 1, 1], [0, 1, 1]]), 1)
print(solution(3, [[1, 0, 1], [0, 1, 0], [1, 0, 1]]), 2)
print(solution(4, [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]), 4)
print(solution(4, [[1, 1, 0, 1], [1, 1, 0, 0], [0, 0, 1, 1], [1, 0, 1, 1]]), 1)
Comments