This is the code I came up with:
def combinations(input):
ret = ['']
for i in range(len(input)):
ret.extend([prefix+input[i] for prefix in ret])
return ret
This algorithm is O(2^n) time, but can space be reduced? I heard using yield might work, but having trouble thinking through how to implement with yield. Please don’t use the built in combination function — I would like to see how it’s implemented.
Your question specifically said you wanted to see what the code would look like, so here is a hand coded example of an O(n) space solution:
Note that the substring arithmetic might be expensive (since it has to copy the string many times), so here is a slightly more efficient version in terms of complexity:
I’m not using Python 3.2, but if you were you could write it like this:
I should also note that this is purely academic since
itertools.combinationsdoes a fine job and works for a wider array of inputs (including generator expressions).