此程序需要通过使用此规则交换元素来找到列表的所有排列 - 交换最后一个元素,直到它变为第一个为止(例如,1,2,3,4变为1,2, 4,3等等,直到4,1,2,3),当它成为第一个元素时,则需要切换最后2个元素并在相反方向上执行相同的操作(交换第一个元素,直到它变为最后一个,然后交换第一个元素2元素和重复),这也被称为Steinhaus-Johnson-Trotter算法。出于某种原因,我的实现不能在Python中工作,我想知道为什么以及为了使其工作需要做什么。Python:使用嵌套循环的程序不能正常工作
编辑:通过“不工作”我的意思是,该程序只打印list1和别的什么都不做,程序只能通过“杀”它关闭,这意味着它被卡在无限循环(这可以证明在将list1附加到all_permutations后打印all_permutations)。
list1 = [0, 1, 2, 3] #list that will be swapped
x = 3 #this is used for swapping
all_permutations = [] #list where permutations will be added
print(list1) #print list1 because it is the first permutation
while len(all_permutations) != 23: #loop until all permutations are found (4! = 24 but since list1 is already 1 permutation we only need 23)
x -= 1
list1[x], list1[x+1] = list1[x+1], list1[x]
all_permutations.append(list1)
#code above swaps the last element until it becomes 1st in the list
if x == 0: #if last element becomes 1st
list1[2], list1[3] = list1[3], list1[2] #swap last 2 elements
while x != 3: #loop which swaps 1st element until it becomes the last element
if len(all_permutations) == 23:
break
else:
continue
x += 1
list1[x-1], list1[x] = list1[x], list1[x-1]
all_permutations.append(list1)
list1[0], list1[1] = list1[1], list1[0] #when loop is over (when 1st element becomes last) switch first 2 elements
all_permutations.append(list1)
else:
continue
print(all_permutations) #print all permutations
你可能是一点点比*更具体的 “不工作” *? – jonrsharpe
它只打印list1(它在循环外部),并且清楚地表明该程序被卡住在无限循环中(这可以通过在将list1附加到all_permutations后立即打印all_permutations来证明)。 – user3711671
请*编辑问题*提供所有必要的信息。 – jonrsharpe