所以我看到了这段代码。我知道它的作用,但它的主要部分(for循环中的递归函数)让我失望。代码是
def flip(c):
return str(1-int(c))
def flip_s(s, i):
t = s[:i]+flip(s[i])+s[i+1:]
return t
def hamming(s, k):
if k>1:
c = s[-1]
if len(s) >= k:
s1=[]
for y in hamming(s[:-1], k):
s1.append(y+c)
else:
s1=[]
s2 = [y+flip(c) for y in hamming(s[:-1], k-1)]
r = []
r.extend(s1)
r.extend(s2)
return r
else:
return [flip_s(s,i) for i in range(len(s))]
def main():
print(hamming('0000',2))
main()
所以如果我们采取第一个for-loop
s1=[]
for y in hamming(s[:-1], k):
s1.append(y+c)
这将如何运作?感谢。
答案 0 :(得分:1)
与任何递归函数一样,理解正在发生的事情的一个好方法是执行干运行:
Calling hamming with s='0000', k=2
k is > 1
c = '0'
len(s) is >= 2
s1 = []
Calling hamming with s='000', k=2
k is > 1
c = '0'
len(s) is >= 2
s1 = []
Calling hamming with s='00', k=2
k is > 1
c = '0'
len(s) is >= 2
s1 = []
Calling hamming with s='0', k=2
k is > 1
c = '0'
len(s) is _not_ >= k
s1 = []
Calling hamming with s='', k=1
k is _not_ > 1
returning []
s2 = []
r = []
returning []
Calling hamming with s='0', k=1
k is _not_ > 1
returning ['1']
s2 = ['11']
r = ['11']
returning ['11']
s1 = ['110']
Calling hamming with s='00', k=1
k is _not_ > 1
returning ['10', '01']
s2 = ['101', '011']
r = ['110', '101', '011']
returning ['10', '101', '011']
s1 = ['100', '1010', '0110']
Calling hamming with s='000', k=1
k is _not_ > 1
returning ['1100', '010', '001']
s2 = ['1001', '0101', '0011']
returning ['1100', '1010', '0110', '1001', '0101', '0011']
Done
因此hamming(s, k)
会返回距离k
远离汉明距离s
的二进制字符串列表。
分解递归函数的另一个好方法是添加depth
参数并使用它来缩进print
语句,如下所示:
def hamming(s, k, depth):
print ' '*(4*depth) + 'hamming(' + s + ', ' + str(k) + ')'
if k>1:
c = s[-1]
if len(s) >= k:
s1=[]
for y in hamming(s[:-1], k, depth+1):
s1.append(y+c)
else:
s1=[]
s2 = [y+flip(c) for y in hamming(s[:-1], k-1, depth+1)]
r = []
r.extend(s1)
r.extend(s2)
print ' '*(4*depth) + 'r = ' +str( r)
return r
else:
x = [flip_s(s,i) for i in range(len(s))]
print ' '*(4*depth) + 'x = ' + str(x)
return x
这导致输出如下:
>>> hamming('1001', 2, 0)
hamming(1001, 2)
hamming(100, 2)
hamming(10, 2)
hamming(1, 2)
hamming(, 1)
x = []
r = []
hamming(1, 1)
x = ['0']
r = ['01']
hamming(10, 1)
x = ['00', '11']
r = ['010', '001', '111']
hamming(100, 1)
x = ['000', '110', '101']
r = ['0101', '0011', '1111', '0000', '1100', '1010']
['0101', '0011', '1111', '0000', '1100', '1010']
答案 1 :(得分:0)
hamming是一个返回列表的函数。 因此,在你的for循环中,你将遍历hamming返回的列表...将c添加到该列表的每个元素并将结果附加到s1。