python - 给定 n 和特定排列 s,按元素 1-n 的字典顺序找到下一个排列(python)
问题描述
例如,假设我们有NextInOrder(10,(1,2,4,7))
,然后将这两个作为函数的输入,我希望编写一个 python 函数,该函数(1,2,4,8)
通过按字典顺序查找下一个排列来返回,其中排列的元素在范围内1-10
所以另一个例子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)
...
推荐阅读
- eloqua - 如何使用批量 API 从 Eloqua 导出所有外部活动
- python - 这里导入错误的确切原因是什么?
- python - 如何从 if 语句中创建永久更改?
- stripe-payments - Stripe - 处理来自同一 IP 的多笔付款
- angular - 如何根据Angular中的虚假值选择默认下拉选项?
- visual-studio-2017 - 指定的任务可执行位置“...\packages\Microsoft.Net.Compilers.1.3.2\build\..\tools\csc.exe”无效
- scala - 如何在 Spark 或 Scala 中检查文件是否是有效的 gz
- html - 导出到 Apps Script webapp 的图表数据为空
- teamsql - TeamSQL 可以转储到文件吗
- javascript - 元素出现但不是子元素的选择器