【发布时间】:2022-01-08 15:12:11
【问题描述】:
我正在复习 Python 的基础知识,并且有两个函数可以使用。解决leet代码问题2的蛮力和字典方法。但是,我试图在使用类时使其工作。我试过把它变成一个大类,现在我把它分成两个类。我不确定如何打印每个函数的结果。请帮忙!
class Solution1:
def __init__(self, x, y):
self.x = x
self.y = y
# Complexity: O(n^2), very inefficient, especially as the list gets longer
def twoSum_BF(self, nums, target):
# don't want to look at the last index (i = index)
for i in range(len(nums) - 1):
# don't need to look at indices we've already seen
# -> i + 1, then go to end of nums
for j in range(i + 1, len(nums)):
if nums[i] + nums[j] == target:
return [i, j]
# dict method
class Solution2:
def __init__(self, x, y):
self.x = x
self.y = y
# Complexity is O(n)?
def twoSum_Dict(self, nums, target):
seen = {}
# enumerate gives both index and val at same time
for i, num in enumerate(nums):
# check whether dict seen contains num
# needed to add to curr to = target
# we need tar - curr
if target - num in seen:
return [seen[target - num], i]
elif num not in seen:
seen[num] = i
x = [2, 7, 11, 15]
y = 9
print("The brute force method returns: ")
BF = (Solution1(x, y))
print(BF)
print("The dictionary method returns: ")
Dict = (Solution2(x, y))
print(Dict)
【问题讨论】:
-
嗨,欢迎来到堆栈溢出!我的意思是没有冒犯,但是这里有很多小错误可以真正简洁地回答您的问题。我强烈建议您查看一些
class教程,尝试了解如何使用它们。请参阅w3schools.com/python/python_classes.asp 以获得高级概述,并阅读官方文档以了解更多关于docs.python.org/3/tutorial/classes.html 的确切情况。祝你好运:) -
你必须运行这些函数。
BF.twoSum_BF(x, y),Dict.twoSum_Dict(x, y)得到结果。如果您将x, y发送到__init__,那么在这些函数中您应该使用self.x、self.y而不获取参数nums, target
标签: python python-3.x python-class