Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
186 views
in Technique[技术] by (71.8m points)

python - Searching for a range

I have a list of integers in ascending order and a target value. And I would like to return the index of the first and last of the target value. Here is my code:

nums = [3,4,5,5,5,6,7,8,9]
target = 5

class Solution:
    def searchRange(self,nums, target):

        for i in range(len(nums)):
            if nums[i] == target:
                left_index = i
                break

            else:
                return [-1,-1]


        for j in range(len(nums)-1,-1,-1):
            if nums[j] == target:
                right_index = j
                break

        return [left_index,right_index]

x = Solution()
print(x.searchRange(nums,5))

The output that I am getting is [-1,-1], i.e. the target is not in the list. However 5 is clearly in the list and the desired output should be [2,4]. ANY HELP WOULD BE GREAT!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Look at the first for-loop:

for i in range(len(nums)):
    if nums[i] == target:
        left_index = i
        break
    else:
        return [-1,-1]  

When it's executing the for-loop for the first time, nums[i] has a value of 3. 3 is not equal to 5 (your target), so it will execute the else statement and directly return [-1, -1].

If you now unindent the else statement by one level, it will only be executed AFTER the for-loop has iterated over all numbers [reference]. If your target value is found, the break keyword will prevent the else statement from getting executed.

So, the following would work:

for i in range(len(nums)):
    if nums[i] == target:
        left_index = i
        break
else:
    return [-1,-1]

Do NOT remove the else part, or you would get a NameError for left_index and right_index if your target is not found in the numbers!

Add an else statement to the second for loop, too (to avoid a NameError for right_index when target is not found a second time in nums):

nums = [3,4,5,5,5,6,7,8,9]
target = 5

class Solution:
    def searchRange(self, nums, target):
        for i in range(len(nums)):
            if nums[i] == target:
                left_index = i
                break
        else:
            return [-1, -1]

        for j in range(len(nums)-1, -1, -1):
            if nums[j] == target:
                right_index = j
                break
        else:
            return [left_index, -1]

        return [left_index, right_index]

x = Solution()
print(x.searchRange(nums, target))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...