鱼C论坛

 找回密码
 立即注册
查看: 1810|回复: 4

[已解决]关于递归循环问题

[复制链接]
发表于 2017-9-15 15:40:40 | 显示全部楼层 |阅读模式

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

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

x
<def test(x):     
    if not x:  
        return 0  
    else :   
        return x[0]+test(x[1:])
  
      
print(test([1,2,3]))>

1、这段代码test(x[1:]是递增的,请问是什么原因使它递增?
2、如果我装test(x[1:]改成test(x[:2],让它递减,代码怎么改?

请大牛帮我解答一下,我困了两天了,非常感谢!
最佳答案
2017-9-15 17:32:41
def test(x):     
    if not x:  
        return 0  
    else :   
        return x[0]+test(x[1:])
这里存在递归调用,test函数不止调用了一次,你可以加一个print看一下,而每次输入的参数因为切片问题,导致他是递增的。
至于想要递减
def test(x):
    if not x:
        return 0
    else:
        return x[len(x)-1] + test(x[:len(x)-1])
   
print (test([1,2,3]))
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2017-9-15 16:09:58 | 显示全部楼层
  1. def test(x):
  2.     if not x:
  3.         return 0
  4.     else:
  5.         print(x[len(x)-1],x)
  6.         return x[len(x)-1]+test(x[:len(x)-1])
  7. print(test([1,2,3,4]))
复制代码

请问是这种效果么
  1. 4 [1, 2, 3, 4]
  2. 3 [1, 2, 3]
  3. 2 [1, 2]
  4. 1 [1]
  5. 10
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2017-9-15 17:32:41 | 显示全部楼层    本楼为最佳答案   
def test(x):     
    if not x:  
        return 0  
    else :   
        return x[0]+test(x[1:])
这里存在递归调用,test函数不止调用了一次,你可以加一个print看一下,而每次输入的参数因为切片问题,导致他是递增的。
至于想要递减
def test(x):
    if not x:
        return 0
    else:
        return x[len(x)-1] + test(x[:len(x)-1])
   
print (test([1,2,3]))
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2017-9-17 21:24:39 From FishC Mobile | 显示全部楼层
SuMo 发表于 2017-9-15 17:32
def test(x):     
    if not x:  
        return 0  

非常感谢,虽然不知道为什么切片会递增
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2017-9-18 10:15:35 | 显示全部楼层
ivausi 发表于 2017-9-17 21:24
非常感谢,虽然不知道为什么切片会递增

建议你通过spyder.... 进行一下代码调试..... 跟一下 你就知道
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

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

本版积分规则

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

GMT+8, 2026-3-2 10:41

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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