fork download
  1. class Solution(object):
  2. def searchRange(self, nums, target):
  3. """
  4. :type nums: List[int]
  5. :type target: int
  6. :rtype: List[int]
  7. """
  8.  
  9. # Recursive Count (counts the number of recursive exits)
  10. RC = [0]
  11. length = len(nums) -1
  12.  
  13. def getRange(left, right, nums):
  14. if(left == right):
  15. # Base case reached
  16. return [left, right]
  17.  
  18. mid = (left + right) // 2
  19. indices = []
  20.  
  21. # Searching for the middlle target index
  22. if (nums[mid] == target):
  23. indices = getRange(mid, mid, nums)
  24. elif (nums[mid] < target):
  25. indices = getRange(mid + 1, right, nums)
  26. elif (nums[mid] > target):
  27. indices = getRange(left, mid - 1, nums)
  28.  
  29. # Ripling (as the program exits the last recursive call)
  30. if indices[0] != 0 and nums[indices[0]] - RC[0] == target:
  31. indices[0] = indices[0] - 1
  32. elif indices[1] != length and nums[indices[1]] + RC[0] == target:
  33. indices[1] = indices[1] + 1
  34.  
  35. RC[0] = RC[0] + 1
  36. return indices
  37.  
  38. return getRange(0, length, nums)
  39.  
  40. target = 8
  41. for lst in ([5,7,7,8,8,10], []):
  42. try:
  43. ans = Solution().searchRange(lst, target)
  44. print(f"Solution for {lst}, {target} is {ans}")
  45. except Exception as e:
  46. print(f"Exception for {lst}, {target}: {e}")
Success #stdin #stdout 0.03s 9680KB
stdin
Standard input is empty
stdout
Solution for [5, 7, 7, 8, 8, 10], 8 is [3, 4]
Exception for [], 8: list index out of range