I have a small question about how to set stop condition for "while".

For example, I have a list and in "while" I treat this list in certain condition (add an element or remove an element according to different condition), when the list doesn't change. That is to say when the list of N's == list of N-1's, "while" stops. How to write the stop condition for this question? Thanks a lot in advance! I put the code here but I'm sorry if the code is not easy to understand.

- Code: Select all
`from numpy import matrix`

import numpy as np

names = [ "Bloemfontein", "Cape Town", "Durban", "East London",

"George", "Johannesburg", "Kimberley", "Mmabatho", "Graskop",

"Oudtshoorn", "Port Elizabeth", "Umtata"]

#distance matrix

d = [[ 0, 1009,625,559,746,389,157,409,788,716,632,508],

[1009, 0, 1532,1034,425,1407,963,1307,1798,456,738,1214],

[625, 1532, 0,650,1219,567,792,860,760,1275,901,424],

[559, 1034, 650, 0,615,963,721,994,1250,671,297,226],

[746, 425, 1219, 615, 0,1142,726,1071,1534,57,319,795],

[389, 1407, 567, 963, 1142, 0, 482,296,395,1115,1059,831],

[157, 963, 792, 721, 726, 482, 0,345,873,671,736,670],

[409, 1307, 860, 994, 1071, 296, 345, 0,689,1015,1080,933],

[788, 1798, 760, 1250, 1534, 395, 873, 689, 0,1505,1450,1024],

[716, 456, 1275, 671, 57, 1115, 671, 1015, 1505, 0,376,852],

[632, 738, 901, 297, 319, 1059, 736, 1080, 1450, 376, 0,478],

[508, 1214, 424, 226, 795, 831, 670, 933, 1024, 852, 478, 0]]

lit=[q for q in range(len(names))]

lt=[[q] for q in range(len(names))]

#Merge the names by average linkage

min_distance = float('inf')

min_pair = (-1, -1)

#Find the firt two nearest neighbor to merge

for i in range(len(lit)):

for j in range(i+1, len(lit)):

distance = d[lit[i]][lit[j]]

if distance < min_distance:

min_distance = distance

min_pair = (i, j)

i, j = min_pair

if min_distance>500:

print 'distance value is too big'

else:

lt[i]=lt[i]+lt[j]

del lt[j]

#del lit[j]

while len(lt)>1:

min_distance3 = float('inf')

min_pair3 = (-1, -1)

#find the nearest neighbors to each group

for f in range(len(lt)):

for g in range(f+1,len(lt)):

dis=0

if len(lt[f])!=0 and len(lt[g])!=0:

for n in range(len(lt[f])):

for m in range(len(lt[g])):

dis = dis+d[lt[f][n]][lt[g][m]]

mind=dis/(len(lt[f])*len(lt[g]))

if mind < min_distance3:

min_distance3 = mind

min_pair3 = (f, g)

r,t=min_pair3

md=min_distance3

#if the distance is smaller than the predefined value

if md<=500:

lt[r]=lt[r]+lt[t]

del lt[t]

print lt,len(lt)

Here, I put condition "len(lt)>1" to "while", but as the condition "if md<=500" is not always satisfied (but if I set 100000 which is bigger than any distance value in the matrix instead of 500, the condition works), the list "lt" becomes stable after some time. So the condition "len(lt)>1" does not work. Here, the real stop condition is that, "if lt of N's == lt of N-1's", but I don't know how to do this.