从Python ProblemSet我想测试以下函数,但似乎无法定义mult和coprime。我尝试导入数学,但这没有帮助。有什么建议吗?
>>> import itertools
>>> def prime_factors(value):
if value > 3:
for this in itertools.chain(iter([2]), xrange(3,int(value ** 0.5)+1, 2)):
if this*this > value: break
while not (value % this):
if value == this: break
value /= this
yield this
yield value
>>> prime_factors(315)
generator object prime_factors at 0x01182468>
>>> def prime_factors_mult(n):
res = list(prime_factors(n))
return sorted([fact, res.count(fact)] for fact in set(res))
>>> prime_factors_mult(315)
[[3, 2], [5, 1], [7, 1]]
>>> def totient(n):
from operator import mul
if n == 1: return 1
return reduce(mul, [(p-1) * p**(m-1) for p,m in prime_factors_mult(n)])
>>> totient(315)
144