This question already has answers here:
Guessing algorithm does not seem to work, guessing number by Python
(3 answers)
Closed 5 years ago.
The program is supposed to take in an integer from the user and guess what that integer is using binary search.
user_num = (int(input("Please think of a number between 0 and 100! ")))
low = 0
high = 100
ans = (high + low)//2
while True:
print("is your secret number " + str(ans))
check_ans = input("""enter 'h' to indicate if the guess is too high.
enter 'l' to indicate if the guess is too low.
enter 'c' if I guessed correctly.""")
if check_ans == 'h':
high = ans//2
ans = high
elif check_ans == 'l':
low = ans*2
ans = low
elif check_ans == 'c' and check_ans == user_num:
print("Game over. Your secret number was: " + str(ans))
break
else:
print("I do not understand your command")
I believe the issue I am having is occurring in the while loop. I need the program to know when to stop once it reaches the threshold. Say if my integer is 34, once I hit 'h' as input it will drop to 25. Now if I hit 'l' it's going to jump back to being 50.
I guess my question is how do I update the ans variable so the program knows to stay within that range?
Let's go over your conditions. What we want to do is redefine low and high based on the answer the program received.
if check_ans == 'h':
# We know that ans is lower, so we set our higher bound to slightly below ans
high = ans - 1
elif check_ans == 'l':
# We know that ans is higher, so we set our lower bound to slightly above ans
low = ans + 1
Then at the beggining of your loop you want to get ans based on the interval by doing ans = (high + low)//2.
Overall this gives
user_num = (int(input("Please think of a number between 0 and 100! ")))
low = 0
high = 100
while True:
ans = (high + low)//2
print("is your secret number " + str(ans))
check_ans = input("""
enter 'h' to indicate if the guess is too high.
enter 'l' to indicate if the guess is too low.
enter 'c' if I guessed correctly.""")
if check_ans == 'h':
high = ans - 1
elif check_ans == 'l':
low = ans + 1
elif check_ans == 'c' and check_ans == user_num:
print("Game over. Your secret number was: " + str(ans))
break
else:
print("I do not understand your command")
The algorithm is slightly wrong when calculating the new interval. Here is the corrected code:
user_num = (int(input("Please think of a number between 0 and 100! ")))
low = 0
high = 100
ans = (high + low) // 2
while True:
print("is your secret number " + str(ans))
check_ans = input("""enter 'h' to indicate if the guess is too high.
enter 'l' to indicate if the guess is too low.
enter 'c' if I guessed correctly.""")
if check_ans == 'h':
high = ans
ans = (high + low) // 2
elif check_ans == 'l':
low = ans
ans = (high + low) // 2
elif check_ans == 'c' and check_ans == user_num:
print("Game over. Your secret number was: " + str(ans))
break
else:
print("I do not understand your command")
Related
So , the compiler returns a syntax error for my if loop in this code, I am very new to Python any & all help will greatly be appreciated.
enter code lower_number = int(input('Enter the lower number'))
higher_number = int(input('Enter the higher number'))
r = random.randint(higher_number,last_number)
print("you have got only ", round(math.log(upper - lower + 1, 2)) ," chances")
count = 0
while count < math.log(upper - lower + 1, 2) :
count = count + 1
guess = int(input("Type your guess here")
#the next line is the line that returns the error
if r == guess :
print("wow you genius")
break;
elif guess < x :
print("not high enough")
elif guess > x :
print("too high ")
if count > math.log(upper - lower + 1, 2):
print("sorry, try next time")
As #Gulzar correctly suggested, you have several indentation errors and your code is not complete, so it's difficult for us to reproduce your use case.
Nevertheless this might help you:
count = 0
while count < math.log(upper - lower + 1, 2) :
count = count + 1
guess = int(input("Type your guess here"))
#the next line is the line that returns the error
if r == guess :
print("wow you genius")
break
elif guess < x :
print("not high enough")
elif guess > x :
print("too high ")
if count > math.log(upper - lower + 1, 2):
print("sorry, try next time")
The problems in your while loop were:
indentation (pay attention, it is fundamental in python)
a missing parenthesis in the line guess = int(input("Type your guess here"))
I'm new to Python. I'm trying to write a small game that asks the end user to pick a number from 1 to 1000 and keep it in their head (the number is not provided to the program). The program should be able to find the number within 10 guesses. As I typically do, I went down the wrong path. My program works most of the time, but there are occasions where it does not find the number in under 10 guesses. Here is my code:
# script to guess a user's number between 1 and 1000 within 10 guesses
# import random so we can use it to generate random numbers
from random import randint
# Variables
lowerBound = 1
upperBound = 1000
numGuesses = 1
myGuess = 500
failed = False
# Welcome Message
print("#####################################################################################################"
"\n# #"
"\n# Please think of a number between 1 and 1000. I will attempt to guess the number in 10 tries. #"
"\n# #"
"\n#####################################################################################################")
while numGuesses <= 10:
# if the lower and upper bounds match we've found the number
if lowerBound == upperBound:
print(f"\nYour number is {str(lowerBound)}. It took me '{str(numGuesses)} guesses!")
break
print(f"\nIs the number {str(myGuess)}? If correct, type CORRECT. If low, type LOW. If high, type HIGH.")
# uncomment for var output
# print(f"\nGuesses = {str(numGuesses)}\nLower bound = {str(lowerBound)}\nUpper bound = {str(upperBound)}")
userFeedback = input("\nResponse: ").upper()
if userFeedback == 'HIGH':
print(f"\nGuess #{str(numGuesses)} was too high")
if numGuesses == 10:
failed = True
break
upperBound = myGuess - 1
myGuess = randint(lowerBound, upperBound)
elif userFeedback == 'LOW':
print(f"\nGuess #{str(numGuesses)} was too low")
if numGuesses == 10:
failed = True
break
lowerBound = myGuess + 1
myGuess = randint(lowerBound, upperBound)
elif userFeedback == 'CORRECT':
print(f"\nYour number is {str(myGuess)}! It took me {str(numGuesses)} guesses!")
break
numGuesses += 1
if failed:
print(f"\nMy final guess of {str(myGuess)} was not correct. I wasn't able to guess your number in 10 tries.")
It seems clear (now) that the way I'm whittling down the numbers is not going to work. I had originally thought to ask if it was 500 and, if lower, ask if it was 250. If lower again, ask if it was 125, and so on. If higher, ask if it was 750, 875 and so on. Is that the correct approach here?
I've been thinking about this too long and I believe I've cooked my brain. Thanks!
myGuess = int(math.ceil((myGuess) / 2))
is not correct.
If you have narrowed down the range to between 6 and 8 and you were guessing 7, your previous code would call 4 instead which is outside your search range.
if userFeedback == 'HIGH':
print(f"\nGuess #{numGuesses} was too high")
upperBound = myGuess - 1
elif userFeedback == 'LOW':
print(f"\nGuess #{numGuesses} was too low")
lowerBound = myGuess + 1
myGuess = int(lowerBound + ((upperBound - lowerBound) / 2))
I've updated my code and I think I have it. Thanks for the tips.
# script to guess a number between 1 and 1000 within 10 guesses
# Variables
lowerBound = 1
upperBound = 1000
numGuesses = 1
myGuess = 500
# Welcome Message
print("#####################################################################################################"
"\n# #"
"\n# Please think of a number between 1 and 1000. I will attempt to guess the number in 10 tries. #"
"\n# #"
"\n#####################################################################################################")
while numGuesses <= 10:
# uncomment next line for var output
# print(f"\nGuesses = {numGuesses}\nLower bound = {lowerBound}\nUpper bound = {upperBound}")
print(f"\nIs the number {myGuess}? If correct, type CORRECT. If low, type LOW. If high, type HIGH.")
userFeedback = input("\nResponse: ").upper()
if userFeedback == 'HIGH':
print(f"\nGuess #{numGuesses} was too high")
upperBound = myGuess
myGuess = (lowerBound + myGuess) // 2
elif userFeedback == 'LOW':
print(f"\nGuess #{numGuesses} was too low")
lowerBound = myGuess
myGuess = (upperBound + myGuess + 1) // 2
elif userFeedback == 'CORRECT':
print(f"\nYour number is {myGuess}! It took me {numGuesses} guesses!")
break
numGuesses += 1
I want to write a python game that knows the number(1-100) taken from a user in 7 steps at most.
2^7>100.
The code below is working but it takes more than 7 steps. I think the problem is guess=guess+-guess//(2^n) part. But I dont know what to replace with.
number=int(input("Enter a number between 1 and 100: "))
guess=50
n=1
if number>100:
number=int(input("Enter a number less than 100: "))
if number<1:
number=int(input("Enter a number greater than 1: "))
while True:
print("Your number is" +' '+ str(guess) +' '+ "?")
ans=str(input("(g)reater,(l)ess or (b)ravo: "))
for n in range(1,10,1):
if ans=="g":
guess=guess+guess//(2^n)
elif ans=="l":
guess=guess-guess//(2^n)
elif ans=="b":
print("Your number is " +' '+ str(guess) +' '+ "Well done for me")
break
You need to keep track of your lowest and highest possible numbers and then make guess that lies halfway between them. Update the lowest and highest numbers based on reply.
number=int(input("Enter a number between 1 and 100: "))
guess = 50
n = 1
if number>100:
number=int(input("Enter a number less than 100: "))
if number<1:
number=int(input("Enter a number greater than 1: "))
lo = 1
hi = 100
while True:
print("Your number is" +' '+ str(guess) +' '+ "?")
ans = str(input("(g)reater,(l)ess or (b)ravo: "))
if ans == "g":
lo = guess
guess=lo + (hi-lo+1)//2
elif ans == "l":
hi = guess
guess=lo + (hi-lo)//2
elif ans == "b":
print("Your number is " +' '+ str(guess) +' '+ "Well done for me")
break
n += 1
I'm trying to create a scoring system for the previous quiz game i asked about.
score = 0
if guess == song_name:
print("2 points")
score = score + 2
elif
print("1 point")
score = score + 1
else:
guess != song_name
print("0 points")
score = score + 0
I want the player too be given 2 points when they get the answer right first time, 1 point when they get it right second attempt and 0 points if they don't get it right the second time.
You need a loop for taking answer and attempt counter.
score = 0
attempt = 0
guess = ""
while guess != song_name:
attempt += 1
print("Enter answer")
guess = input()
if attempt == 1:
print("2 points")
score = score + 2
elif attempt == 2:
print("1 point")
score = score + 1
else:
guess != song_name
print("0 points")
This is my code for a game in which the computer must guess a user defined number within a given range. This is a challenge from a beginners course/ book.
I'd like to draw your attention to the 'computerGuess()' function. I think there must be a more eloquent way to achieve the same result? What I have looks to me like a botch job!
The purpose of the function is to return the middle item in the list (hence middle number in the range of numbers which the computer chooses from). The 0.5 in the 'index' variable equation I added because otherwise the conversion from float-int occurs, the number would round down.
Thanks.
Code:
# Computer Number Guesser
# By Dave
# The user must pick a number (1-100) and the computer attempts to guess
# it in as few attempts as possible
print("Welcome to the guessing game, where I, the computer, must guess your\
number!\n")
print("You must select a number between 1 and 100.")
number = 0
while number not in range(1, 101):
number = int(input("\nChoose your number: "))
computerNumber = 0
computerGuesses = 0
higherOrLower = ""
lowerNumber = 1
higherNumber = 101
def computerGuess(lowerNumber, higherNumber):
numberList = []
for i in range(lowerNumber, higherNumber):
numberList.append(i)
index = int((len(numberList)/2 + 0.5) -1)
middleValue = numberList[index]
return middleValue
while higherOrLower != "c":
if computerGuesses == 0:
computerNumber = computerGuess(lowerNumber, higherNumber)
elif higherOrLower == "l":
higherNumber = computerNumber
computerNumber = computerGuess(lowerNumber, higherNumber)
elif higherOrLower == "h":
lowerNumber = computerNumber + 1
computerNumber = computerGuess(lowerNumber, higherNumber)
print("\nThankyou. My guess is {}.".format(computerNumber))
computerGuesses += 1
higherOrLower = input("\nHow did I do? If this is correct, enter\
'c'. If your number is higher, enter 'h'. If it is lower, enter 'l': ")
print("\nHaha! I got it in {} attempt(s)! How great am I?".format\
(computerGuesses))
input("\n\nPress the enter key to exit.")
Like this ?
import math
def computerGuess(lowerNumber, higherNumber):
return int((lowerNumber+higherNumber)/2)