鱼C论坛

 找回密码
 立即注册
查看: 977|回复: 3

[已解决]python旧版第23讲的课后题不明白

[复制链接]
发表于 2022-2-26 20:42:54 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

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

print(Dec2Bin(62))


result = Dec2Bin(dec//2)  这里不理解,请大佬解释一下
最佳答案
2022-2-26 21:44:02
你这个要对递归有一个了解
你可以带一个比较小的值进去一步一步拿纸笔算算
我就带个dec = 5
  1. def Dec2Bin(dec):
  2.     result = ''

  3.     if dec: # 当dec = 0 时执行归一
  4.         result = Dec2Bin(dec//2) # 递
  5.         return result + str(dec % 2) # 归二
  6.     else:
  7.         return result # 归一


  8. print(Dec2Bin(5))

  9. """
  10. 第一次进入 Dec2Bin(5)
  11. 1递 dec = (5//2) => dec = 2 => 执行 Dec2Bin(2)
  12. 2递 dec = (2//2) => dec = 2 => 执行 Dec2Bin(1)
  13. 3递 dec = (1//2) => dec = 0 => 执行 归二 => return ''
  14. 3归 result = 3递返回值 => result = '' => 归二 => return '' + (1 % 2) =>  return '1'
  15. 2归 result = 3归二返回值 => result = '1' => 归二 => return '1' + (2 % 2) =>  return '10'
  16. 1归 result = 2归二返回值 => result = '10' => 归二 => return '10' + (5 % 2) =>  return '101'
  17. 全部归完输出 101
  18. """
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2022-2-26 21:35:30 | 显示全部楼层
递归2大条件
1, 函数调用自身 。 Dec2Bin(dec//2)
2,结束条件。  
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2022-2-26 21:44:02 | 显示全部楼层    本楼为最佳答案   
你这个要对递归有一个了解
你可以带一个比较小的值进去一步一步拿纸笔算算
我就带个dec = 5
  1. def Dec2Bin(dec):
  2.     result = ''

  3.     if dec: # 当dec = 0 时执行归一
  4.         result = Dec2Bin(dec//2) # 递
  5.         return result + str(dec % 2) # 归二
  6.     else:
  7.         return result # 归一


  8. print(Dec2Bin(5))

  9. """
  10. 第一次进入 Dec2Bin(5)
  11. 1递 dec = (5//2) => dec = 2 => 执行 Dec2Bin(2)
  12. 2递 dec = (2//2) => dec = 2 => 执行 Dec2Bin(1)
  13. 3递 dec = (1//2) => dec = 0 => 执行 归二 => return ''
  14. 3归 result = 3递返回值 => result = '' => 归二 => return '' + (1 % 2) =>  return '1'
  15. 2归 result = 3归二返回值 => result = '1' => 归二 => return '1' + (2 % 2) =>  return '10'
  16. 1归 result = 2归二返回值 => result = '10' => 归二 => return '10' + (5 % 2) =>  return '101'
  17. 全部归完输出 101
  18. """
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2022-2-26 22:11:28 From FishC Mobile | 显示全部楼层
大马强 发表于 2022-2-26 21:44
你这个要对递归有一个了解
你可以带一个比较小的值进去一步一步拿纸笔算算
我就带个dec = 5

非常感谢!
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-4-30 04:59

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表