我有一个生成素数的生成器和另一个生成fibbonacci的生成器,我想创建一个生成器,它生成上述生成器或任何两个输入生成器的交集。
def primes():
yield 2
i = 3
while True:
if is_prime(i):
yield i
i += 2
def is_prime(num):
count = 0
for i in range(2, num):
if num % i == 0:
count = 1
if count == 0:
return True
else:
return False
def fibonacci_numbers():
yield 1
a = 0
b = 1
while True:
c = a+b
yield c
a = b
b = c
答案 0 :(得分:0)
生成无数序列数字的生成器在primes()和fibonacci_numbers()中是常见的:
def common(pgen, fgen):
p = next(pgen)
f = next(fgen)
while True:
if p == f:
yield p
f = next(fgen)
p = next(pgen)
elif p > f:
f = next(fgen)
elif f > p:
p = next(pgen)
def test():
cgen = common(primes(), fibonacci_numbers())
assert 2 == next(cgen)
assert 3 == next(cgen)
assert 5 == next(cgen)
assert 13 == next(cgen)
assert 89 == next(cgen)
assert 233 == next(cgen)