TheDude TheDude - 5 months ago 11x
Python Question

NoneType object is not iterable Error

I have the task to write classes for Dijkstra's Algorithm. Though I'm not allowed to edit the Dijkstra class:

class Dijkstra():
# initialize with a string containing the root and a
# weighted edge list
def __init__(self, in_string):
self.root, self.nnodes, self.adj_list = self.convert_to_adj_list(in_string)
self.nodes = [Node(i) for i in range(self.nnodes)]
self.nodes[self.root].key = 0
self.heap = MinHeap(self.nodes)
# the input is expected to be a string
# consisting of the number of nodes
# and a root followed by
# vertex pairs with a non-negative weight
def convert_to_adj_list(self, in_string):
nnodes, root, edges = in_string.split(';')
root = int(root)
nnodes = int(nnodes)
adj_list = {}
edges = [ map(int,wedge.split()) for wedge in edges.split(',')]
for u,v,w in edges:
for u in range(nnodes):

This is my problem:

string = '3; 0; 1 2 8, 2 0 5, 1 0 8, 2 1 3'
Traceback (most recent call last):
File "<pyshell#321>", line 1, in <module>
File "C:\Users\TheDude\Downloads\", line 71, in __init__
self.root, self.nnodes, self.adj_list = self.convert_to_adj_list(in_string)
TypeError: 'NoneType' object is not iterable

Do I assign
's return value? And how can I fix it w/o editing
class Djikstra()

Tanks for reading.


In order for the assignment

    self.root, self.nnodes, self.adj_list = self.convert_to_adj_list(in_string)

to work, convert_to_adj_list has to return a tuple of three values to be unpacked into those three variables. Your method, however, returns nothing (thus implicitly returning None). Change your convert_to_adj_list method to something like this, then it should work:

def convert_to_adj_list(self, in_string):
    ... your code ...
    return root, nnodes, adj_list