misc¶
这里是自己随手刷到 / 写题目用过的 python 库的使用。
itertools¶
- 安装:
pip install itertools
- 使用:生成组合数字,用于获取某个特大数的所有因数。
迭代器 | 参数 | 结果 |
---|---|---|
product() | p, q, ... [repeat=1] | 笛卡尔积,相当于嵌套 for 循环 |
permutations() | p[, r] | r 长度元组,所有可能的顺序,没有重复的元素 |
combinations() | p, r | r 长度元组,按排序顺序,没有重复的元素 |
combinations_with_replacement() | p, r | r 长度元组,按排序顺序,重复元素 |
product('ABCD', repeat=2) | AA AB AC AD BA BB BC BD CA CB CC CD DA DB DC DD | |
permutations('ABCD', 2) | AB AC AD BA BC BD CA CB CD DA DB DC | |
combinations('ABCD', 2) | AB AC AD BC BD CD | |
combinations_with_replacement('ABCD', 2) | AA AB AC AD BB BC BD CC CD DD |
In [ ]:
Copied!
from itertools import chain, combinations
# sage 中的 divisors(n) 效果相同;但是如果可以先用 factordb 获得质因子,那么就一样的了。
def getFullFactors(factors):
"""获得所有的因子"""
def getSubset(iterable):
"""获得可迭代对象的所有子集"""
s = list(iterable)
return chain.from_iterable(combinations(s, r) for r in range(len(s) + 1))
def getProduct(iterable):
"""获得可迭代对象所有元素的乘积"""
result = 1
for i in iterable:
result *= i
return result
# 使用集合去除重复元素
return set(getProduct(i) for i in getSubset(factors))
from itertools import chain, combinations
# sage 中的 divisors(n) 效果相同;但是如果可以先用 factordb 获得质因子,那么就一样的了。
def getFullFactors(factors):
"""获得所有的因子"""
def getSubset(iterable):
"""获得可迭代对象的所有子集"""
s = list(iterable)
return chain.from_iterable(combinations(s, r) for r in range(len(s) + 1))
def getProduct(iterable):
"""获得可迭代对象所有元素的乘积"""
result = 1
for i in iterable:
result *= i
return result
# 使用集合去除重复元素
return set(getProduct(i) for i in getSubset(factors))
In [ ]:
Copied!
big_num = 8699621268124163273600280057569065643071518478496234908779966583664908604557271908267773859706827828901385412151814796018448555312901260592
# 使用 factordb.com 等分解
factors = (
[2] * 4
+ [3] * 2
+ [
31,
61,
223,
4013,
281317,
4151351,
339386329,
370523737,
5404604441993,
26798471753993,
25866088332911027256931479223,
64889106213996537255229963986303510188999911,
]
)
[1] + list(getFullFactors(factors))
big_num = 8699621268124163273600280057569065643071518478496234908779966583664908604557271908267773859706827828901385412151814796018448555312901260592
# 使用 factordb.com 等分解
factors = (
[2] * 4
+ [3] * 2
+ [
31,
61,
223,
4013,
281317,
4151351,
339386329,
370523737,
5404604441993,
26798471753993,
25866088332911027256931479223,
64889106213996537255229963986303510188999911,
]
)
[1] + list(getFullFactors(factors))