Leecode

Leecode,第1张

Python中函数调用问题

当我在leecode上写完代码,自己在pycharm运行的时候,发现老是出错。`

class Solution():
    def twoSum(self,nums,target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        d = {}  
        self.nums=nums
        self.target=target
        for i,num in enumerate(nums):
            if target - num in d:
                return [d[target-num],i]
            d[num] = i
B=[2,7,11,15]
A=Solution(B,9)

会报如下的错误:

发现自己好蠢啊,Solution就没有传入形参,怎么能运行成功的呢!
最后,我改了代码,有两种:

class Solution():
    def twoSum(self,nums,target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        d = {}  # 哈希表
        self.nums=nums
        self.target=target
        for i,num in enumerate(nums):
            if target - num in d:
                return [d[target-num],i]
            d[num] = i
B=[2,7,11,15]
A=Solution()
print(A.twoSum(B,9))


因为代码中写的在twoSum函数中传入参数啊,所以肯定是在twoSum中传入实参。

还有一种:

class Solution():
    def __init__(self,nums,target):
        self.nums=nums
        self.target=target
    def twoSum(self):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        d = {} 
        self.nums=self.nums
        self.target=self.target
        for i,num in enumerate(self.nums):
            if self.target - num in d:
                return [d[self.target-num],i]
            d[num] = i
B=[2,7,19,18]
A=Solution(B,20)
print(A.twoSum())


使用__init__(self,…)方法。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/919185.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-16
下一篇2022-05-16

发表评论

登录后才能评论

评论列表(0条)

    保存