I’ve tried to implement the algorithm in “Programming Interviews Exposed” in Python, as below, but it doesn’t seem to work (page 99 on the 2nd Edition):
The idea is to generate all combinations (not permutations) of a string, such that if you input “wxyz” you would get “w, wx, wxy, wxyz, wxz, wy, wyz, wz…. ” etc. if wz is displayed then zw is not valid.
def doCombine(strng, out, length, level, start):
for i in range(start, length):
out.append(strng[i])
print out
if (i < length - 1):
doCombine(strng, out, length, level +1, i + 1)
out = out[:-1]
x = list()
target = "wxyz"
print doCombine(target, x, len(target), 0, 0)
What could be amiss here? I get relatively garbage output.
In your current code, try changing the line
out = out[:-1]todel out[-1]. Both of those result inouthaving the last item removed, but in your current codeoutis reassigned instead of using the same list. This results in characters never being removed from the original list, which will obviously mess with the output pretty significantly.After making that change, here is the output: