使用 totient 函数 - 未定义的问题
来自 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
From Python ProblemSet I would like to test the following functions but it seems that mult and coprime could not be defined. I tried importing math but that did not help. Any recommendations?
>>> 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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您检查运算符模块的文档,您会发现乘法运算符是
乘
。另外,我相信 coprime 的定义依赖于之前问题的定义。
If you check the documentation for the operator module, you'll find that the multiplication operator is
mul
.Also, I believe the definition of
coprime
relies on definitions from previous problems.