栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

【Python】: 容易被忽略的一个小问题:int 变量判断是否是None时怎么判断?

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【Python】: 容易被忽略的一个小问题:int 变量判断是否是None时怎么判断?

最近在刷题【牛客剑指offer刷题】:Python:18. 删除链表的节点
时,遇到这样一个问题,由于写错了一句话导致怎么也不通过,最后发现原来是判断 int 为 0 时判断为 False 了, 这里记录一下:

输入:{2, 3, 4, 0, 1}, 0

错误的代码:
class Solution:
    def deleteNode(self , head: ListNode, val: int) -> ListNode:
        # write code here
        # 注意:这里的val如果为0 的话那么判断not val就是TRUE
        if not head or not val:
            return None
        if head.val == val:
            return head.next
        pre, cur = None, head
        while cur:
            if cur and cur.val == val:
                cur  = pre
                cur.next = cur.next.next
            else:
                pre = cur
                cur = cur.next
        return head

错误的输出:{}

正确的代码:
class Solution:
    def deleteNode(self , head: ListNode, val: int) -> ListNode:
        # write code here
        # 注意:这里的val如果为0 的话那么判断val is None就是False
        if not head or val is None:
            return head
        if head.val == val:
            return head.next
        pre, cur = None, head
        while cur:
            if cur and cur.val == val:
                cur  = pre
                cur.next = cur.next.next
            else:
                pre = cur
                cur = cur.next
        return head

正确输出:{4,1,9}

总结:

以后需要判断 int 变量是否是None值时:不能使用if not val而应该使用if val is None。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/588032.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号