看看这个简单的功能
def prime_factors(n): for i in range(2,n): if n % i == 0: return i, prime_factors(n / i) return n
这是结果 prime_factors(120)
(2, (2, (2, (3, 5))))
我希望它返回一个扁平元组或列表,而不是嵌套元组.
(2, 2, 2, 3, 5)
有一个简单的方法吗?
def prime_factors(n): for i in range(2,n): if n % i == 0: return [i] + prime_factors(n / i) return [n]
def prime_factors(n): for i in range(2,n): if n % i == 0: yield i for p in prime_factors(n / i): yield p return yield n
例:
>>> tuple(prime_factors(100)) (2, 2, 5, 5)
不改变原始功能,来自Python技巧:
def flatten(x): """flatten(sequence) -> list Returns a single, flat list which contains all elements retrieved from the sequence and all recursively contained sub-sequences (iterables). Examples: >>> [1, 2, [3,4], (5,6)] [1, 2, [3, 4], (5, 6)] >>> flatten([[[1,2,3], (42,None)], [4,5], [6], 7, MyVector(8,9,10)]) [1, 2, 3, 42, None, 4, 5, 6, 7, 8, 9, 10]""" result = [] for el in x: #if isinstance(el, (list, tuple)): if hasattr(el, "__iter__") and not isinstance(el, basestring): result.extend(flatten(el)) else: result.append(el) return result
liw.fi在评论中建议:
您可以将列表作为参数传递并追加到该列表中,而不是为每个返回值创建一个新列表。如果列表变大,则可以节省一些空间和时间。
这是liw.fi建议的实现。
def prime_factors(n, factors=None): if factors is None: factors = [] for i in range(2,n): if n % i == 0: factors.append(i) return prime_factors(n / i, factors) factors.append(n) return factors