AndreiL
Welcome to AndreiL.
Enjoy your time.
Please log in.

Iterative Binary search (update) - Python

Go down

Iterative Binary search (update) - Python

Post by Lucaci Andrei on Wed Feb 15, 2012 2:08 am

 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
'''
Created on Feb 15, 2012

@author: sin
'''
n = int(raw_input("Insert the upper bound of the range: "))
p = int(raw_input("Insert the lower bound of the range: "))
x = int(raw_input("Insert searched number: "))
a = range(p, n)
print a
def caut(h, x):
p, q = 0, len(h) - 1
while 1:
if q < p:
print "Value outside the given range."
raw_input("Press Enter to exit...")
exit()
mid = (p + q) / 2
if mid == x:
return mid
else:
if x < h[mid]:
q = mid - 1
elif x > h[mid]:
p = mid + 1
else:
return mid

print caut(a, x)
raw_input("Press Enter to exit...")










For a quick use of the code:
Code:


'''
Created on Feb 15, 2012

@author: sin
'''
n = int(raw_input("Insert the upper bound of the range: "))
p = int(raw_input("Insert the lower bound of the range: "))
x = int(raw_input("Insert searched number: "))
a = range(p, n)
print a
def caut(h, x):
    p, q = 0, len(h) - 1
    while 1:
        if q < p:
            print "Value outside the given range."
            raw_input("Press Enter to exit...")
            exit()
        mid = (p + q) / 2
        if mid == x:
            return mid
        else:
            if x < h[mid]:
                q = mid - 1
            elif x > h[mid]:
                p = mid + 1
            else:
                return mid

print caut(a, x)
raw_input("Press Enter to exit...")
avatar
Lucaci Andrei
"Tata Lor"


Number of messages : 222
Points : 2266743
Reputation : 1007
Registration date : 2008-08-15
Age : 26
Location : Cluj-Napoca

View user profile http://www.andreil.wgz.ro

Back to top Go down

Back to top

- Similar topics

 
Permissions in this forum:
You cannot reply to topics in this forum