python - 排列的东西
问题描述
如何编写一个函数(在 Python 中):
如果我们取 A、B 和 C 的所有排列:ABC、ACB、BAC、BCA、CAB、CBA
该函数将获取一个索引并返回该索引的排列。
例如 F("ABC", 4) 将返回 "BCA"
对于非常大的排列集,它应该在合理的时间内运行。
解决方案
您可以解析/过滤 的结果itertools.permutations()
,因为无法直接索引生成器。像这样的函数可以做到这一点:
from itertools import permutations
def nth_permutation(items, n):
i = 0
perms = permutations(items)
try:
next_perm = next(perms)
while i < n:
next_perm = next(perms)
i += 1
except StopIteration:
# implement error behavior here, if n > number of permutations.
# For now we just return the default value, None
# you might instead try throwing an IndexError
return None
return next_perm
(注意,索引的排列4
是 "CAB" - "BCA" 是 index 3
)
推荐阅读
- javascript - 检查任何元素是否有文本 - 没有每个循环
- sharepoint - 我的网站页面上的 Sharepoint 2016 个人资料图片问题
- nginx - limit_req 按一天中的时间区分区域
- docker - Kubernetes:将 mod_cluster 替换为后端服务(反向代理)
- javascript - Jquery else if 语句似乎不起作用
- c++ - 函数调用中的意外编译错误 (C++)
- go - 在 go-pg ORM 中指定多对多关系的键
- ethereum - Ethereum Go-ethereum 待处理交易
- android - 如何使 RecyclerView 出现动画?
- java - 错误:无法解决:recyclerview-v7