简体   繁体   English

添加两个数字 - Python - Leetcode - AttributeError: 'ListNode' object 没有属性 'reverse'

[英]Add two numbers - Python - Leetcode - AttributeError: 'ListNode' object has no attribute 'reverse'

I'm trying to solve this problem on [LeetCode] https://leetcode.com/problems/add-two-numbers/我正在尝试在 [LeetCode] https://leetcode.com/problems/add-two-numbers/上解决这个问题

When I copy my code into PyCharm it works correctly.当我将代码复制到 PyCharm 中时,它可以正常工作。 However when I submit it too LeetCode I receive this error:但是,当我也提交 LeetCode 时,我收到此错误:

AttributeError: 'ListNode' object has no attribute 'reverse' l1.reverse() AttributeError: 'ListNode' object 没有属性 'reverse' l1.reverse()

Can someone check if my code is incorrect, or if the issue is something to do with LeetCode's IDE?有人可以检查我的代码是否不正确,或者问题是否与 LeetCode 的 IDE 有关?

Here is my code:这是我的代码:

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution(object):
    def addTwoNumbers(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        l1.reverse()
        l2.reverse()

        s1 = [str(x) for x in l1]
        res1 = int("".join(s1))
    
        s2 = [str(x) for x in l2]
        res2 = int("".join(s2))

        ans = res1 + res2

        ans1 = [int(x) for x in str(ans)]

        ans1.reverse()
        
        return(ans1)

I adjusted the code somewhat for PyCharm, but this is the code that actually works:我为 PyCharm 稍微调整了代码,但这是实际工作的代码:

l1 = [4,5,6]
l2 = [6,2,3]

l1.reverse()
l2.reverse()

s1 = [str(x) for x in l1]
res1 = int("".join(s1))

s2 = [str(x) for x in l2]
res2 = int("".join(s2))

ans = res1 + res2

ans1 = [int(x) for x in str(ans)]

ans1.reverse()
print(ans1)

The arguments passed by Leetcode are ListNode type and not default list, so you have to write your own reverse method. Leetcode 传递的 arguments 是 ListNode 类型而不是默认列表,所以你必须编写自己的反向方法。 In pycharm your inputting arguments of type list, which has a reverse method, and thats why ur code is working on pycharm.在 pycharm 中,您输入类型列表的 arguments,它具有反向方法,这就是为什么您的代码正在处理 pycharm 的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM