Sorting for index values using a binary search function in python -
i being tasked designing python function returns index of given item inside given list. called binary_sort(l, item) l list(unsorted or sorted), , item item you're looking index of.
here's have far, can handle sorted lists
def binary_search(l, item, issorted=false): templist = list(l) templist.sort() if l == templist: issorted = true = 0 j = len(l)-1 if item in l: while != j + 1: m = (i + j)//2 if l[m] < item: = m + 1 else: j = m - 1 if 0 <= < len(l) , l[i] == item: return(i) else: return(none)
how can modify return index of value in unsorted list if given unsorted list , value parameters?
binary search (you misnamed - algorithm above not called "binary sort") - requires ordered sequences work.
it can't work on unordered sequence, since ordering allows throw away @ least half of items in each search step.
on other hand, since allowed use list.sorted
method, seems way go: calling l.sort()
sort target list before starting search operations, , algorithm work.
in side note, avoid in program call l
- maybe nice name list background in mathematics , used things on paper - on screen, l
hard disinguish 1
, makes poor source code reading. names case sequence
lst
, or data
. (list
should avoided well, since override python built-in same name).
Comments
Post a Comment