对于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')
一些伪代码来说明出了什么问题。
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)
换句话说,由于递归,您的排列不会从您认为它们开始的位置开始。
当你在你的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']