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!
'ab'
are'ab'
and'ba'
. – Cristobalcristobalitestring
(that's the name of a built-in module), and I'm not sure what you're trying to accomplish by callingstr
on objects that are already strings (first
,rem
, etc.). – Zionism