15,117,830 members
See more:
Hi! I am currently developing a custom algorithm that implements the Havel-Hakimi algorithm choosing a node randomly. Unfortunately I have run into a logical error that is hard for me to trace (since I am a beginner in programming).I would appreciate it if someone could help me spot the issue. What happens is I get the correct sequence returned sometimes, but other times not

Python
```import networkx as nx
import matplotlib.pyplot as plt
import random

def nodes_connected(G,u,v):
return u in G.neighbors(v)

def hh_graph(seq):
if not(nx.is_graphical(seq)):
print("Sequence is not graphical")
else:
#Randomly mix the degree sequence
random.shuffle(seq)
#Create graph
G = nx.Graph()
#Repeat for every node in the sequence
for i in range(0,len(seq)):
#j stores number of edges to be added
j=seq[i]
#selected node is zeroed
seq[i]=0
#Repeat till all edges have been connected
while j>0:
k=0
done=False
#Repeat till finding a suitable node to connect to
while k<len(seq) and done==False :
#Check to connect to a maximum value node,and avoiding a duplicate connection
if seq[k]==max(seq) and nodes_connected(G,i+1,k+1)==False:
seq[k]-=1
done=True
k+=1
j-=1
#Check graph degree sequence to validate results
degree_sequence = [d for n, d in G.degree()]
print(f"Graph degree sequence {degree_sequence}")
#nx.draw_networkx(G)
#plt.show()

A=[5, 4, 4, 4, 4, 4, 3, 3, 3, 3, 3]
B=[6, 3, 3, 3, 3, 2, 2, 2, 2, 2,1,1]
C=[4,3,2,1]
hh_graph(A)
hh_graph(B)
hh_graph(C)```

What I have tried:

I have tried to focus on the loops where I think there might be an issue.I have tested different if cases and implementations,but still cant understand how it works half of the time and other times not
Posted