回答
像這樣的事情也許
>>> from itertools import *
>>> from operator import mul
>>> d = {2:2,5:1} # result of pf(20)
>>> l = list(chain(*([k] * v for k, v in d.iteritems())))
>>> l
[2, 2, 5]
>>> factors = set(chain(*(permutations(l, i) for i in range(1,len(l)+1))))
set([(2, 2, 5), (2,), (5,), (5, 2, 2), (2, 2), (2, 5), (5, 2), (2, 5, 2)])
>>> set(reduce(mul, fs, 1) for fs in factors)
set([4, 2, 10, 20, 5])
不能得到比那更pythonic。 –
+1,但考慮「組合」而不是「排列」。 – georg
from itertools import product
def primeplus():
"""
Superset of primes using the primes are a subset of 6k+1 and 6k-1.
"""
yield 2
yield 3
n=5
while(True):
yield n
yield n+2
n+=6
def primefactorization(n):
ret={}
for i in primeplus():
if n==1: break
while n%i==0:
ret[i]=ret.setdefault(i,0)+1
n=n//i
return ret
def divisors(n):
pf=primefactorization(n)
keys,values=zip(*pf.items())
return (reduce(lambda x,y:(x[0]**x[1])*(y[0]**y[1]),zip(keys,p1)+[(1,1)]) for p1 in product(*(xrange(v+1) for v in values)))
雖然這個回答是不是太Python的,它使用簡單的遞歸發現的主要因素。
def find_factors(x):
for i in xrange(2, int(x ** 0.5) + 1):
if x % i == 0:
return [i] + find_factors(x/i)
return [x]
print find_factors(13) # [13]
print find_factors(103) # [103]
print find_factors(125) # [5,5,5]
print find_factors(1334234) # [2, 11, 60647]
from collections import Counter
print dict(Counter(find_factors(13))) # {13: 1}
print dict(Counter(find_factors(103))) # {103: 1}
print dict(Counter(find_factors(125))) # {5: 3}
print dict(Counter(find_factors(1334234))) # {2: 1, 11: 1, 60647: 1}
你只需要搜索,直到找到x ** 0.5(即上限您的xrange可以爲x ** 0.5 + 1而不是X/2,它給你一個更好的大O字運行時)。此外,x/2已經返回一個int(整數除以默認的樓層結果)。 – user1413793
修正了這個問題,謝謝大家: - ) –
它應該是x ** 0.5 + 1,因爲xrange不包含上限。例如,在9的情況下,您希望xrange在3處停止。您現在擁有的方式將停止在2,並且聲明9是一個質數。 – user1413793
一個班輪:
>>> d = {3:4, 5:1, 2:2}
>>> sorted(map(lambda p: reduce(mul, p), product(*map(lambda c: [c[0] ** i for i in range(c[1] + 1)], d.iteritems()))))
[1, 2, 3, 4, 5, 6, 9, 10, 12, 15, 18, 20, 27, 30, 36, 45, 54, 60, 81, 90, 108, 135, 162, 180, 270, 324, 405, 540, 810, 1620]
>>>
- 1. 輸出?素因式分解
- 2. Python中的素因式分解
- 3. Python中的Coprime因式分解
- 4. Pyschools因式分解
- 5. 因式分解application_helper
- 6. 大數的因式分解
- 7. Fermat的因式分解C++
- 8. 格式因式分解算法的
- 9. 因式分解在Haskell
- 10. 整數因式分解
- 11. 因式分解循環
- 12. 因式分解在OAM中
- 13. 因式分解Spark列
- 14. 查找數字因子和因式分解多項式(Lua)
- 15. SBT中的因式分解引理
- 16. 因式分解算法中的噪音
- 17. 加快我的費馬因式分解函數(Python)
- 18. python在單個圖像中的非負矩陣因式分解
- 19. C++如何展開/因式分解方程式(不解決問題)
- 20. 在Haskell中實現因式分解法
- 21. 因式分解問題用戶輸入
- 22. 因式分解紅寶石條件
- 23. 蟒蛇因式分解性能
- 24. 因式分解在幾個JSF元素
- 25. 快速因式分解模塊
- 26. 使用Python進行費馬因式分解
- 27. Python 2.7使用記憶改進遞歸pollard rho因式分解
- 28. 因式分解javascript/jquery代碼隱藏模式當單擊外
- 29. 給出分項金額的公式
- 30. 在python,C++中解析文本文件,給出特定格式
不應認爲是'{2:1,5:1}'? –
是的,我也被你的字典弄糊塗了。 – user1413793
我認爲字典格式是關鍵因素,指數是值 - '2 ** 2 * 5 ** 2'。 – PaulMcG