DEV Community

Nw3965
Nw3965

Posted on

Binary Search

Binary Search

The code I wrote.

class Solution:
    def search(self, nums: List[int], target: int) -> int:
        result = count(nums)
        return  result
Enter fullscreen mode Exit fullscreen mode

Checked by AI.


class Solution:
    def search(self, nums: List[int], target: int) -> int:
        result = nums.count(target)
        return result
Enter fullscreen mode Exit fullscreen mode

I realized that I should write like this.
result = nums.count(target)

I could not pass the coding test so I asked AI again to check.

class Solution:
    def search(self, nums: List[int], target: int) -> int:
        try:
            result = nums.index(target)
            return result
        except ValueError:
            return -1
Enter fullscreen mode Exit fullscreen mode

I needed exception.

except ValueError:
return -1

Question;User
what is the difference between nums.index(target) and nums.count(target)

Answer from ChatGPT

Let's use the list [-1, 0, 3, 5, 9, 12] and demonstrate the use of both nums.index(target) and nums.count(target) with this specific list:

nums = [-1, 0, 3, 5, 9, 12]
target = 9

# Using nums.index(target)
try:
    index = nums.index(target)
    print(f"The target {target} is at index {index}.")
except ValueError:
    print(f"The target {target} is not in the list.")

# Using nums.count(target)
count = nums.count(target)
print(f"The target {target} appears {count} times in the list.")

Enter fullscreen mode Exit fullscreen mode

Output:

perl

The target 9 is at index 4.
The target 9 appears 1 times in the list.
Enter fullscreen mode Exit fullscreen mode

In this example, nums.index(target) returns the index of the first occurrence of 9, which is 4. nums.count(target) returns the number of occurrences of 9, which is 1. Both methods are used to gather information about the presence and location of the target value in the list.

So I should use "index" to count index number for this test.

nums.count(target) returns the number of occurrences of 9,

I could not write this "Try Except" so I need to practice this also.
Python Try Except

Top comments (0)