在这段代码中,我试图为寻找LCM的主要方法获取主要因素。那么我试图通过计数器保存它,但是我无法为正确的方法划分键和值。 我被卡在柜台了,任何人都可以帮我吗?
from collections import Counter
def q2_factor_lcm(a, b): #function for lcm
fa = factor_list(a) #factor list for a
fb = factor_list(b) #factorlist for b
c = Counter(fa) #variables to save counter for a
d = Counter(fb) #variables to save counter for b
r = c | d
r.keys()
for key, value in sorted(r.items()): # for loop for getting counter subtraction
l = pow(key, value)
result = [] # I am getting confused what to do now
for item in l:
result.append(l)
return result #will return result
def factor_list(n): # it is to generate prime numbers
factors = [] # to save list
iprimes = iter( primes_list(n) ) # loop
while n > 1:
p = next(iprimes)
while n % p == 0: # python calculation
n = n // p
factors.append(p)
return factors # it will return factors
答案 0 :(得分:1)
首先,这种方法并不是真正有效的查找lcm的方法。因为有一些不错的方法可以找到gcd,所以用lcm = a * b / gcd(a,b)
(*)来获得a和b的lcm很容易。
第二,从不使用pow和整数值。已知浮点算术broken不准确。
现在开始提问。 2个计数器上的更新操作不是您想要的:两个字典中都存在键时,您将丢失其中一个值。相反,您应该使用键集的并集,然后使用两个值的最大值(不存在的键被视为指数的0值):
...
# use a true dict to be able to later use the get method with a default
c = dict(Counter(fa)) #variables to save counter for a
d = dict(Counter(fb)) #variables to save counter for b
result = []
for key in sorted(set(c.keys()).union(set(d.keys()))):
exp = max(c.get(key, 0), d.get(key, 0))
for i in range(exp):
result.append(key)
return result
(*)诀窍在于,当a> b时,GCD(a,b)为GCD(b,mod(a,b))。在Python中,它会立即给出:
def gcd(a, b):
if b > a:
return gcd(b, a)
if b == 1:
return b
m = a % b
return b if m == 0 else gcd(b, m)
def lcm(a,b):
return a * b / gcd(a,b)