附加列表和递归(汉明距离)-Python 3 [英] Appending a List and Recursion (Hamming Distance) - Python 3
问题描述
我应该编写一个程序,该程序采用一串二进制代码和一个数字,并输出在原始字符串的汉密距离内的所有字符串.我有一个函数可以执行所有操作,但是在输出中,列表中有列表.我明白为什么会这样-该函数是递归的,有时它会返回可能值的列表.
I'm supposed to write a program that takes a string of binary code and a number, and outputs all the strings within that hamming distance of the original string. I have a function that does everything, but in the output there are lists within lists. I understand why this is - the function is recursive, and sometimes it will return a list of possible values.
问题是,我不知道如何更改它,因此它输出完整的字符串.例如,对于字符串"0000"和汉明距离"2",我得到: ["1 ['100','010','001']","01 ['10','01']","001 ['1']"]
The problem is, I don't know how to change it so it outputs complete strings. For example, for a string of "0000" and hamming distance "2", I get: ["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
返回的列表,则应该能够以正确的方式将字符串附加在一起-像这样:
If you loop through the list that is returned by hamming
you should be able to append the strings together the right way - like this:
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
这篇关于附加列表和递归(汉明距离)-Python 3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!