你的問題具體說你想看到的代碼是什麼樣子,所以這裏是一個O(n)的空間解決方案的手工編碼例如:
def combinations(input_list, acc=''):
if not input_list:
yield acc
return
next_val = input_list[0]
for rest in combinations(input_list[1:], acc):
yield rest
acc += next_val
# In python 3.2, you can use "yield from combinations(input_list[1:], acc)"
for rest in combinations(input_list[1:], acc):
yield rest
注意,子算術可能是昂貴的(因爲它有字符串多次複製),所以這裏是在複雜性方面稍微更有效的版本:
def combinations(input_list, acc='', from_idx=0):
if len(input_list) <= from_idx:
yield acc
return
next_val = input_list[from_idx]
for rest in combinations(input_list, acc, from_idx + 1):
yield rest
acc += next_val
# In python 3.2, you can use "yield from combinations(input_list[1:], acc)"
for rest in combinations(input_list, acc, from_idx + 1):
yield rest
我不使用Python 3.2,但如果你是,你可以寫這樣的:
def combinations(input_list, acc='', from_idx=0):
if len(input_list) <= from_idx:
yield acc
return
next_val = input_list[from_idx]
yield from combinations(input_list, acc, from_idx + 1)
acc += next_val
yield from combinations(input_list, acc, from_idx + 1)
我也應該注意到,這是純學術的,因爲itertools.combinations
做了很好的工作,適用於更廣泛的輸入數組(包括生成器表達式)。
-1因爲問題特別要求不要只使用'itertools.combinations'。 – lvc 2012-04-12 01:50:24