3

我对编程还很陌生,而且我已经使用 Python 工作了几个月了。我试图让一个概念与 Stackless 一起工作,但就是不知道如何(尽管我已经编写了其他与 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 而不是递归函数运行的脚本?(这个版本是我能想到的最好的版本,但无论我怎么安排都失败了。这是许多尝试中的一个,我不妨在这一点上把意大利面扔到墙上。)

奖励 e-cookie 用于在没有bounceBack 功能的情况下执行此操作 - 我还没有找到一种方法让单个 tasklet 在没有一个的情况下多次将信息传递给它自己。

谢谢你的时间!

4

2 回答 2

1

I think you want to research "generators" (i.e. "yield" python keyword). Basically a generator lets you pause in the middle of a function call and sort of return the result. When the function is "called" again it resumes at the line just after the "yield". When you finally "return" you are done.

Here's some example code for you:

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

The output is below. Notice in the generator case (myGen), the "in myGen" is printed alternating with the print of the list. But in the myFn of course "in myFn" is printed out first.

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
于 2011-06-21T02:13:02.120 回答
0

如果我正确理解了您的问题并且由于您已经制定了方法,那么将其插入即可

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

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

于 2011-07-25T13:04:11.533 回答