La tua domanda specificamente detto che volevi vedere ciò che il codice sarà simile, ecco una mano esempio codificato di un O (n) soluzione di spazio:
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
Nota che la stringa aritmetica potrebbe essere costoso (in quanto si deve copiare la stringa molte volte), ecco una versione leggermente più efficiente in termini di complessità:
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
non sto usando Python 3.2, ma se tu fossi si può scrivere in questo modo:
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)
Si noti anche che questo è puramente accademica in quanto itertools.combinations
fa un ottimo lavoro e lavora per una più ampia array di input (incluse le espressioni del generatore).
-1 perché la domanda chiede in particolare di non usare solo itertools.combinations'. – lvc