Python FAQ 019 递归(4)
本帖最后由 一个账号 于 2020-3-5 17:51 编辑Python FAQ 019 递归(4)
问题:
def Dec2Bin(dec):
result = ''
if dec:
result = Dec2Bin(dec//2)
return result + str(dec%2)
else:
return result
print(Dec2Bin(62))
这个程序是什么意思啊?
我的解答:
假设dec为9:
1: result = Dec2Bin(9//2)
2: result = Dec2Bin(4//2)
3:result = Dec2Bin(2 // 2)
4:result = Dec2Bin(1 // 2)
返回:
1:return result, result = 9 % 2 == 1
2:return result, result = 4 % 2 == 0
3:return result, result = 2 % 2 == 0
4:return reuslt, result = 1 % 2 == 1
这时全部返回完毕,结果就是1001 您好,感谢回复,看了您的过程之后,我明白了“result = Dec2Bin(dec//2)”这个代码的意思,还想请教一下“return result + str(dec%2)”的意思是把余数用字符串的形式合并在一起吗?另外,else是指什么情况? cxj9103 发表于 2020-3-14 14:46
您好,感谢回复,看了您的过程之后,我明白了“result = Dec2Bin(dec//2)”这个代码的意思,还想请教一下“ ...
1,是的
2,如果除没了就直接返回result qiuyouzhi 发表于 2020-3-14 14:51
1,是的
2,如果除没了就直接返回result
2. 就是针对待转换数据为0或者1的情况,对吗? cxj9103 发表于 2020-3-14 15:20
2. 就是针对带转换数据为0或者1的情况,对吗?
为0的情况,为1时还要再除一遍 qiuyouzhi 发表于 2020-3-14 15:21
为0的情况,为1时还要再除一遍
明白了,非常感谢您的指点和耐心! cxj9103 发表于 2020-3-14 15:33
明白了,非常感谢您的指点和耐心!
没事的啦{:10_256:} 本帖最后由 龟派气功 于 2020-3-21 15:46 编辑
def Dec2Bin(dec):
result = ''
if dec:
return Dec2Bin(x//2) + str(dec%2)
else:
return result
写成这个样子我比较好理解。result根本不需要在循环里面
假如 x = 9
递:
B(9) = B(4) + str(1)
B(4) = B(2) + str(0)
B(2) = B(1) + str(0)
B(1) = B(0) + str(1)
归:
B(9) = B(B(B(B(0) + str(1)) + str(0)) + str(0)) + str(1)) 龟派气功 发表于 2020-3-21 15:38
写成这个样子我比较好理解。result根本不需要在循环里面
可是你的代码不能运行啊 qiuyouzhi 发表于 2020-3-21 15:41
可是你的代码不能运行啊
我还有一个x没换过来。。
def Dec2Bin(dec):
result = ''
if dec:
return Dec2Bin(dec//2) + str(dec%2)
else:
return result
页:
[1]