add some exs

This commit is contained in:
Mia von Steinkirch 2019-05-12 21:23:24 -07:00
parent 0d5e21b867
commit 9b4c8df7f7
7 changed files with 85 additions and 1 deletions

View File

@ -1 +0,0 @@
#!/usr/bin/env python

View File

@ -0,0 +1,48 @@
#!/usr/bin/env python
def binary_search(array, value):
last, first = len(array), 0
while first < last:
mid = (last - first)//2
item = array[mid]
if item == value:
return True
elif item < value:
last = mid
else:
first = mid
return False
def binary_search_rec(array, value, first=0, last=None):
last = last or len(array)
if len(array[first:last]) < 1:
return False
mid = (last - first)//2
if array[mid] == value:
return True
elif array[mid] < value:
return binary_search_rec(array, value, first=first, last=mid)
else:
return binary_search_rec(array, value, first=mid, last=last)
array = [3, 4, 6, 7, 10, 11, 34, 67, 84]
value = 6
assert(binary_search(array, value) == True)
assert(binary_search_rec(array, value) == True)
value = 8
assert(binary_search(array, value) == False)
assert(binary_search_rec(array, value) == False)
array = [8]
assert(binary_search(array, value) == True)
assert(binary_search_rec(array, value) == True)
array = []
assert(binary_search(array, value) == False)
assert(binary_search_rec(array, value) == False)

View File

@ -0,0 +1,37 @@
#!/usr/bin/env python
def merge_sort(list_to_sort):
# Base case: lists with fewer than 2 elements are sorted
if len(list_to_sort) < 2:
return list_to_sort
# Step 1: divide the list in half
mid_index = len(list_to_sort) / 2
left = list_to_sort[:mid_index]
right = list_to_sort[mid_index:]
# Step 2: sort each half
sorted_left = merge_sort(left)
sorted_right = merge_sort(right)
# Step 3: merge the sorted halves
sorted_list = []
current_index_left = 0
current_index_right = 0
while len(sorted_list) < len(left) + len(right):
if ((current_index_left < len(left)) and
(current_index_right == len(right) or
sorted_left[current_index_left] < sorted_right[current_index_right])):
sorted_list.append(sorted_left[current_index_left])
current_index_left += 1
else:
sorted_list.append(sorted_right[current_index_right])
current_index_right += 1
return sorted_list
list_to_sort = [5, 3, 7, 12, 1, 0, 10]
print merge_sort(list_to_sort)