I’m trying to write python code to print the powerset of a string, but am running into some bugs. Here’s what I’ve got:
def getperm (string):
perm = []
if len(string) == 0:
perm.append("")
return perm
#if len(string) == 1:
# perm.append(string)
# perm.append("")
first = string[0]
print "first = " + str(first)
rem = string[1:len(string)]
print "rem = " + str(rem)
words = getperm(rem)
for word in words:
for i in range(len(word)):
temp = string[0:i] + first + string[i:len(string)]
print "temp = " + str(temp)
perm.append(temp)
return perm
if __name__=="__main__":
a = "ab"
mag = getperm(a)
print mag
My expected output would be:
['', 'a', 'b', 'ab']
My actual output is:
[]
Can anyone help me figure out what’s going on? Is this some nuance of python, or is there a bug in my code? I think my code should be ok — I’m going off the fifth edition of Cracking the coding interview
Thank you!
You’re overthinking it
This part is trying to do too much
See how simple it really should be
Now you should be able to make the code look a lot nicer with a little refactoring