组合函数以减少查询

时间:2011-10-13 23:38:06

标签: python function

Python Problem Set这三个函数正常工作但它们需要一次执行一个函数才能移动到下一个函数以获得最终结果。有没有办法从所有三个结果中获取结果而不必单独查询每个结果?

>>> 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

1 个答案:

答案 0 :(得分:1)

您可以组合第二个2,但生成器应该保留一个生成器:

In [1]: import itertools
In [2]: from operator import mul

In [3]: 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

In [4]: def totient(n):
            if n != 1:
                res = list(prime_factors(n))
                prime_factors_mult = sorted([fact, res.count(fact)] for fact in set(res))
                retValue = reduce(mul, [(p-1) * p**(m-1) for p,m in prime_factors_mult]), prime_factors_mult
            else:
                retValue = n
            return retValue

In [5]: x = totient(315)

In [6]: print x
(144, [[3, 2], [5, 1], [7, 1]])

In [7]: print x[0]
144

In [8]: print x[1]
[[3, 2], [5, 1], [7, 1]]

你实际上可以组合所有3并且让1函数返回每个返回值的3元组:

import itertools
from operator import mul

def totient(n):
    if n == 1:  return 1
    res = list()
    value = int("%d" % n)
    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
                res.append(this)
    res.append(value)
    prime_factors_mult = sorted([fact, res.count(fact)] for fact in set(res))
    return res, reduce(mul, [(p - 1) * p**(m - 1) for p,m in prime_factors_mult]), prime_factors_mult

x = totient(315)

# This would be the returned list from prime_factors(315)
print x[0]
[3, 3, 5, 7]

# This would be the returned value from totient(315)
print x[1]
144

# This would be the returned list from prime_factors_mult(315)
print x[2]
[[3, 2], [5, 1], [7, 1]]

# The 3-tuple:
print x
([3, 3, 5, 7], 144, [[3, 2], [5, 1], [7, 1]])