0

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.

1

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1
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())

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.