Created
February 13, 2013 11:39
-
-
Save nafu/4944047 to your computer and use it in GitHub Desktop.
Bisection Search
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
x = 1234567 | |
epsilon = 0.01 | |
numGuesses = 0 | |
low = 0.0 | |
high = x | |
ans = (high + low)/2.0 | |
while abs(ans**2 - x) >= epsilon: | |
print('low = ' + str(low) + ' high = ' + str(high) + ' ans = ' + str(ans)) | |
numGuesses += 1 | |
if ans**2 < x: | |
low = ans | |
else: | |
high = ans | |
ans = (high + low)/2.0 | |
print('numGuesses = ' + str(numGuesses)) | |
print(str(ans) + ' is close to square root of ' + str(x)) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
high = 100 | |
low = 0 | |
ans = (high + low)/2 | |
x = '' | |
print('Please think of a number between 0 and 100!') | |
while x != 'c': | |
print('Is your secret number ' + str(ans) + '?') | |
x = raw_input("Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly. ") | |
if x == 'h': | |
high = ans | |
elif x == 'l': | |
low = ans | |
elif x == 'c': | |
print('Game over. Your secret number was: ' + str(ans)) | |
break | |
else: | |
print('Sorry, I did not understand your input.') | |
continue | |
ans = (high + low)/2 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment