Python-search function -
i want write search function takes in value x , sorted sequence , returns position value should go iterating through elements of sequence starting first element. position x should go in list should first position such less or equal next element in list.
example:>>> search(-5, (1, 5, 10))——0 >>> search(3, (1, 5, 10))——1
building list of every item bit of waste of resources if there big gaps in list, instead can iterate through each list item until input bigger value.
in terms of code -
def search(input,inputlist): in range( len( inputlist ) ): if inputlist[i]>input: return return len( inputlist ) print search(-5, (1, 5, 10)) #result: 0 print search(3, (1, 5, 10)) #result: 1
to insert list, work, split list in 2 based on index , add value in middle.
def insert(input,inputlist): index = search(input,inputlist) #get value should inserted newinput = [input]+list(inputlist[index:]) #add end of list input if index: newinput = list(inputlist[:index])+newinput #add start of list if index isn't 0 return newinput print insert(-5, (1, 5, 10)) #result: (-5, 1, 5, 10) print insert(3, (1, 5, 10)) #result: (1, 3, 5, 10)
Comments
Post a Comment