2013-09-26 60 views
0

該函數在函數內部具有函數。該程序創建一個包含所有可能的字符串組合的列表。我遇到了內部函數的問題,它是遞歸的。有人可以幫幫我嗎?有人可以幫我理解下面的python程序嗎?

def combine0(s): 
    out = [] 
    length = len(s) 
    def loc(start): 
     for i in range(start, length): 
      out.append(s[i]) 
      print (''.join(out)) 
      if (i < length-1): 
       loc(i+1) 
      del out[-1] 
    loc(0) 

combine0('mary') 

產生

m 
ma 
mar 
mary 
may 
mr 
mry 
my 
a 
ar 
ary 
ay 
r 
ry 
y 
+0

它不起作用 –

+1

'def loc(start):'不正確地縮進? – gregb212

+0

更新了縮進 –

回答

0

當與被叫參數'Mary',這就是combine0所做的:

s = 'Mary' 
out = [] 
length = len(s) # in this case length=4 

# for i in range(0, 4): 
# i = 0 
out.append(s[0]) # s[0] = 'M', out = ['M'] 
print(''.join(out)) # print('M') 
# if i < length - 1: => if 0 < 3: 
# loc(i + 1) => loc(1) 
# for j in range(1, 4): 
# j = 1 
out.append(s[1]) # s[1] = 'a', out = ['M', 'a'] 
print(''.join(out)) # print('Ma') 
# if j < length - 1: => if 1 < 3: 
# loc(j + 1) => loc(2) 
# for k in range(2, 4): 
# k = 2 
out.append(s[2]) # s[2] = 'r', out = ['M', 'a', 'r'] 
print(''.join(out)) # print ('Mar') 
# if k < length - 1: => if 2 < 3: 
# loc(k + 1) => loc(3) 
# for l in range(3, 4): 
# l = 3 
out.append(s[3]) # s[3] = 'y', out = ['M', 'a', 'r', 'y'] 
print(''.join(out)) # print('Mary') 
# if l < length - 1: => if 3 < 3: 
# condition fails -> do not recurse 
del out[-1] # out = ['M', 'a', 'r'] 
# end of for l in range(3, 4) 
del out[-1] # out = ['M', 'a'] 
# k = 3, now in for k in range(2, 4): 
out.append(s[3]) # s[3] = 'y', out = ['M', 'a', 'y'] 
print(''.join(out)) # print('May') 
# if k < length - 1: => if 3 < 3: 
# condition fails -> do not recurse 
del out[-1] # out = ['M', 'a'] 
# end of for k in range(2, 4) 
del out[-1] # out = ['M'] 
# j = 2, now in for j in range (1, 4): 
out.append(s[2]) # s[2] = 'r', out = ['M', 'r'] 
print(''.join(out)) # print('Mr') 
# if j < length - 1: => if 2 < 3: 
# loc(j + 1) => loc(3) 
# for m in range(3, 4) 
# m = 3 
out.append(s[3]) # s[3] = 'y', out = ['M', 'r', 'y'] 
print(''.join(out)) # print('Mry') 
# if m < length - 1: => if 3 < 3: 
# condition fails -> do not recurse 
del out[-1] # out = ['M', 'r'] 
# end of for m in range(3, 4) 
del out[-1] # out = ['M'] 
# j = 3, now in for j in range (1, 4): 
out.append(s[3]) # s[3] = 'y', out = ['M', 'y'] 
print(''.join(out)) # print('My') 
# if j < length - 1: => if 3 < 3: 
# condition fails -> do not recurse 
del out[-1] # out = ['M'] 
# end of for j in range(1, 4) 
del out[-1] # out = [] 
# i = 1 

#... you get the rest 
1

是的,這是自稱的函數,名字是遞歸調用。這種代碼的Here are some descriptions

改正的代碼將是:

def combine0(s): 
    out = [] 
    length = len(s) 
    def loc(start): 
     for i in range(start, length): 
      out.append(s[i]) 
      print (''.join(out)) 
      if (i < length-1): 
       loc(i+1) 
      del out[-1] 
    loc(0) 

combine0("abc") 

和輸出爲 「ABC」:

一個 AB ABC 交流 b BC Ç

相關問題