0

I am doing a problem in leetcode where I am supposed to return the index of the specific target, here's the code:

class Solution:
    def searchInsert(self, nums: List[int], target: int) -> int:
        l=len(nums)
        for i in range(0,l):
            if(nums[i]==target):
                print(i)

The error I get:

TypeError: None is not valid value for the expected return type integer
    raise TypeError(str(ret) + " is not valid value for the expected return type integer");

I was expecting the index to return

maciek97x
  • 2,251
  • 2
  • 10
  • 21

3 Answers3

1

You don't return a value, you print it.

print(i) should be return i

tim the fiend
  • 179
  • 1
  • 1
  • 9
1

You need to return the index instead of printing it.

class Solution:
    def searchInsert(self, nums: List[int], target: int) -> int:
        l=len(nums)
        for i in range(0,l):
            if(nums[i]==target):
                return i
  • you should add some logic for the case that `target` is not found. In that case, the function would still return None – FlyingTeller Aug 21 '23 at 07:07
  • @FlyingTeller I am not giving accurate solutions for the problems. It may be possible that the problem statement states `the target value will be always available in the list.` – Roslin Mahmud Joy Aug 21 '23 at 07:11
0
  class Solution:
       def searchInsert(self, nums: List[int], target: int) -> Optional[int]:
           l=len(nums)
           for i in range(0,l):
               if(nums[i]==target):
                   return i

If no return in your function, None will be returned as default, and in your code, just print(i) couldn't break the for loop. Follow the comment, the searchInsert will return None if could find the index.

Kaison L
  • 86
  • 5