Reputation: 11
So basically we have some textfiles which contain in 'pickled' format a dictionary of dictionaries. An example would be this:
{'1': {'3': 3, '2': 5, '4': 8},
'3': {'5': 4, '6': 8},
'2': {'3': 3, '4': 2},
'5': {'4': 4, '6': 3},
'4': {'3': 4, '6': 2},
'7': {'4': 5},
'6': {}}
Now this actually represent a graph, and the keys of the main dictionary(1 until 7) are the nodes of this graph, and each of these nodes/keys contain as values another dictionary, and in this dictionary the keys represent the nodes the original node has an arc with and after each key the distance(so if we look at key '1' in the main dictionary, we see that is has arcs with the nodes 3, 2 and 4, with respectively the distances 3, 5 and 8). Sorry if this is confusing.
Basically, I need to write 4 functions:
IsArc(graph, n1, n2)
Answers the question: Does graph contain an arc from n1 to n2 ?
LenArc(graph, n1, n2)
Answers the question: What is the length of the arc from n1 to n2 ?
Returns 1000000 if there is no arc from n1 to n2 in graph.
NodeSet(graph)
Returns the set of all nodes in graph.
PrintSet(s)
Prints the elements of set s in lexicographical (alphabetical) order.
This is what I have now:
def IsArc(graph, n1, n2):
return graph[n1].has_key('n2')
LenArc(graph, n1, n2):
if IsArc(graph, n1, n2)==True:
return graph[n1][n2]
else:
return inf
def NodeSet(graph):
setlist=[]
for k, v in graph.iteritems():
setlist.append(k)
setnode=set(setlist)
return setnode
def PrintSet(s):
listset=[]
for nodes in s:
listset.append(nodes)
listalpha=listset.sort()
output=""
for i in range(0, n):
output+= listalpha[i]
print output
However, IsArc
always seems to return 'False'
for me, and consequently LenArc
always returns 1000000 since it depends on IsArc
to give the right value.
Also, I want PrintSet(s)
to print the elements of any given set like this:
{element1, element 2, element 3, ..... , lastelement }
but I'm not really sure how to do this. The only function that does seem to work good though is NodeSet(graph)
.
BTW my python version is 2.7.11
Upvotes: 0
Views: 52
Reputation: 5243
The error is that you are looking for a key named 'n2':
def IsArc(graph, n1, n2):
return graph[n1].has_key('n2')
when you should look for a key named n2:
def IsArc(graph, n1, n2):
return graph[n1].has_key(str(n2))
Also, consider simplifying NodeSet as follows:
def NodeSet(graph):
return set(graph.keys())
Upvotes: 1