Question
[Computer Science / Python Algorithm Question] Python Algorithm I did code myself but I think my code is incorrect. Could you please fix my code?(The
[Computer Science / Python Algorithm Question]
Python Algorithm I did code myself but I think my code is incorrect. Could you please fix my code?(The ouput(answer) is already provided at the bottom) Please read and follow the problem(requirement) below, If you need more information, pleas let me know. Thanks!
- Problem:
- If the target is not in the array, we return the index where we should insert the target to keep the array sorted
- here we should return the index of the first item in the array that equals the target
- for example, if arr = [2, 3, 3, 4] and target = 3, we should return 1 (the index of the first 3 in arr) rather than 2 (the index of the second 3)
- find the solution with the complexity below
- Complexity:
- O(n) time
- O(1) space
======================================================================================================
# Implementation def exr_1(arr, target): """ Find a target in a sortetd array (in ascending order) Parameters ---------- arr : a list of integers target : an integer Returns ---------- The index of the first item in arr that equals the target, if the target is in the array The index where the target should be inserted (so that the array is still sorted in ascending order), otherwise """ # The starting and ending point of the input array left, right = 0, len(arr) - 1 # While the subarray is not empty while (left <= right): # Get the index of the middle item in the subarray mid = left + (right - left) // 2 # If the middle item equals the target if arr[mid] == target: return mid # If the middle item is larger than the target elif arr[mid] > target: right = mid - 1 # If the middle item is smaller than the target else: left = mid + 1 return left
===================================================================================================
The output should look like this.
# Test arr_1 = [2] arr_2 = [4] arr_3 = [2, 3, 4] arr_4 = [2, 3, 3, 4] arr_5 = [2, 2, 3, 3, 3, 4, 4] arr_6 = [3, 3]
print(exr_1(arr_1, 3)) print(exr_1(arr_2, 3)) print(exr_1(arr_3, 3)) print(exr_1(arr_4, 3)) print(exr_1(arr_5, 3)) print(exr_1(arr_6, 3))
1 0 1 1 2 0
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started