python - 链表 while 语句(来自 LeetCode 的 addTwoNumbers)
问题描述
以下是我提交并随后被接受的代码。
class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
result = ListNode(0)
result_tail = result
carry = 0
while l1 or l2 or carry:
val1 = (l1.val if l1.val else 0)
val2 = (l2.val if l2.val else 0)
out = (val1+val2 + carry)%10
carry = (val1+val2 + carry)//10
result_tail.next = ListNode(out)
result_tail = result_tail.next
l1 = (l1.next if l1.next else None)
l2 = (l2.next if l2.next else None)
return result.next
最初,我有,while l1.val or l2.val or carry:
但它被拒绝并显示以下错误消息:
AttributeError:“NoneType”对象具有 njo 属性“val”
但是,链接节点列表 l1 和 l2 显然具有属性 val 和 next。
我不知道为什么while l1.val or l2.val or carry:
没有工作。
下面是我最初提交但被拒绝的代码。
class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
result = ListNode(0)
result_tail = result
carry = 0
print(l1.val)
print(l2.val)
while l1.val or l2.val or carry:
val1 = (l1.val if l1.val else 0)
val2 = (l2.val if l2.val else 0)
out = (val1+val2 + carry)%10
carry = (val1+val2 + carry)//10
result_tail.next = ListNode(out)
result_tail = result_tail.next
l1 = (l1.next if l1.next else None)
l2 = (l2.next if l2.next else None)
return result.next
解决方案
可能有一个测试用例,其中 l1 和/或 l2 的传入值为 None。如果发生这种情况,则会引发 AttributeError ,因为 None 没有任何此类属性 - 它只是 None (在其他语言中为 null)。
请注意,您通过简单地从 while 语句中的每个 l1 和 l2 中删除 .val 来解决了检查 None 的问题。这就是第二次提交成功接受的原因。
推荐阅读
- ios - 如何运行和编译 SPM 以查看结果
- python - 将元组元组转换(和反转)为字典时出错
- java - 无法在 Visual Studio 代码中使用引用的库编译 java 程序,错误:找不到符号
- javascript - 对从屏幕上填充的 api 获取的数据中的特定单词进行样式设置
- windows - Windows 上的 GCC/G++-11
- azure-rm - 如何使用二头肌将父资源名称引用到模块内的资源
- tinymce - TinyMCE:Span Tag 不能包含 a、i、br 元素。不是继续跨度,而是拆分
- tensorflow - 在 Arduino nano 上编译模型时出现 Tensorflowlite 错误
- python - Python 9x9 和 3x3 数组验证不包括 0
- laravel - Gitpod托管的laravel应用程序自动显示laravel安装页面而不显示主页