对于enumerate()函数中的给定字符串,当i = 0时,它应该打印第一个元素。但是我不明白为什么这次要打印第二个元素。在我看来,在i = 0的第一次迭代中,它应该为给定的字符串('abc')打印'a'。而是打印“ b”。帮我明白另外,在第一次迭代中,当i = 0时s [:i]的值是'b'吗?
def permute(s):
out = []
# Base Case
if len(s) == 1:
out = [s]
else:
# For every letter in string
for i, let in enumerate(s):
# Step 2 and 3
for perm in permute(s[:i] + s[i+1:]):
print ("current i is:", i)
print ("current let is:", let)
print ("current perm is:", perm)
print ("current s[:i] is:", s[:1])
# Add it to output
out += [let + perm]
print("current out is", out)
print("\n")
return out
permute('abc')
答案 0 :(得分:1)
当在您的enumerate
循环中调用permute
时,它实际上重新运行了您刚刚执行的操作,并且状态不再是您所认为的...:
def permute(s):
out = []
# Base Case
if len(s) == 1:
out = [s]
else:
# For every letter in string
for i, let in enumerate(s):
print 'If this is a first call to permute, things are like you expect...'
print 'Otherwise, something looks weird ;-)'
print ("current i is:", i)
print ("current let is:", let)
print ("current s[:i] is:", s[:1])
# Step 2 and 3
for perm in permute(s[:i] + s[i+1:]):
print 'This only comes after another call to permute'
print ("current i is:", i)
print ("current let is:", let)
print ("current s[:i] is:", s[:1])
# Add it to output
out += [let + perm]
return out
permute('abc')
# If this is a first call to permute, things are like you expect...
# Otherwise, something looks weird ;-)
# ('current i is:', 0)
# ('current let is:', 'a')
# ('current s[:i] is:', 'a')
# If this is a first call to permute, things are like you expect...
# Otherwise, something looks weird ;-)
# ('current i is:', 0)
# ('current let is:', 'b')
# ('current s[:i] is:', 'b')
# This only comes after another call to permute
# ('current i is:', 0)
# ('current let is:', 'b')
# ('current s[:i] is:', 'b')
# etc...
不太确定要实现什么,但是删除对permute
的递归调用对我来说似乎是个好主意:
def permute(s):
# Base Case
if len(s) == 1:
out = [s]
else:
out = []
for i, let in enumerate(s):
print ("current i is:", i)
print ("current let is:", let)
print ("current s[:i] is:", s[:1])
out += [let + s[:i] + s[i+1:]]
print("current out is", out)
print("\n")
return out
foo = permute('abc')
print foo
# ['abc', 'bac', 'cab']
答案 1 :(得分:0)
一些伪代码来说明出了什么问题。
for perm in permute( s[:0] + s[1:] = 'bc'):
for i, let in enumerate('bc'):
for perm in permute ('bc'[:i] + 'bc'[i+1:]):
print stuff
#print(i=0)
#print(let = b)
#print(perm = c)
#printinseconditeration(i=1, let = c, perm=b)
换句话说,由于递归,排列不会从您认为它们开始的地方开始。