Here's my script:
def index(seq, item):
"""Returns the index of an item in an increasingly-sorted
sequence (if exists) otherwise returns the index where
it would be inserted, using binary search.
seq: a sequence.
precondition: seq is sorted increasingly.
"""
# Updates the sequence with the item using a
# set to avoid duplicates.
seq = set(seq)
seq.update([item])
# Converts the sequence to a list and re-sorts it.
sorted_seq = sorted(seq)
middle = len(sorted_seq) // 2
middle_value = sorted_seq[middle]
first_half = sorted_seq[:middle]
second_half = sorted_seq[middle:]
if item == middle_value:
return middle
elif item < middle_value:
return index(first_half, item)
elif item > middle_value:
return index(second_half, item) + len(first_half)
How can it be refactored and optimized?
Notes:
I'm a hobbyist and beginner (in programming in general, and Python in particular).
I'm new to binary search I just understand the basic idea.