110k views
3 votes
Modify the guessing-game program so that the user thinks of a number that the computer must guess.

The computer must make no more than the minimum number of guesses, and it must prevent the user from cheating by entering misleading hints.


Use I'm out of guesses, and you cheated and Hooray, I've got it in X tries as your final output.


(Hint: Use the math.log function to compute the minimum number of guesses needed after the lower and upper bounds are entered.)

User Koviroli
by
4.5k points

1 Answer

3 votes

Answer:

import random

import math

smaller = int(input("Enter the smaller number: "))

larger = int(input("Enter the larger number: "))

count = 0

print()

while True:

count += 1

myNumber = (smaller + larger) // 2

print('%d %d' % (smaller, larger))

print('Your number is %d' % myNumber)

choice = input('Enter =, <, or >: ')

if choice == '=':

print("Hooray, I've got it in %d tries" % count)

break

elif smaller == larger:

print("I'm out of guesses, and you cheated")

break

elif choice == '<':

larger = myNumber - 1

else:

smaller = myNumber + 1

Step-by-step explanation:

The code to be Modified is as indicated below:

# Modify the code below:

import random

smaller = int(input("Enter the smaller number: "))

larger = int(input("Enter the larger number: "))

myNumber = random.randint(smaller, larger)

count = 0

while True:

count += 1

userNumber = int(input("Enter your guess: "))

if userNumber < myNumber:

print("Too small")

elif userNumber > myNumber:

print("Too large")

else:

print("You've got it in", count, "tries!")

break

Detailed Explanation:

Line 3 and 4 of the codes prompts the user to enter a smaller and larger number. Line 5 we initiate the formula for minimum number of guesses. Line 14 and 17 prints out the output I'm out of guesses, and you cheated and Hooray, I've got it in X after validating the conditions.

User Gidim
by
4.6k points