加油fighting 发表于 2020-3-31 10:50:25

递归代码运行问题

本帖最后由 加油fighting 于 2020-3-31 12:05 编辑

原问题:


图片方框的代码是怎么运行的?python代码运行不是从上往下么

按我理解:

result = Dec2Bin(dec//2)    要得出结果得一直运行自身函数 然后再执行return

所以最后应该 return的是 result = ''

思考后编辑:

大概明白流程了,但这样写很不好理解,引用答案中的更好的代码
def Dec2Bin(dec):
    result = ''
    if dec:
      return Dec2Bin(dec//2) + str(dec%2)
    else:
      return result
这个更好理解

qiuyouzhi 发表于 2020-3-31 11:03:01

https://fishc.com.cn/thread-159193-1-1.html

永恒的蓝色梦想 发表于 2020-3-31 11:13:49

python代码运行不是从上往下么回去复习函数

加油fighting 发表于 2020-3-31 11:39:16

qiuyouzhi 发表于 2020-3-31 11:03
https://fishc.com.cn/thread-159193-1-1.html

我还是没看懂你写的东西,帖子上另外一个人写的代码看懂了,我想知道 result = Dec2Bin(dec//2) 怎么回事
不得先把 等号后面的 Dec2Bin(dec//2) 的值给result 再执行下一段的return么? Dec2Bin(dec//2)一直运行下去最后返回的就是'',然后执行return result + str(dec%2)   也就是 假设输入9,最后返回了''+str(9%2)

qiuyouzhi 发表于 2020-3-31 11:41:01

加油fighting 发表于 2020-3-31 11:39
我还是没看懂你写的东西,帖子上另外一个人写的代码看懂了,我想知道 result = Dec2Bin(dec//2) 怎么回事 ...

它是分批次返回的,调用了就进去,直到dec等于0

raimond 发表于 2020-3-31 12:33:59

def Dec2Bin(dec):
    result = ''

    if dec:
      result = Dec2Bin(dec // 2)
      return result + str(dec % 2)
    else:
      return result


print(Dec2Bin(123))

print('' + str(1 % 2) + str(3 % 2) + str(7 % 2) + str(15 % 2) + str(30 % 2) + str(61 % 2) + str(123 % 2))
D:\1.png

_2_ 发表于 2020-3-31 12:51:00

raimond 发表于 2020-3-31 12:33


file文件,太秀了{:10_256:}
@永恒的蓝色梦想

永恒的蓝色梦想 发表于 2020-3-31 12:52:30

_2_ 发表于 2020-3-31 12:51
file文件,太秀了
@永恒的蓝色梦想

{:10_327:}他最后还是传上来了

_2_ 发表于 2020-3-31 12:53:07

永恒的蓝色梦想 发表于 2020-3-31 12:52
他最后还是传上来了

……呵呵                                                                        

Twilight6 发表于 2020-3-31 12:53:15

看来你的问题差不多解决了。
如果对递归那些想更加了解每一步是怎么运行的 这边我建议你可以试试不用IDLE编译器
用PyCharm 进行调试

永恒的蓝色梦想 发表于 2020-3-31 12:53:36

_2_ 发表于 2020-3-31 12:53
……呵呵

{:10_256:}大家都是大水比{:10_327:}

_2_ 发表于 2020-3-31 12:54:20

这是个递归啊兄dei
回去好好复习
页: [1]
查看完整版本: 递归代码运行问题