Bisection search w Python'ie

0

Witam, skleciłem taki kod do bisection search w pythonie

l=0;
h=100;
guess=50;

ans=raw_input('Input a number from <0-100>');
print('Is your secret number ' + str(guess) + '? ')
ans=raw_input('Input h if number is too high, l if too low and c if correct');

while ans!="c":
    if ans =="h":
        guess=(guess+l)/2
        print('Is your secret number  ' + str(guess) + '? ')
        ans=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. ')
    elif ans=="l":
        guess=(guess+h)/2
        print('Is your secret number  ' + str(guess) + '? ')
        ans=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. ')
    elif not(ans in["l","h"]):
        print('Sorry, I did not understand your input.')
        print('Is your secret number  ' + str(guess) + '? ')
        ans=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.')
    
print "Game over. Your secret number was: "+str(guess)

Program wpada w nieskonczoną pętle, jak to naprawić? Jest to taka zgadywanka, user wpisuje liczbe i program ma zadanie zgadnąć.

0

o_O
Kod jest błędny bo u ciebie zmienne h oraz l są stałe, a powinny się zmniejszać za każdym "zawężeniem" przedziału. Wtedy jak h==l to koniec gry.
Pomyśl! Jeśli szukamy liczby 13 to

  • komputer zgaduje 50 i dostaje info że za dużo to teraz przedzial szukania to juz tylko <0,50> bo powyżej nie ma co szukać
  • komputer zgaduje 25 i dostaje info że za dużo to teraz przedzial szukania to juz tylko <0,25> bo powyżej nie ma co szukać
  • komputer zgaduje 12 i dostaje info że za mało to teraz przedzial szukania to juz tylko <12,25>
    itd
    a u ciebie cały czas masz h=100 i l=0
0

Zrobiłem prościej, bo faktycznie jak tamto w głowie liczyłem sobie potem to aż się za nią złapałem :D

Może się komuś przyda

print('Think of a number between 0 and 100!')

hi=100
lo=0

guessed=False

while not guessed:
    guess=(hi + lo)/2
    print('Is  your number '+str(guess)+'?')
    ans=raw_input('H if too high,L if too low and C if correct')

    if ans=='h':
        hi=guess
    elif ans=='l':
        lo=guess
    elif ans=='c':
        guessed=True
        print('This is your number '+str(guess)+'.')

1 użytkowników online, w tym zalogowanych: 0, gości: 1