鱼C论坛

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

【Python递归求和】

[复制链接]
发表于 2018-4-1 16:09:27 | 显示全部楼层 |阅读模式

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

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

x
def sumtree(L):
        tot = 0
        for x in L:
                try:
                        if not isinstance(x, list):
                                tot += x
                        else:
                                tot += sumtree(x)
                except:
                        print("Crashed!")
        return tot

print(sumtree([1,2,3,(4,5)]))
--------------------------------------
Crashed!
6
[Finished in 0.1s]
------------------------------------------
如果参数是列表的话没事,但是如果参数中含有tuple,则会崩溃。
为什么呢??
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

 楼主| 发表于 2018-4-1 16:13:49 | 显示全部楼层
def sumtree(L):
        tot = 0
        for x in L:
                try:
                        if isinstance(x, list) or isinstance(x, tuple):
                                tot += sumtree(x)
                        else:
                                tot += x
                except:
                        print("Crashed!")
        return tot

print(sumtree([1,2,3,(4,5)]))

----------------------------------------------

这样写就好了。
可是……请看这一句:``if not isinstance(x, list):``——这句代码不是包括了等于tuple的情况吗(从逻辑上看。?)
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2018-4-1 16:18:10 | 显示全部楼层
你的普通元素和元祖都能被x替代,他们都满足不是列表
数字可以加数字,数字能加元祖吗
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2018-4-1 16:22:58 | 显示全部楼层
  1. def sumtree(L):
  2.         tot = 0
  3.         for x in L:
  4.                 try:
  5.                         if not isinstance(x, (list, tuple)):
  6.                                 tot += x
  7.                         else:
  8.                                 tot += sumtree(x)
  9.                 except:
  10.                         print("Crashed!")
  11.         return tot

  12. print(sumtree([1,2,3,(4,5)]))
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2018-4-1 23:30:14 | 显示全部楼层
ABC23 发表于 2018-4-1 16:13
def sumtree(L):
        tot = 0
        for x in L:

1.list 和 tuple是两个不同的对象instance判断也是不同的
2.上面for x in L的时候,L[3]是(4,5),L[3][0]是4,L[3][1]是5,所以整数自加会报错,你可以仔细看看错误提示的.
3.后面那个能用,是因为所有的列表和元祖都被再次调用sumtree()了,所有的返回值tot都是整数,可以相互相加
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

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

本版积分规则

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

GMT+8, 2025-12-29 01:23

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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