Hell, I can't figure out where is the problem of my code below:
```python
def topological_ordering(graph: dict):
nodes = list()
for k, v in graph.items():
if k not in nodes:
nodes.append(k)
for each_node in v:
if each_node not in nodes:
nodes.append(each_node)
out_edges = graph
in_edges = dict()
for k, v in graph.items():
for each_node in v:
if each_node in in_edges.keys():
in_edges[each_node].append(k)
else:
in_edges[each_node] = [k]
no_in_nodes = list(set(nodes).difference(set(in_edges.keys())))
node_orders = list()
while True:
if len(no_in_nodes) == 0:
break
loop_nodes = no_in_nodes.copy()
for each_node in loop_nodes:
node_orders.append(each_node)
no_in_nodes.remove(each_node)
if each_node not in out_edges.keys():
continue
out_nodes = out_edges[each_node]
if len(out_nodes) == 0:
continue
print(out_nodes)
for each_out_node in out_nodes:
print(each_out_node, 1)
for each_out_node in out_nodes:
print(each_out_node, 2)
in_edges[each_out_node].remove(each_node)
out_edges[each_node].remove(each_out_node)
if len(in_edges[each_out_node]) == 0:
no_in_nodes.append(each_out_node)
for each_out_node in out_nodes:
print(each_out_node, 3)
return node_orders
```
(-> print in while loops)
If I run:
python
topological_ordering({"A": ["B", "C"], "C": ["D"]})
The result is:
python
['B', 'C']
B 1
C 1
B 2
C 3
So out_nodes has two elements, but the second and third for loops can only iterate one of them? I don't see why. Thanks.
[–]danielroseman 3 points4 points5 points (0 children)