[python] ‘dict’개체에 ‘has_key’속성이 없습니다.

Python에서 그래프를 탐색하는 동안 다음 오류가 발생합니다.

‘dict’개체에 ‘has_key’속성이 없습니다.

내 코드는 다음과 같습니다.

def find_path(graph, start, end, path=[]):
    path = path + [start]
    if start == end:
        return path
    if not graph.has_key(start):
        return None
    for node in graph[start]:
        if node not in path:
            newpath = find_path(graph, node, end, path)
            if newpath: return newpath
    return None

이 코드는 한 노드에서 다른 노드로의 경로를 찾는 것을 목표로합니다. 코드 소스 : http://cs.mwsu.edu/~terry/courses/4883/lectures/graphs.html

이 오류가 발생하는 이유는 무엇이며 어떻게 해결할 수 있습니까?



답변

has_keyPython 3에서 제거되었습니다. 문서에서 :

  • 제거됨 dict.has_key()in대신 연산자를 사용합니다 .

예를 들면 다음과 같습니다.

if start not in graph:
    return None


답변

has_keyPython 3.0 에서 더 이상 사용되지 않습니다 . 또는 ‘in’을 사용할 수 있습니다.

graph={'A':['B','C'],
   'B':['C','D']}

print('A' in graph)
>> True

print('E' in graph)
>> False


답변

python3에서 다음 has_key(key)으로 대체됩니다.__contains__(key)

python3.7에서 테스트되었습니다.

a = {'a':1, 'b':2, 'c':3}
print(a.__contains__('a'))


답변

in키가 이미 존재하는지 결정할 때 사용하는 것이 “더 비단뱀 적”이라고 생각합니다 .

if start not in graph:
    return None


답변

문서의 전체 코드는 다음과 같습니다.

graph = {'A': ['B', 'C'],
             'B': ['C', 'D'],
             'C': ['D'],
             'D': ['C'],
             'E': ['F'],
             'F': ['C']}
def find_path(graph, start, end, path=[]):
        path = path + [start]
        if start == end:
            return path
        if start not in graph:
            return None
        for node in graph[start]:
            if node not in path:
                newpath = find_path(graph, node, end, path)
                if newpath: return newpath
        return None

작성한 후 문서를 저장하고 F5를 누릅니다.

그 후 Python IDLE 셸에서 실행할 코드는 다음과 같습니다.

find_path (그래프, ‘A’, ‘D’)

IDLE에서 받아야 할 답변은

['A', 'B', 'C', 'D'] 


답변

시험:

if start not in graph:

자세한 내용은 ProgrammerSought를 참조하십시오.


답변