简体   繁体   English

如何在 python 中使用生成器从 dfs 产生结果?

[英]how to use a generator in python to yield results from dfs?

I have a dfs function (permutation) in which it takes long time to compute all possible values;我有一个 dfs function (排列),其中计算所有可能的值需要很长时间; I wish to create a generator such that every time I call a function get_value it will provide a possible outcome.我希望创建一个生成器,这样每次我调用 function get_value时,它都会提供一个可能的结果。 So in the example below when calling get_value 3 times the results should be:因此,在下面的示例中,当调用get_value 3 次时,结果应该是:

['1', '2', '3', '4']
['1', '2', '4', '3']

my current execution:我目前的执行:

class Solution:
     
 def permutation(self, lst):
 
    if len(lst) == 0:
        return []
  
    if len(lst) == 1:
        return [lst]
  
    l = []
 
    for i in range(len(lst)):
       m = lst[i]
  
       remLst = lst[:i] + lst[i+1:]
       for p in self.permutation(remLst):
           l.append([m] + p)
    return l

 #def get_value():
 #      yield ???

if __name__=='__main__':
    
    s = Solution()
    r = s.permutation(['1','2','3','4']) 

    for p in r:
        print (p)

    #what I want is:
    s = Solution()
    v1 = s.get_value() #['1', '2', '3', '4']
    v2 = s.get_value() #['1', '2', '4', '3']
    #and so forth

There is a built-in for this: permutations from the package itertools (no pip install required):有一个内置的:package itertoolspermutations (不需要安装 pip):

from itertools import permutations
r = permutations(['1','2','3','4'])

next(r)
# ('1', '2', '3', '4')
next(r)
# ('1', '2', '4', '3')
next(r)
# ('1', '3', '2', '4')
next(r)
# ('1', '3', '4', '2')

...

For yields in recursion, you can use yield from对于递归中的收益率,您可以使用yield from

    def permutation(self, lst):

        if len(lst) == 0:
            return

        if len(lst) == 1:
            yield lst

        for i in range(len(lst)):
            m = lst[i]

            remLst = lst[:i] + lst[i+1:]
            yield from ([m] + p for p in self.permutation(remLst))

The for loop will still work: for 循环仍然有效:

r = s.permutation(['1', '2', '3', '4'])
for p in r:
    print(p)

Instead of get_value , you should use next() :而不是get_value ,您应该使用next()

r = s.permutation(['1', '2', '3', '4'])
print(next(r))
print(next(r))
print(next(r))

Just be aware that the for loop consumes the iterator:请注意 for 循环消耗迭代器:

r = s.permutation(['1', '2', '3', '4'])
for p in r:
    print(p)
r = s.permutation(['1', '2', '3', '4']) # Reset the iterator otherwise `next` will fail
print(next(r))
print(next(r))
print(next(r))

Use yield from :使用yield from

def permutation(self, lst):
    if not lst:
        return []
    if len(lst) == 1:
        yield lst
    for i in range(len(lst)):
        m = lst[i]
        remLst = lst[:i] + lst[i+1:]
        yield from ([m] + p for p in self.permutation(remLst))

Then, use next :然后,使用next

it = s.permutation(['1', '2', '3', '4'])
print(next(it)) # ['1', '2', '3', '4']
print(next(it)) # ['1', '2', '4', '3']
print(next(it)) # ['1', '3', '2', '4']

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

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