如何在 python 中实现 2d array/odometer?
How to implement 2d array/odometer in python?
我正在研究从质因数中找出数的所有因数的算法。这是我到目前为止的代码
def is_prime(x):
return all(x % i for i in range(2, x))
def next_prime(x):
return min([a for a in range(x+1, 2*x) if is_prime(a)])
def numFactors(n):
factors = {1, n}
primeFactors = dict()
s = n
while s != 1:
# print(s)
pr = 2
while s % pr != 0:
pr = next_prime(pr)
if pr in primeFactors.keys():
primeFactors[pr] += 1
else:
primeFactors[pr] = 1
factors.add(pr)
factors.add(int(s/pr))
s = int(s/pr)
此代码为我提供了一本包含所有质因数及其指数的字典。因此,例如,120 给出 {2: 3, 3: 1, 5: 1}
我正在尝试做的是获得这样的每个因素:(2^1 * 3^0 * 5^0), (2^2 * 3^0 * 5^0)...
或多或少是这样的里程表
(0 0 0)
(1 0 0)
(2 0 0)
(3 0 0)
(0 1 0)
(1 1 0)
(2 1 0)
...
如何从 primeFactors 值中实现这一点?我似乎无法组合正确的循环组合,尤其是因为每一列都有不同的最大整数。
你可以试试itertools.product
from itertools import product
d = {2: 3, 3: 1, 5: 1}
keys = d.keys()
possibilies = ['*'.join([f'{j[0]}^{j[1]}' for j in zip(keys, i)]) for i in product(*[range(v+1) for v in d.values()])]
print(possibilies)
['2^0*3^0*5^0',
'2^0*3^0*5^1',
'2^0*3^1*5^0',
'2^0*3^1*5^1',
'2^1*3^0*5^0',
'2^1*3^0*5^1',
'2^1*3^1*5^0',
'2^1*3^1*5^1',
'2^2*3^0*5^0',
'2^2*3^0*5^1',
'2^2*3^1*5^0',
'2^2*3^1*5^1',
'2^3*3^0*5^0',
'2^3*3^0*5^1',
'2^3*3^1*5^0',
'2^3*3^1*5^1']
我正在研究从质因数中找出数的所有因数的算法。这是我到目前为止的代码
def is_prime(x):
return all(x % i for i in range(2, x))
def next_prime(x):
return min([a for a in range(x+1, 2*x) if is_prime(a)])
def numFactors(n):
factors = {1, n}
primeFactors = dict()
s = n
while s != 1:
# print(s)
pr = 2
while s % pr != 0:
pr = next_prime(pr)
if pr in primeFactors.keys():
primeFactors[pr] += 1
else:
primeFactors[pr] = 1
factors.add(pr)
factors.add(int(s/pr))
s = int(s/pr)
此代码为我提供了一本包含所有质因数及其指数的字典。因此,例如,120 给出 {2: 3, 3: 1, 5: 1}
我正在尝试做的是获得这样的每个因素:(2^1 * 3^0 * 5^0), (2^2 * 3^0 * 5^0)...
或多或少是这样的里程表
(0 0 0)
(1 0 0)
(2 0 0)
(3 0 0)
(0 1 0)
(1 1 0)
(2 1 0)
...
如何从 primeFactors 值中实现这一点?我似乎无法组合正确的循环组合,尤其是因为每一列都有不同的最大整数。
你可以试试itertools.product
from itertools import product
d = {2: 3, 3: 1, 5: 1}
keys = d.keys()
possibilies = ['*'.join([f'{j[0]}^{j[1]}' for j in zip(keys, i)]) for i in product(*[range(v+1) for v in d.values()])]
print(possibilies)
['2^0*3^0*5^0',
'2^0*3^0*5^1',
'2^0*3^1*5^0',
'2^0*3^1*5^1',
'2^1*3^0*5^0',
'2^1*3^0*5^1',
'2^1*3^1*5^0',
'2^1*3^1*5^1',
'2^2*3^0*5^0',
'2^2*3^0*5^1',
'2^2*3^1*5^0',
'2^2*3^1*5^1',
'2^3*3^0*5^0',
'2^3*3^0*5^1',
'2^3*3^1*5^0',
'2^3*3^1*5^1']