From Python Problem Set The three functions work correctly but they require executing one at a time before moving to the next in order to get the final result. Is there a way to obtain the result from all three without having to query each one individually?
>>> 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
You can combine the second 2, but the generator should stay a generator:
You actually can combine all 3 and have the 1 function return a 3-tuple of what each ones return value would be: