Reputation: 1
Here is My Python Code is given below:-
import networkx as nx
import matplotlib.pyplot as plt
from random import choice
g=nx.Graph()
city_set=['Delhi','Lucknow','Indore','Kolkata','Hyderabad','Chennai',
'Tivandrum','Banglore','Pune','Mumbai','Surat','Ahmedabad','Jaipur']
for each in city_set:
g.add_node(each)
costs=[]
value =100
while(value<=2000):
costs.append(value)
value=value+70
while(g.number_of_edges()<24):
c1=choice(g.nodes())
c2=choice(g.nodes())
if c1!=c2 and g.has_edge(c1,c2)==0:
w=choice(costs)
g.add_edge(c1,c2,weight=w)
nx.draw(g,with_labels=1)
plt.show(g)
and while compiling the code I got the error stated below:-
$ python cities.py
Traceback (most recent call last):
File "cities.py", line 22, in <module>
c1=choice(g.nodes())
File "/usr/lib/python2.7/random.py", line 277, in choice
return seq[int(self.random() * len(seq))] # raises IndexError if seq
is empty
File "/usr/local/lib/python2.7/dist-
packages/networkx/classes/reportviews.py", line 178, in __getitem__
return self._nodes[n]
KeyError: 7
I also created vitual enviourment of Pyhton but again it shows the smae error. Also, I tried finding some stuff on Google and check for the solution but no one has similar problem like this.
Upvotes: 0
Views: 419
Reputation: 11
import random
import networkx as nx
costs = []
value=100
while(value<=2000):
costs.append(value)
value+=100
print (costs)
while(G.number_of_edges()<16):
c1 = random.choice(list(G.nodes()))
c2 = random.choice(list(G.nodes()))
if c1!=c2 and G.has_edge(c1,c2)==0:
w= random.choice(costs)
G.add_edge(c1,c2,weight = w)
Try this code as there is some error in the syntax of the random shown in the video. I have pasted my code, test it.
G.nodes() needs to return a list but here is returning a NodeView. Hence change G.nodes() to list(G.nodes())
Upvotes: 1
Reputation: 486
Change
c1=choice(g.nodes())
c2=choice(g.nodes())
into
c1=choice(list(g))
c2=choice(list(g))
should work.
g.nodes()
returns a NodeView
and not a list of nodes.
Upvotes: 1