## Python：使用递归算法作为生成器？内容来源于 Stack Overflow，并遵循CC BY-SA 3.0许可协议进行翻译与使用

• 回答 (2)
• 关注 (0)
• 查看 (43)

def getPermutations(string, storage, prefix=""):
if len(string) == 1:
storage.append(prefix + string)   # <-----
else:
for i in range(len(string)):
getPermutations(string[:i]+string[i+1:], storage, prefix+string[i])

storage = []
getPermutations("abcd", storage)
for permutation in storage: print permutation

def getPermutations(string, prefix=""):
if len(string) == 1:
yield prefix + string             # <-----
else:
for i in range(len(string)):
getPermutations(string[:i]+string[i+1:], prefix+string[i])

for permutation in getPermutations("abcd"):
print permutation

from types import GeneratorType

def flatten(*stack):
stack = list(stack)
while stack:
try: x = stack[0].next()
except StopIteration:
stack.pop(0)
continue
if isinstance(x, GeneratorType): stack.insert(0, x)
else: yield x

def _getPermutations(string, prefix=""):
if len(string) == 1: yield prefix + string
else: yield (_getPermutations(string[:i]+string[i+1:], prefix+string[i])
for i in range(len(string)))

def getPermutations(string): return flatten(_getPermutations(string))

for permutation in getPermutations("abcd"): print permutation

flatten允许我们继续在另一台发电机上取得进展yield而不是迭代yield手动处理每个项目。

Python 3.3将添加yield from语法：

def getPermutations(string, prefix=""):
if len(string) == 1:
yield prefix + string
else:
for i in range(len(string)):
yield from getPermutations(string[:i]+string[i+1:], prefix+string[i])

Tina

Go Serverless!

### 域名在腾讯备的案，解析的腾讯云，现在想把域名解析到别商家的服务器，腾讯云会把备案注销吗？

software微软、谷歌、腾讯、阿里、百度……

Hyman Wang

Jinqn