I am having this error:
Traceback (most recent call last):
File (...)
edge = random.choice(graph[node])
TypeError: unhashable type: 'list'
My code is as follows:
print(graph) # {'0': ['3'],
# '1': ['0'],
# '2': ['1', '6'],
# '3': ['2'],
# '4': ['2'],
# '5': ['4'],
# '6': ['5', '8'],
# '7': ['9'],
# '8': ['7'],
# '9': ['6']}
visited = {}
node = random.choice(list(graph.keys()))
print(node) # '9' for example
# edge = random.choice(graph[node]) ---> this prints ['6'] but fails inside the loop
while True:
edge = random.choice(graph[node]) # this is where it breaks
if node not in visited:
visited[node] = [edge]
else:
if visited[node] == edge:
break
else:
visited[node].append(edge)
if visited[node]==graph[node]:
break
node = graph[edge]
print(visited)
I've looked through other answers and they're all trying to index a dict with a list, but node is a string, which should work. The code right above the loop works, and I even tried with a different loop condition. I'm trying to get a random key and then get its value (trying to randomly walk in a directed graph). Thanks!
Aucun commentaire:
Enregistrer un commentaire