vicchan
vicchan

Reputation: 19

Python-search function

I want to write a search function that takes in a value x and a sorted sequence and returns the position that the value should go to by iterating through the elements of the sequence starting from the first element. The position that x should go to in the list should be the first position such that it will be less than or equal to the next element in the list.

 Example:>>> search(-5, (1, 5, 10))——0
         >>> search(3, (1, 5, 10))——1

Upvotes: 0

Views: 205

Answers (2)

Peter
Peter

Reputation: 3495

Building a list of every item would be a bit of a waste of resources if there were big gaps in the list, instead you can just iterate through each list item until the input is bigger than the value.

In terms of your code -

def search(input,inputList):
    for i in range( len( inputList ) ):
        if inputList[i]>input:
            return i
    return len( inputList )

print search(-5, (1, 5, 10))
#Result: 0
print search(3, (1, 5, 10))
#Result: 1

To insert it into the list, this would work, I split the list in 2 based on the index and add the value in the middle.

def insert(input,inputList):
    index = search(input,inputList)                    #Get where the value should be inserted
    newInput = [input]+list(inputList[index:])         #Add the end of the list to the input
    if index:
        newInput = list(inputList[:index])+newInput    #Add the start of the list if the 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)

Upvotes: 2

user2977715
user2977715

Reputation: 15

since someone has answered a similar question, I will just draw a rough skeleton of what u may want to do.

declare a list and populate it with your stuff; mylist = [1, 2, 3, 5, 5, 6, 7]

then just make a function and iterate the list;

def my_func( x, mylist):
    for i in mylist:
        if((mylist[i] == x)|| (mylist[i] > x)):
            return i

Given 3 in list (1, 2, 3, 4, 5), the function should return index 2. Given 3 in list (1, 2, 4, 5, 6), it should still return 2

You may want to check my python code, because I have not checked this for errors, I am assuming you know some python and if you have the skeleton, you should crack it. And Oh, python cares about the tabbibg I did.

Upvotes: 1

Related Questions