V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
achilles111
V2EX  ›  Python

Python 问题求助,函数 return 了一个正整数,变量接收到的返回值却是 None

  •  
  •   achilles111 · 2019-05-01 16:01:08 +08:00 · 2248 次点击
    这是一个创建于 1828 天前的主题,其中的信息可能已经有所发展或是发生改变。
    leetcode 上一道题目,求数组中能组成的最大周长三角形,代码如下:

    # 给定由一些正数(代表长度)组成的数组 A,返回由其中三个长度组成的、
    # 面积不为零的三角形的最大周长。如果不能形成任何面积不为零的三角形,返回 0。

    # 三角形要求两边之和大于第三边,两边之差小于第三边

    # 先排序,之后取末尾三个数字,若 n-2 + n-1 < n,则递归 n-1。若满足就是最大边长三角形

    def largestPerimeter(A):
    '''
    求数组 A 中能组成的最大周长三角形
    in param A:正整数数组 A
    return :最大周长或者 0
    '''
    if len(A) == 3:
    if isTriangle(A[0],A[1],A[2]):
    return sum(A)
    else:
    return 0
    else:
    A.sort()
    if isTriangle(A[-1],A[-2],A[-3]):
    return sum(A[-3:])
    else:
    num = A.pop()
    largestPerimeter(A)

    def isTriangle(a,b,c):
    '''
    判断传入的 a、b、c 能否组成三角形
    '''
    return a+b>c and abs(a-b)<c and a+c>b and abs(a-c)<b \
    and b+c>a and abs(b-c)<a

    # 测试用例[3,2,3,4]——>10,[3,6,2,3]——>8
    A = [3,6,2,3]
    a = largestPerimeter(A)
    print(a)
    print(largestPerimeter(A))

    控制台输出:
    None
    8

    问题:如上,我用[3,6,2,3]列表进行测试,返回值应该是 8.
    但是我将函数返回值赋值给变量 a,print(a )却是 None。在 leetcode 上提交也是。但是如果我直接 print(largestPerimeter(A)),又能够输出 8.希望大佬帮忙解答,十分感谢
    achilles111
        1
    achilles111  
    OP
       2019-05-01 16:31:12 +08:00
    已经解决了,根本原因不在于变量接收函数的 return 上,而是函数内部用到了递归,而递归没有 return 语句,所以实际上没有返回值,
    将递归的那一句修改为
    return largestPerimeter(A)
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   753 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 24ms · UTC 21:36 · PVG 05:36 · LAX 14:36 · JFK 17:36
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.