Why is an empty list passed to the binary_search function? After all, it’s not really empty.
from typing import List
def binary_search(nums: List[int], item: int):
print("binary_search nums", nums)
low = 0
high = len(nums) - 1
while low <= high:
middle = (low + high) // 2
if nums[middle] == item:
return middle
if nums[middle] > item:
high = middle - 1
if nums[middle] < item:
low = middle + 1
return None
def smallest_find(nums: List[int]):
smallest = nums[0]
smallest_index = 0
for i in range(1, len(nums)):
if nums[i] < smallest:
smallest = nums[i]
smallest_index = i
return smallest_index
def selection_sort(nums: List[int]):
sorted_nums = []
for _ in range(len(nums)):
smallest_index = smallest_find(nums)
sorted_nums.append(nums.pop(smallest_index))
return sorted_nums
import random
while True:
nums = [random.randint(-100, 100) for _ in range(20)]
item = 24
if item in nums:
print(nums)
print(selection_sort(nums))
print(binary_search(selection_sort(nums), item))
break
Result:
[20, 84, -65, -76, -46, -7, 19, 48, -55, 31, 62, -86, 16, 24, 67, -87, -65, -57, 12, 61]
[-87, -86, -76, -65, -65, -57, -55, -46, -7, 12, 16, 19, 20, 24, 31, 48, 61, 62, 67, 84]
binary_search nums []
None
Why is an empty list passed to the binary_search function? After all, it’s not really empty.
Python 3.8.10
>Solution :
Your second call to selection_sort actually returns an empty list, that is why binary_search is getting an empty list.
The reason is this line:
sorted_nums.append(nums.pop(smallest_index))
You are pop-ing all values from nums in your selection_sort routine. This is emptying out (and overwriting) input list nums
You can avoid this by making a shallow copy of nums:
from typing import List
def binary_search(nums: List[int], item: int):
print("binary_search nums", nums)
low = 0
high = len(nums) - 1
while low <= high:
middle = (low + high) // 2
if nums[middle] == item:
return middle
if nums[middle] > item:
high = middle - 1
if nums[middle] < item:
low = middle + 1
return None
def smallest_find(nums: List[int]):
smallest = nums[0]
smallest_index = 0
for i in range(1, len(nums)):
if nums[i] < smallest:
smallest = nums[i]
smallest_index = i
return smallest_index
def selection_sort(nums: List[int]):
sorted_nums = []
nums_ = nums[:] # shallow copy
for _ in range(len(nums_)):
smallest_index = smallest_find(nums_)
sorted_nums.append(nums_.pop(smallest_index))
return sorted_nums
import random
while True:
nums = [random.randint(-100, 100) for _ in range(20)]
item = 24
if item in nums:
print(nums)
print(selection_sort(nums))
print(binary_search(selection_sort(nums), item))
break
Output:
[41, -59, 38, -50, 25, -62, 58, -81, 7, 24, -93, 41, 92, 3, 65, -61, 47, -54, 72, 65]
[-93, -81, -62, -61, -59, -54, -50, 3, 7, 24, 25, 38, 41, 41, 47, 58, 65, 65, 72, 92]
binary_search nums [-93, -81, -62, -61, -59, -54, -50, 3, 7, 24, 25, 38, 41, 41, 47, 58, 65, 65, 72, 92]
9