2014-03-01 24 views
-4

我試圖做這個工作,它確實提供了7個數字的程序,但一旦我增加到8+就失敗了。我不確定我做錯了什麼。該程序應該採用遞歸方式,使用7個以上的數字並輸出它們的所有6位數組合。Python遞歸6個數字中的7個數字的獨特組合

實施例輸入:1 2 3 4 5 6 7

輸出:

1 2 3 4 5 6 
1 2 3 4 5 7 
1 2 3 4 6 7 
1 2 3 5 6 7 
1 2 4 5 6 7 
1 3 4 5 6 7 
2 3 4 5 6 7 

這是我有。

def main(): 
    numbers = '1 2 3 5 8 13 21 34' 
    numbers = numbers.split(' ') 
    for i in range(len(lotto(numbers))): 
     print(lotto(numbers)[i]) 

def lotto(numbers): 
    if len(numbers) < 7: 
     return numbers 
    else: 
     output = list() 
     for i in range(len(numbers)): 
      rem = lotto(numbers[i+1:]) 
      output.append(numbers[:i]+rem) 
    return output 

當我把在1 2 3 5 8 13 21 34如上述所示,

['1', '3', '5', '8', '13', '21', '34'] 
['1', '2', '5', '8', '13', '21', '34'] 
['1', '2', '3', '8', '13', '21', '34'] 
['1', '2', '3', '5', '13', '21', '34'] 
['1', '2', '3', '5', '8', '21', '34'] 
['1', '2', '3', '5', '8', '13', '34'] 
['1', '2', '3', '5', '8', '13', '21'] 

是對輸出,而不是

1 2 3 5 8 13 
1 2 3 5 8 21 
1 2 3 5 8 34 
1 2 3 5 13 21 
1 2 3 5 13 34 
1 2 3 5 21 34 
1 2 3 8 13 21 
1 2 3 8 13 34 
1 2 3 8 21 34 
1 2 3 13 21 34 
1 2 5 8 13 21 
1 2 5 8 13 34 
1 2 5 8 21 34 
1 2 5 13 21 34 
1 2 8 13 21 34 
1 3 5 8 13 21 
1 3 5 8 13 34 
1 3 5 8 21 34 
1 3 5 13 21 34 
1 3 8 13 21 34 
1 5 8 13 21 34 
2 3 5 8 13 21 
2 3 5 8 13 34 
2 3 5 8 21 34 
2 3 5 13 21 34 
2 3 8 13 21 34 
2 5 8 13 21 34 
3 5 8 13 21 34 

問題不在列表vs沒有列表輸出,它是輸出的數量和大小。

+0

你說的'fails'意味着什麼? – thefourtheye

+1

這應該做什麼? –

+0

爲了清晰起見,我希望 – user3018875

回答

1

的Python已經有這個功能內置:http://docs.python.org/2/library/itertools.html#itertools.permutations

g = permutations('1 2 3 5 8 13 21 34'.split()) 
for v in g: 
    print " ".join(v) 

下面是示例輸出:

34 21 13 8 2 1 3 5 
34 21 13 8 2 1 5 3 
34 21 13 8 2 3 1 5 
34 21 13 8 2 3 5 1 
34 21 13 8 2 5 1 3 
34 21 13 8 2 5 3 1 
+0

我想輸入7+個數字,但結果只有6個字符。我也必須使用遞歸。 – user3018875

+0

@ user3018875那麼,使用內置的python是最好的解決方案,因爲該功能經過測試並且速度很快。但如果這是一個家庭作業問題,我認爲我在這裏沒有多大幫助。您應該在將來添加「家庭作業」標籤 –

0

使用''.join(list)

>>> x = 'hello world' 
>>> x = list(x) 
>>> x 
['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd'] 
>>> ''.join(x) 
'hello world' 
>>> 
相關問題