【发布时间】:2017-05-30 00:19:11
【问题描述】:
我可以按照维基百科上列出的三叉树算法生成所有互质数对: https://en.wikipedia.org/wiki/Coprime_integers
快点:
Start with two coprime branches: (2,1), (3,1), then iterate:
Branch 1: (2m-n,m)
Branch 2: (2m+n,m)
Branch 3: (m+2n,n)
但是,每生产一对(例如打印,或者不保存在内存中),使用的空间将增加三倍。
这可能是haskell中的一个解决方案: Generating sorted list of all possible coprimes
但我在 python 中寻找一些东西,它没有惰性求值或无限列表。
【问题讨论】:
-
请澄清:您想要与 Haskell 问题中相同的限制吗?
The first element in each pair must be less than the second. The sorting must be done in ascending order -- by the sum of pair's elements; and if two sums are equal, then by the pair's first element.如果是这样,您想在算法中交换这些对。 Python 确实有无限的生成器,可能就像你的“无限列表”。您是想避免“增长三倍”的问题,还是只想要简单的 Python 代码? -
“但我在 python 中寻找一些东西,它没有惰性求值或无限列表。” Python 有生成器(惰性生成值)和函数(尤其是在
itertools) 会产生潜在的无限序列。 -
我不是在寻找 haskell 解决方案的限制,我应该这么说。无论懒惰/无限的术语如何,任何惯用的 python 解决方案都可以工作。
标签: python algorithm primes ternary-tree