从发电机产生 [英] Generate from generators

查看:89
本文介绍了从发电机产生的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个生成器,它使用数字作为参数并产生其他数字. 我想使用此生成器生成的数字,并将它们作为参数传递给同一生成器,从而创建一定长度的链.

I have a generator that takes a number as an argument and yields other numbers. I want to use the numbers yielded by this generator and pass them as arguments to the same generator, creating a chain of some length.

例如,mygenerator(2)产生5、4和6.将mygenerator应用于这些数字中的每一个,一遍又一遍地应用于所产生的数字.生成器始终生成比作为参数传递的数字更大的数字,并且对于2个不同的数字将永远不会生成相同的数字.

For example, mygenerator(2) yields 5, 4 and 6. Apply mygenerator to each of these numbers, over and over again to the numbers yielded. The generator always yields bigger numbers than the one passed as argument, and for 2 different numbers will never yield the same number.

mygenerator(2):4 5 mygenerator(4):10 11 12 mygenerator(5):9300500

mygenerator(2): 4 5 mygenerator(4) : 10 11 12 mygenerator(5): 9 300 500

因此,集合(9,10,11,12,300,500)与原始数字2的距离为"2".如果将其应用于数字9,我将得到一组与原始数字的距离为"3"的数字.原始2.

So the set (9,10,11,12,300,500) has "distance" 2 from the original number, 2. If I apply it to the number 9, I will get a set of numbers with distance "3" from the original 2.

本质上,我想要的是创建一个与给定数字具有指定距离的集合,而我在弄清楚如何在Python中做到这一点时遇到了问题.帮助非常感谢:)

Essentially what I want is to create a set that has a specified distance from a given number and I have problems figuring out how to do that in Python. Help much appreciated :)

推荐答案

此解决方案不需要将所有结果都保留在内存中:(以防不适合在内存中使用,等等)

This solution does not require to keep all results in memory: (in case it doesn't fit in memory etc)

def grandKids(generation, kidsFunc, val):
  layer = [val]
  for i in xrange(generation):
    layer = itertools.chain.from_iterable(itertools.imap(kidsFunc, layer))
  return layer

示例:

def kids(x): # children indices in a 1-based binary heap
  yield x*2
  yield x*2+1

>>> list(grandKids(3, kids, 2))
[16, 17, 18, 19, 20, 21, 22, 23]

顺便说一句,Haskell中的解决方案:

Btw, solution in Haskell:

grandKids generation kidsFunc val =
  iterate (concatMap kidsFunc) [val] !! generation

这篇关于从发电机产生的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆