具有外部中断条件的Python生成器

2024-03-28 22:13:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要迭代n(=5,f.I.)整数的升序序列x,找到函数f(*x)返回True的所有序列。在

假设对于某个特定的y,如果f_n(*y)为False,那么对于z_i gt;=y_i的任何z,f_n(*z)id为False,因此f琰n在其所有参数中都是单调的。在

这种生成函数可以用以下方式来确定所有平方和为100的整数升序序列

for sequence in generate_sequences(5):
   if sum_squares_is_at_least(sequence, 100):
       # some code to trigger the breaking of the generator loop
   else:
       print sequence

澄清: 这里的问题是我们需要单独迭代n个元素。最初,我们将[1,1,1,1,1]迭代到[1,1,1,1,x],然后我们必须继续从[1,1,1,2,2]到[1,1,1,2,y],最后以[a,b,c,d,e]结尾。生成器看起来应该是这样的,但是需要一些代码来打破for和/或while循环,如果需要(由外部确定):

^{pr2}$

示例: 对于n=3且平方和不大于20,将生成以下序列: [1,1,1],[1,1,2],[1,1,3],[1,1,4],[1,2,2],[1,2,3],[1,3,3],[2,2,2],[2,2,3]

注意,在一般情况下,我不能使用4是每个元素的上限的信息。这也会严重影响大型示例的运行时间。在


Tags: the函数gtidfalsetrue元素示例
3条回答

我会用递归来解决这个问题,从一个给定的列表开始,然后附加另一个数字(用逻辑来防止超过平方和目标)

def makegen(N): #make a generator with max sumSquares: N
    def gen(l=[]): #empty list is valid with sum == 0
        yield l
        if l:
            i = l[-1] #keep it sorted to only include combinations not permutations
        else:
            i = 1 #only first iteration
        sumsquare = sum(x*x for x in l) #find out how much more we can add
        while sumsquare + i*i < N: #increase the appended number until we exceed target
            for x in gen(l+[i]): #recurse with appended list
                yield x
            i += 1
    return gen

用下面的方式调用我们的生成器(tee-hee:D)可以让我们得到我们想要的任何最大平方和

^{pr2}$
import itertools as it

it.takewhile(lambda x: sum_squares_is_at_least(x, 100), generate_sequences(5))

如果您现在确定了generate_sequences中的5,那么就让它yield只要它被调用:

^{pr2}$

然后这样使用:

it.takewhile(lambda x: sum_squares_is_at_least(x, 100), generate_sequences())

你在找itertools.takewhile?在

>>> from itertools import takewhile
>>> def gen():  #infinite generator
...    i=0
...    while True:
...       yield range(i,i+5)
...       i = i+1
... 
>>> [ x for x in takewhile( lambda x:sum(x)<20, gen() ) ]
[[0, 1, 2, 3, 4], [1, 2, 3, 4, 5]]
>>> 

相关问题 更多 >