2013-10-24 4 views
2

Итак, я некоторое время работаю над этой проблемой угадывания игры, и я остаюсь царапать свой мозг в течение последних 2 часов, пытаясь понять, что не так, но я не могу. Я также попытался найти решение, но я не хочу делать копию &, и я действительно хочу решить мой код.Python-Застрял в программе угадывания игры?

Вот что я был в состоянии получить до сих пор:

start = 0 
end = 100 
print 'Please think of a number between 0 and 100!' 
user = '' 
ans = (start + end)/2 

while user != 'c': 
    print ('Is your secret number ' + str((start + end)/2) + '?') 
    user = 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 user == 'l': 
     start = ans 
    elif user == 'h': 
     end = end - ans 
    ans = start 
print 'Game over. Your secret number was: ' + str((start + end)/2) 

Что я делаю неправильно? Edit: Игра должна запустить что-то вроде этого:

Please think of a number between 0 and 100! 
Is your secret number 50? 
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. l 
Is your secret number 75? 
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. l 
Is your secret number 87? 
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. h 
Is your secret number 81? 
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. l 
Is your secret number 84? 
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. h 
Is your secret number 82? 
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. l 
Is your secret number 83? 
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. c 
Game over. Your secret number was: 83 
+2

И какая проблема у вас с кодом? Что происходит, когда вы запускаете его? для какого-то ввода, какой результат вы ожидаете, и какой результат вы на самом деле получаете? –

+0

тоже, похоже, это в формате python 2, почему вы не используете python3? – Monacraft

+0

Я беру курс Edx на Intro для CS и программирования, и они используют Python 2.x, вот почему. Но для моих собственных проектов я всегда использую Py 3.x. :) –

ответ

1

Вы настройки ans = start, то будет ошибка. Поскольку вы хотите решить это самостоятельно, я больше не буду объяснять вещи. Вот почему ваша программа никогда не уменьшается ниже 25:

Please think of a number between 0 and 100! 
Is your secret number 50? 
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. h 
Is your secret number 25? 
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. h 
Is your secret number 25? 
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. h 
Is your secret number 25? 
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. h 
Is your secret number 25? 
0

Я вижу две проблемы с вашим текущим кодом. Прежде всего, вы никогда не меняете ans внутри цикла. Вероятно, вы хотите, чтобы ans содержал номер, который является текущим. Поэтому вы должны устанавливать его, когда вы делаете предположение, и использовать его непосредственно в выводе. Поэтому переместите строку ans = (start + end)/2 в начале цикла.

Вторая проблема заключается в том, что вы установили end = end - ans, когда предположение было слишком высоким. Хотя это работает в большинстве случаев, когда вы используете бинарный поиск и всегда угадываете половинки, это не совсем то, что вы хотите сделать. Если вы хотите выполнить поиск в диапазоне [start, end], тогда вы должны установить end на самый высокий номер, который по-прежнему доступен для угадывания; это будет ans - 1, когда вы догадались слишком высоко.

И, наконец, вы, вероятно, захотите поймать ситуацию, когда start == end. В этом случае либо вы нашли номер, либо пользователь ввел некоторые неправильные вещи.

Также, как правило, распечатка промежуточных результатов может очень помочь при отладке. Например, вы можете поместить print(start, end) в верхней части цикла, чтобы увидеть диапазон, на который вы смотрите во время каждой догадки. Тогда вы бы легко заметили, что начало диапазона никогда не менялось.

0

Мое решение работает:

import random 
numH = 100 
numL = 0 
num = random.randint(numL, numH) 
print num 

x = raw_input('Enter high, low or number 1: ') 
while x == 'l' or x == 'h': 
    if x == 'l': 
     numH = num - 1 
     num = random.randint(numL, numH) 
     print num 
     x = raw_input('Enter high, low or number 2: ') 
    if x == 'h': 
     numL = num + 1 
     num = random.randint(numL, numH) 
     print num 
     x = raw_input('Enter high, low or number 2: ') 
    else: 
     print 'your number is ', num 
Смежные вопросы