【发布时间】:2012-10-18 00:55:05
【问题描述】:
我在尝试使用递归创建排列代码时遇到了麻烦。这假设将一个列表返回给使用,其中包含每个字母的所有可能位置。所以对于 cat 这个词,它应该返回 ['cat','act',atc,'cta','tca','tac'] 。到目前为止我有这个
def permutations(s):
lst=[]
if len(s) == 1 or len(s) == 0 :
# Return a list containing the string, not the string
return [s]
# Call permutations to get the permutations that don't include the
# first character of s
plst = permutations(s[1:])
print(plst)
for item in plst:
print (item)
plst= permutations(s[1+1:])
# Now move through each possible position of the first character
# and create a new string that puts that character into the strings
# in plst
for i in range(len(s)):
pass
# Create a new string out of item
# and put it into lst
# Modify
for item in lst:
print(index)
那里有步骤,但我不知道如何使用它们
【问题讨论】:
-
我不知道你为什么要写这个,但你也可以使用itertools.permutations()。它使用
yield,因此不必构造整个列表。 -
我还没有学会如何使用yield。所以我想知道是否有办法在不使用 yeild 的情况下执行此代码
-
你为什么不检查 Numpy.. 我认为它提供了这些功能。虽然不确定
-
@brianChiem,
itertools.permutations()使用yield对您来说基本上是透明的,所以试一试。如果您不打算在for循环中对其进行迭代,请使用list(itertools.permutations(...)。
标签: python recursion permutation