Home > Mobile >  cannot convert my code to oop style in python
cannot convert my code to oop style in python

Time:12-13

I have done leetcode question in procedural way. I do not if it is proper ask the same question from this platform. But I am looking for OOP podcasts, and needed some practice. Occasionally, leetcode gave me opportunity- I can solve question by top to down procedural way writing code, but leetcode needs OOP version. I will share question and my answer as procedural and try of oop. If it is not proper I will delete, no problem. question; `Given an array of integers nums which is sorted in ascending order, and an integer target, write a function to search target in nums. If target exists, then return its index. Otherwise, return -1.

You must write an algorithm with O(log n) runtime complexity.`

my response;

def f_nums(nums,target):
    for i in range(len(nums)-1):
        if nums[i]==target:
            a= i
    try:
        if a:
            return a
        else:
            return -1
    except:
        return -1

res=f_nums([-1,0,3,5,9,12],9)
print(res)

my try in oop version;

class Solution:
    def search(self, nums: List[int], target: int) -> int:
        for i in range(len(self.nums)-1):
            if self.nums[i]==self.target:
                a=i
        try:
            if a:
                return a
            else:
                return -1
        except:
            return -1

gives an error ;

`

AttributeError: 'Solution' object has no attribute 'nums'
    for i in range(len(self.nums)-1):
Line 3 in search (Solution.py)
    ret = Solution().search(param_1, param_2)
Line 37 in _driver (Solution.py)
    _driver()
Line 48 in <module> (Solution.py)

`

CodePudding user response:

You are given the references to nums and target. No need to use the self object:

class Solution:
def search(self, nums: List[int], target: int) -> int:
    a = -1
    for i in range(len(nums)-1):
        if nums[i]==target:
            a=i
    return a

This solution is just O(n) however, and it is expected to be faster than that. To understand how the binary search works look at this video for example: Binary Search Algorithm in 100 Seconds

A better solution for your problem would be:

class Solution:
def search(self, nums: List[int], target: int) -> int:
    left, right = 0, len(nums)-1
    while left <= right:
        mid = (left   right) // 2
        if nums[mid] == target:
            return mid
        elif nums[mid] < target:
            left = mid   1
        else:
            right = mid - 1
    return -1
  • Related