Câu hỏi của bạn đặc biệt nói rằng bạn muốn xem những gì mã sẽ như thế nào, vì vậy đây là một mã ví dụ bàn tay của một O (n) giải pháp không gian:
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
Lưu ý rằng số học chuỗi con có thể rất tốn kém (vì nó có để sao chép chuỗi nhiều lần), vì vậy đây là một phiên bản nhẹ hiệu quả hơn về sự phức tạp:
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
tôi không sử dụng Python 3.2, nhưng nếu bạn là bạn có thể viết nó như thế này:
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)
Tôi cũng nên lưu ý rằng đây hoàn toàn là học từ itertools.combinations
làm một công việc tốt và làm việc cho một rộng hơn mảng đầu vào (bao gồm các biểu thức máy phát).
-1 vì câu hỏi yêu cầu cụ thể không chỉ sử dụng 'itertools.combinations'. – lvc