我应该编写一个程序,它接受一串二进制代码和一个数字,并输出原始字符串的汉明距离内的所有字符串。我有一个可以做所有事情的函数,但在输出中列表中有列表。我明白为什么会这样 - 该函数是递归的,有时它会返回可能值的列表。
问题是,我不知道如何更改它,因此它会输出完整的字符串。例如,对于"0000"和汉明距离"2"的字符串,我得到:["1['100', '010
', '001']", "01['10', '01']", "001['1']"]但我想要的是:
1100
1010
1001
0110
0101
0011
代码如下:
def hamming(num, dist):
if dist == 0:
return num
else:
outputlist = list()
for item in range(len(num)):
if len(num[item:]) > dist - 1:
if num[item] == "0":
restoflist = hamming(num[item + 1:], dist - 1)
outputlist.append(num[:item] + "1" + str(restoflist))
else:
restoflist = hamming(num[item + 1:], dist - 1)
outputlist.append(num[:item] + "0" + str(restoflist))
return outputlist
如果你循环访问hamming
返回的列表,你应该能够以正确的方式将字符串附加到一起 - 像这样:
def hamming(num, dist):
if dist == 0:
return num
else:
outputlist = list()
for item in range(len(num)):
if len(num[item:]) > dist - 1:
if num[item] == "0":
restoflist = hamming(num[item + 1:], dist - 1)
if type(restoflist) is not str
for rest in restoflist:
outputlist.append(num[:item] + "1" + str(rest))
else
outputlist.append(num[:item] + "1" + str(restoflist))
else:
restoflist = hamming(num[item + 1:], dist - 1)
if type(restoflist) is not str
for rest in restoflist:
outputlist.append(num[:item] + "0" + str(rest))
else
outputlist.append(num[:item] + "0" + str(restoflist))
return outputlist
您可以通过
返回[num]
而不是基本情况下的num
来修复它,在一般情况下,使用 map
和 extend
而不是append
来组合递归调用的结果:
def hamming(num, dist):
if dist == 0:
return [num]
else:
outputlist = list()
for item in range(len(num)):
if len(num[item:]) > dist - 1:
if num[item] == "0":
restoflist = hamming(num[item + 1:], dist - 1)
outputlist.extend(map(lambda x: num[:item] + "1" + x, restoflist))
else:
restoflist = hamming(num[item + 1:], dist - 1)
outputlist.extend(map(lambda x: num[:item] + "0" + x, restoflist))
return outputlist
>>> hamming('0000', 2)
['1100', '1010', '1001', '0110', '0101', '0011']
>>>