0

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

所以另一个例子NextInOrder(10, (5,3,2,10))会返回(5,3,4,1)

4

2 回答 2

2

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

例如:

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)
...
于 2021-02-08T22:05:48.830 回答
0

你可以使用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)
于 2021-02-08T20:30:28.860 回答