繁体   English   中英

无限生成器的Python产品

[英]Python product of infinite generators

我试图获得2个无限生成器的产品,但itertools product函数不允许这种行为。

示例行为:

from itertools import *
i = count(1)
j = count(1)
x = product(i, j)

[Killed]

我想要的是:

x = product(i, j)

((0,0), (0,1), (1,0), (1,1) ...)

只要给定无限时间,组合返回的顺序无关紧要,最终将生成所有组合。 这意味着给定元素组合,返回的生成器中必须有一个有限的索引。

TL;博士

下面给出的代码现在包含在PyPI的infinite包中。 所以现在你可以在运行之前实际上只是pip install infinite

from itertools import count
from infinite import product

for x, y in product(count(0), count(0)):
    print(x, y)
    if (x, y) == (3, 3):
        break

懒惰的解决方案

如果您不关心订单,由于生成器是无限的,有效的输出将是:

(a0, b1), (a0, b2), (a0, b3), ... (a0, bn), ...

所以你可以从第一个生成器中获取第一个元素,然后遍历第二个元素。

如果你真的想要这样做,你需要一个嵌套循环,你需要用tee复制嵌套的生成器,否则你将无法再次循环它(即使它无关紧要因为你永远不会排气发电机,所以你永远不需要循环)

但如果你真的真的想要这样做,你可以在这里:

from itertools import tee

def product(gen1, gen2):
    for elem1 in gen1:
        gen2, gen2_copy = tee(gen2)
        for elem2 in gen2_copy:
            yield (elem1, elem2)

我们的想法是始终制作gen2的单一副本。 首先尝试使用有限生成器。

print(list(product(range(3), range(3,5))))
[(0, 3), (0, 4), (1, 3), (1, 4), (2, 3), (2, 4)]

然后是无限的:

print(next(product(count(1), count(1))))
(1, 1)

之字形算法

正如评论中的其他人所指出的那样(并且如前面的解决方案中所述),这不会产生所有组合。 然而,自然数和数字对之间的映射存在,因此必须能够以不同的方式迭代对,以便在有限的时间内完成寻找特定对(没有无限数),你需要zig- zag扫描算法。

之字形扫描算法

为了做到这一点,你需要缓存以前的值,所以我创建了一个类GenCacher来缓存以前提取的值:

class GenCacher:
    def __init__(self, generator):
        self._g = generator
        self._cache = []

    def __getitem__(self, idx):
        while len(self._cache) <= idx:
            self._cache.append(next(self._g))
        return self._cache[idx]

之后,您只需要实现Zig-zag算法:

def product(gen1, gen2):
    gc1 = GenCacher(gen1)
    gc2 = GenCacher(gen2)
    idx1 = idx2 = 0
    moving_up = True

    while True:
        yield (gc1[idx1], gc2[idx2])

        if moving_up and idx1 == 0:
            idx2 += 1
            moving_up = False
        elif not moving_up and idx2 == 0:
            idx1 += 1
            moving_up = True
        elif moving_up:
            idx1, idx2 = idx1 - 1, idx2 + 1
        else:
            idx1, idx2 = idx1 + 1, idx2 - 1

from itertools import count

for x, y in product(count(0), count(0)):
    print(x, y)
    if x == 2 and y == 2:
        break

这会产生以下输出:

0 0
0 1
1 0
2 0
1 1
0 2
0 3
1 2
2 1
3 0
4 0
3 1
2 2

将解决方案扩展到2个以上的发电机

我们可以稍微编辑解决方案,使其即使对于多个生成器也能工作。 基本思路是:

  1. 迭代距离(0,0) (索引之和(0,0)的距离。 (0,0)是距离为0的唯一一个, (1,0)(0,1)距离为1,等等。

  2. 生成该距离的所有索引元组

  3. 提取相应的元素

我们仍然需要GenCacher类,但代码变为:

def summations(sumTo, n=2):
    if n == 1:
        yield (sumTo,)
    else:
        for head in xrange(sumTo + 1):
            for tail in summations(sumTo - head, n - 1):
                yield (head,) + tail

def product(*gens):
    gens = map(GenCacher, gens)

    for dist in count(0):
        for idxs in summations(dist, len(gens)):
            yield tuple(gen[idx] for gen, idx in zip(gens, idxs))
 def product(a, b):
     a, a_copy = itertools.tee(a, 2)
     b, b_copy = itertools.tee(b, 2)
     yield (next(a_copy), next(b_copy))
     size = 1
     while 1:
         next_a = next(a_copy)
         next_b = next(b_copy)
         a, new_a = itertools.tee(a, 2)
         b, new_b = itertools.tee(b, 2)
         yield from ((next(new_a), next_b) for i in range(size))
         yield from ((next_a, next(new_b)) for i in range(size))
         yield (next_a, next_b)
         size += 1

使用itertools.tee的自制软件解决方案。 这使用大量内存,因为中间状态存储在tee

这有效地回归了不断扩大的广场的两侧:

0 1 4 9 
2 3 5 a
6 7 8 b
c d e f

给定无限时间和无限内存,此实现返回所有可能的产品。

无论你如何做,内存都会增长很多,因为每个迭代器的每个值在第一次之后都会发生无限次,所以它必须在一些增长的变量中保持不变。

所以这样的事情可能有用:

def product(i, j):
    """Generate Cartesian product i x j; potentially uses a lot of memory."""
    earlier_values_i = []
    earlier_values_j = []

    # If either of these fails, that sequence is empty, and so is the
    # expected result. So it is correct that StopIteration is raised,
    # no need to do anything.
    next_i = next(i)
    next_j = next(j)
    found_i = found_j = True

    while True:
        if found_i and found_j:
            yield (next_i, next_j)
        elif not found_i and not found_j:
            break  # Both sequences empty

        if found_i: 
            for jj in earlier_values_j:
                yield (next_i, jj)
        if found_j:
            for ii in earlier_values_i:
                yield (ii, next_j)

        if found_i:
            earlier_values_i.append(next_i)
        if found_j:
            earlier_values_j.append(next_j)

        try:
            next_i = next(i)
            found_i = True
        except StopIteration:
            found_i = False

        try:
            next_j = next(j)
            found_j = True
        except StopIteration:
            found_j = False

这在我脑海中如此简单,但在输入后看起来非常复杂,必须有一些更简单的方法。 但我认为它会起作用。

你可以使用生成器表达式:

from itertools import *
i = count(1)
j = count(1)

for e in ((x, y) for x in i for y in j):
    yield r

或者在python3中:

yield from ((x, y) for x in i for y in j)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM