我正在尝试解决一个包含给定数字的原始因式分解的运动。
def primes(n):
p=[]
for a in range(2,n+1):
if (is_prime(a)): p.append(a)
return p
def is_prime(number):
for n in range(2,number):
if not number%n : return False
return True
def factor(z):
p=primes(z)
fact={}
if z in p:
fact[z]=1
else:
for n in p:
while z%n==0 and (z/n not in p):
if n not in fact: fact[n]=1
else: fact[n]+=1
z/=n
if z%n==0 and (z/n in p):
if n in fact: fact[n]+=1+(z/n==n)
else:
fact[n]=1
fact[z/n]=1+(z/n==n)
break
return fact
print factor(13)
我的代码就像一个魅力;但是,exercice希望我把它放在一个以下开头的课程中:
class PrimeFactorizer:
#your code here
使用PrimeFactorizer(n).factor
当我将上面的工作代码添加到
中时class PrimeFactorizer:
def __init__(self, z):
self.z=z
调用PrimeFactorizer(13).factor
时,它会返回一个空的内容
有人能给我一些关于我做错的提示吗?
感谢
答案 0 :(得分:0)
这应该可以解决问题:
class PrimeFactorizer:
def __init__(self, z):
self.z=z
def primes(self,n):
p=[]
for a in range(2,n+1):
if (self.is_prime(a)): p.append(a)
return p
def is_prime(self,number):
for n in range(2,number):
if not number%n : return False
return True
def factor(self):
p=self.primes(self.z)
fact={}
if self.z in p:
fact[self.z]=1
else:
for n in p:
while self.z%n==0 and (self.z/n not in p):
if n not in fact: fact[n]=1
else: fact[n]+=1
self.z/=n
if self.z%n==0 and (self.z/n in p):
if n in fact: fact[n]+=1+(self.z/n==n)
else:
fact[n]=1
fact[self.z/n]=1+(z/n==n)
break
return fact
print PrimeFactorizer(8).factor() # Output: {2: 3}
print PrimeFactorizer(13).factor() # Output: {13: 1}}