Stackless Python - for循环中的递归?

时间:2011-06-10 02:57:49

标签: python recursion concurrent-programming stackless python-stackless

我是编程新手,我已经使用Python几个月了。我正试图让一个概念与Stackless一起工作,但是无法弄清楚如何(尽管我写的other test scripts与Stackless一起工作)。

Anywho,作为一个简单的例子,考虑通过列表运行的以下代码,并通过递归调用相同的函数找到它的所有排列(编辑:n维笛卡尔积)。

def traverseList(theList,temp,solutions,level=1):
    if level != len(theList):
        for x in theList:
            temp.append(x)
            traverseList(theList,temp,solutions,level+1)
            temp.pop()
    else:
        for x in theList:
            temp.append(x)
            solutions.append(temp[:])
            temp.pop()

myList = ["a",None,2,"gamma",8] #the list doesn't always have just numbers
solutionList = []
tempList = []

traverseList(myList,tempList,solutionList)
print("%s... %s" %(solutionList[0], solutionList[-1]))

产生:

['a', 'a', 'a', 'a', 'a']... [8, 8, 8, 8, 8]

到目前为止,似乎我发现Stackless和递归的唯一例子都是在函数结束后将函数发送出去的函数。永远不要在for循环的中间,如上所述。

我怎么会这样做?我如何将其转换为可以与tasklet而不是递归函数一起运行的脚本? (This version是我能想到的最好的,但无论我如何安排,它都会失败。这是许多尝试之一,此时我还可以将意大利面扔在墙上。)

在不使用bounceBack功能的情况下实现此方法的奖励电子cookie - 我还没有找到一种方法让一个tasklet多次将信息传递给自己而没有一个。

谢谢你的时间!

2 个答案:

答案 0 :(得分:1)

我认为你想研究“生成器”(即“yield”python关键字)。基本上,生成器允许您在函数调用的中间暂停并返回结果。当该函数再次被“调用”时,它将在“yield”之后的行重新开始。当你最终“回归”时,你就完成了。

以下是一些示例代码:

def myGen(*x):
  for elem in x:
    print "in myGen"
    yield elem

def myFn(*x):
  ret = []
  for elem in x:
    print "in myFn"
    ret.append(x)
  return x


for e in myGen(1,2,3,4,5):
  print e

for e in myFn(1,2,3,4,5):
  print e

输出如下。请注意,在生成器案例(myGen)中,“in myGen”与列表的打印交替打印。但是在myFn当然“首先打印出myFn”。

in myGen
1
in myGen
2
in myGen
3
in myGen
4
in myGen
5
in myFn
in myFn
in myFn
in myFn
in myFn
1
2
3
4
5

答案 1 :(得分:0)

如果我理解你的问题,并且因为你已经有了适当的方法,那么将其插入就行了

import stackless as s
channel = s.channel()
s.tasklet(traverseList)(myList,tempList,solutionList)
s.run()
print("%s... %s" %(solutionList[0], solutionList[-1]))

或者,您可以在参数列表中使用* args / ** kwargs到tasklet