I'm a newbie in Python.
I try to make a Kruskal algo. Here is my code:
#c={('v','a'):5,('v','g'):5,('g','a'):5,('v','b'):7,('v','e'):4,('f','e'):8,('f','b'):8,('f','c'):11,('c','e'):9,('c','d'):7,('c','b'):9,('e','d'):8}
#n=8
def argmin(c):
m=1e100
r=()
for i in c:
if c[i]<m:
m=c[i]
r=i
return r
def kruskal (n, c):
T=[]
B=[]
while len(T)<n-1:
E=argmin(c)
c.pop(E)
e=[]
e+=E
a0=0
a1=0
f0=-1
f1=-1
cross=0
# print('e avant',e)
for i in range(len(B)):
for j in range(len(B[i])):
if e[0]==B[i][j]:
cross+=1
f0=i
if e[1]==B[i][j]:
cross+=1
f1=i
if cross==2: break
else: cross=0
if cross==2: continue
# print('e apres',e)
T.append(e)
# print('T',T)
if f0!=-1 and f1!=-1:
B[f0].extend(B[f1])
B.pop(f1)
elif f0!=-1:
B[f0].extend(e[1])
elif f1!=-1:
B[f1].extend(e[0])
else :
B.append(e)
# print('B', B)
return T
The problem I have is in the line where is: "T.append(e)" In the result T[0] is not what I expect. if I input the following:
c={('v','a'):5,('v','g'):5,('g','a'):5,('v','b'):7,('v','e'):4,('f','e'):8,('f','b'):8,('f','c'):11,('c','e'):9,('c','d'):7,('c','b'):9,('e','d'):8}
n=8
Then I call my function: kruskal(8, c) I get:
[['v', 'e', 'g', 'a', 'b', 'f', 'c', 'd'], ['v', 'g'], ['v', 'a'], ['v', 'b'], ['c', 'd'], ['f', 'b'], ['e', 'd']]
Where as I expect the following:
[['v', 'e'], ['v', 'g'], ['v', 'a'], ['v', 'b'], ['c', 'd'], ['f', 'b'], ['e', 'd']]