f=open("out_27_18_7.txt","w") def hamiltonian(h,l,m,k=[]): k=k+[l] if l==m: return [k] if not h.has_key(l): return [] n=[] for i in h[l]: if i not in k: w=hamiltonian(h,i,m,k) for a in w: if len(a)==len(h): n.append(a) return n h={'U': ['V','W','Z'],'V': ['U','X','Y'],'W': ['U','X','Z'],'X': ['W','V','Y'],'Y': ['V','X'],'Z': ['W','U']} r=hamiltonian(h,'U','Z') z=str(r) f.write(z+"\n") f.close()