Python Key Error 0 - Can t find Dict error in code

0 votes

basically I have been racking my brains for a good while now as to why my code is not working, I have tested parts separately and have look throughout the web to see if it can help, to no avail. I am getting an error that the traceback is:

Traceback (most recent call last):
File "yes2.py", line 62, in <module>
g.add_edge(row_index,col_index, b)
File "yes2.py", line 27, in add_edge
self.adj[u].append(edge) 
KeyError: 0

The two parts with errors are

    def add_edge(self, u, v, w=0): 
    if u == v: 
        raise ValueError("u == v") 
    edge = Edge(u,v,w) 
    redge = Edge(v,u,0) 
    edge.redge = redge 
    redge.redge = edge 
    self.adj[u].append(edge) #### LINE 27 ####
    self.adj[v].append(redge) 
    self.flow[edge] = 0 
    self.flow[redge] = 0 

and

g = FlowNetwork()
map(g.add_vertex, ['0','1','2','3','4','5','6'])
with open('network.txt', "r") as file:
for row_index, row in enumerate(file):
    for col_index, value in enumerate(row.split(",")):
        b = int(value)
        if b != 0:
            g.add_edge(row_index,col_index, b) ### LINE 62 ####

And here is the completed code, as without this it may be difficult to see what is happening

class Edge(object):
def __init__(self, u, v, w):
    self.source = u
    self.sink = v 
    self.capacity = w 
def __repr__(self): 
    return "%s->%s:%s" % (self.source, self.sink, self.capacity) 

class FlowNetwork(object): 
def __init__(self): 
    self.adj = {} 
    self.flow = {} 

def add_vertex(self, vertex): 
    self.adj[vertex] = [] 

def get_edges(self, v): 
    return self.adj[v] 

def add_edge(self, u, v, w=0): 
    if u == v: 
        raise ValueError("u == v") 
    edge = Edge(u,v,w) 
    redge = Edge(v,u,0) 
    edge.redge = redge 
    redge.redge = edge 
    self.adj[u].append(edge) 
    self.adj[v].append(redge) 
    self.flow[edge] = 0 
    self.flow[redge] = 0 

def find_path(self, source, sink, path): 
    if source == sink: 
        return path 
    for edge in self.get_edges(source): 
        residual = edge.capacity - self.flow[edge] 
        if residual > 0 and not (edge,residual) in path: 
            result = self.find_path( edge.sink, sink, path + [(edge,residual)] ) 
            if result != None: 
                return result 

def max_flow(self, source, sink): 
    path = self.find_path(source, sink, []) 
    while path != None: 
        flow = min(res for edge,res in path) 
        for edge,res in path: 
            self.flow[edge] += flow 
            self.flow[edge.redge] -= flow 
        path = self.find_path(source, sink, []) 
    return sum(self.flow[edge] for edge in self.get_edges(source)) 

g = FlowNetwork()
map(g.add_vertex, ['0','1','2','3','4','5','6'])
with open('network.txt', "r") as file:
# enumerate allows you to iterate through the list with an index and an object
for row_index, row in enumerate(file):
    # split allows you to break a string apart with a string key
    for col_index, value in enumerate(row.split(",")):
        #convert value from string to int
        b = int(value)
        if b != 0:
            g.add_edge(row_index,col_index, b)

print g.max_flow('1','6')

Many thanks for your time, much appreciated.

Dec 22, 2022 in Python by erzan
• 630 points
473 views

No answer to this question. Be the first to respond.

Your answer

Your name to display (optional):
Privacy: Your email address will only be used for sending these notifications.

Related Questions In Python

0 votes
1 answer

Python Error: Can't find '_main_' module in 'C:/Users/DELL/Pythonprojects/Aks'

I can see there no Python file ...READ MORE

answered Jun 25, 2020 in Python by Karan
• 19,610 points
3,662 views
0 votes
1 answer

Key error in Python

A KeyError occurs when the Key doesn't ...READ MORE

answered Sep 20, 2018 in Python by SDeb
• 13,300 points
1,477 views
0 votes
2 answers

Python Error "UnicodeEncodeError: 'ascii' codec can't encode character u'\u03b1' in position 20: ordinal not in range(128)"

import csv import sys reload(sys) sys.setdefaultencoding('utf8') data = [["a", "b", u'\xe9']] with ...READ MORE

answered Jun 28, 2019 in Python by anonymous
13,883 views
0 votes
1 answer

Is it possible to find the source code of built-in functions of Python?

Since Python is open source you can ...READ MORE

answered Jul 17, 2019 in Python by Neel
• 3,020 points
4,778 views
0 votes
3 answers
0 votes
2 answers
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 7, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 4,434 views
0 votes
1 answer
+5 votes
6 answers

Lowercase in Python

You can simply the built-in function in ...READ MORE

answered Apr 11, 2018 in Python by hemant
• 5,790 points
4,070 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP