给定n和一个特定的排列s,按照元素1-n (python)的字典顺序找出下一个排列



例如,假设我们有NextInOrder(10,(1,2,4,7)),然后将这两个作为函数的输入,我希望编写一个python函数,通过查找字典顺序中的下一个排列(该排列的元素在1-10

范围内)来返回(1,2,4,8)

。作为另一个例子,NextInOrder(10, (5,3,2,10))将返回(5,3,4,1)

您可以使用从最后一个位置开始的数字计数器方法。将最后一个位置增加到不在前一个位置中的值。当下一个值超出范围时,返回到前一个位置。

例如:

def nextPerm(N,P):
result = list(P)           # mutable permutation
i = len(P)-1               # position to advance (start with last)
while i in range(len(P)):  # advance/backtrack loop
result[i] += 1         # next value at position
if result[i] > N:      # value beyond range
result[i]=0
i -= 1             # backtrack
elif result[i] not in result[:i]: # distinct values only
i += 1             # next position to advance
return None if i<0 else tuple(result)

输出:

P = (1,2,4,7)
while P:
P = nextPerm(10,P)
print(P)
(1, 2, 4, 8)
(1, 2, 4, 9)
(1, 2, 4, 10)
(1, 2, 5, 3)
(1, 2, 5, 4)
(1, 2, 5, 6)
(1, 2, 5, 7)
(1, 2, 5, 8)
(1, 2, 5, 9)
(1, 2, 5, 10)
(1, 2, 6, 3)
...

您可以使用itertools:

from itertools import permutations
def NextInOrder(n, current):
perms = permutations(range(1, n+1), len(current))
for perm in perms:
if perm == current:
return next(perms)

演示:

>>> NextInOrder(10,(1,2,4,7))
(1, 2, 4, 8)
>>> NextInOrder(10, (5,3,2,10))
(5, 3, 4, 1)

最新更新