字符串的打印功率集 [英] print powerset of a string
本文介绍了字符串的打印功率集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试编写python代码以打印字符串的 powerset ,但是遇到了一些错误.这就是我所拥有的:
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
我的预期输出将是:
['', 'a', 'b', 'ab']
我的实际输出是:
[]
有人可以帮我弄清楚发生了什么吗?这是python的细微差别吗,还是我的代码中存在错误?我认为我的代码应该没问题-我即将结束《破解编码面试》的第五版
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
谢谢!
推荐答案
您想得太多
这部分正在尝试做很多事情
This part is trying to do too much
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)
看看它到底应该是多么简单
See how simple it really should be
def get_powerset (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 = get_powerset(rem)
perm.extend(words)
for word in words:
perm.append(first+word)
return perm
if __name__=="__main__":
a = "ab"
mag = get_powerset(a)
print mag
现在您应该可以通过少量重构使代码看起来更好
Now you should be able to make the code look a lot nicer with a little refactoring
这篇关于字符串的打印功率集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文