So I'm creating this game where the computer guesses a number, and based on the reply, it splits and re-selects a number. I've had little problems so far, but now I'm quite stuck on the loop. I know what I have to do, I just can't figure out how to do it properly, and have it function.
lowest = int(input( "What is the lowest number you will think of?: "))
highest = int(input( "What is the highest number you will think of?: "))
print("So you're thinking of a number between",lowest,"and",highest)
x=[]
for number in range(lowest,highest):
x.append(number)
middleIndex = (len(x))//2
print ("is it "+str(x[middleIndex])+"?")
answer = input("")
if answer == "lower":
x = (x[:len(x)//2])
else:
x = (x[len(x)//2:])
I know it has to go after the
x.append(number)
but I can't get it to work using for or while loops.
The entire for loop is kind of pointless, with the x.append line especially so. range() gives you a list anyway (in Python 3 it gives you a range object which can be converted to a list using the list function).
You could replace that with:
x=list(range(lowest, highest))
Also, this is more convention than anything technically incorrect, but in Python I think camel case is generally reserved for class names; for this reason, I would rename middleIndex to middle_index.
And finally, you don't have anything for the case when the computer guesses the right number!
What you're looking for is basically an interactive binary search algorithm that runs over a range of numbers. You don't actually need to use range or a list, because you can calculate the average of your min and max values instead of finding the middle_index.
Here is an example implementation:
def main():
print("What range will your guessed number fall within?")
min = int(input("Min: "))
max = int(input("Max: "))
print("Ok; think of a number between {0} and {1}.".format(min, max))
while min <= max:
mid = (min + max) // 2
if input("Is it {0}? (Y/N) ".format(mid)) == "Y":
print("It is!? Well, that was fun.")
return
elif input("Darn. Is it higher than {0}? (Y/N) ".format(mid)) == "Y":
min = mid + 1
else:
max = mid - 1
print("Well, it looks like you were dishonest somewhere along the line.")
print("I've exhausted every possibility!")
main()
Related
I am extremely new to python and this is one of the first things I have tried. There are 3 criteria that I want this game to meet. First is to use the number 0-10 and guess the number 3 which it does correctly. Next is 0-25 when 11 is chosen. This also works correctly.
However this last part has been giving me trouble. When picking from 0-50, it should guess 1 which it does. It should also print the "I'm out of guesses" line when another input is placed as it cannot go higher than one now. What am I doing wrong here?
import random
import math
smaller = int(input("Enter the smaller number: "))
larger = int(input("Enter the larger number: "))
maxTry = math.log(larger - smaller)
count = 0
guess = int((smaller+larger)/2)
while count != maxTry:
count += 1
guess = int((smaller+larger)/2)
print("Your number is ", guess)
help = input("Enter =, <, or >: ")
if help == ">":
smaller = guess +1
elif help == "<":
larger = guess -1
elif help == "=":
print("Hooray, I've got it in", count, "tries")
break
elif count == maxTry:
print("I'm out of guesses, and you cheated")
break
Your maxTry is a log so it is not an integer, therefore it can never be equal to count.
You can either use an int for maxTry (cast it to int maxTry = int(math.log(larger - smaller))) or compute it with something different than log that will return an int.
Alternatively, your condition could be count > maxTry instead of equal. It would actually be a bit better conceptually.
Note: you should not use capital letters in variable names in python but all lowercase with _ max_try. It is only a convention though so won't affect your program directly. You can find more info on conventions in the PEP8 documentation
What i want to do with this code is roll 'n' number of dice and then find the lower quartile of it.
so far i have:
from random import randint
#Rolling the Die
numofdie = int(input("Please input the number of dice u want to roll: "))
if numofdie < 1:
print ("PLease enter 1 or more")
quit()
if numofdie > 100:
print ("PLease enter a number less than 100")
quit()
#Sum
def dicerolls():
return [randint(1,6) for _ in range(numofdie)]
print (dicerolls())
Then i used the string.sort() function to try and sort the dicerolls() but realised that it will not work as it is a function. How can i fix this and consequently be able to find the lower quartile.
Thanks
Put the result in a variable, then sort that.
rolls = dicerolls()
rolls.sort()
print(rolls)
Or use the sorted() function:
print(sorted(dicerolls())
The built-in sorted() function will return a sorted version of whatever list you give it. Since dicerolls() returns a list, you can add that list right in:
print(sorted(dicerolls()))
I am trying to create a game where i think of a number in my head. And then the computer guesses the number through me telling it if its guess is too low or high.
This is what I've come up with but i am pretty lost tbh.
maxguess = 100
minguess = 1
count = 0
print("Think of a number between {} and {}".format(minguess,maxguess))
def midpoint(maxguess, minguess) :
z = ((maxguess + minguess)/2)
def guessing(x) :
print("Is you number greater (>) , equal (=) ,or less (<) than" ,z,)
print("please answer <,=, or >! >")
x = input()
if x == (">") :
minpoint = z
count += 1
continue
elif x == ("<") :
maxpoint = z
count += 1
continue
elif x == ("=") :
print ("I have guessed it!")
count += 1
break
print("I needed {} steps!".format(count))
Purposely not a complete solution, but some hints for you:
I'd recommend avoiding the global variables like count, maxguess, and minguess. Instead, make a function that holds all these variables.
Change your midpoint function to return z instead, then call it inside your guessing function.
Your continue and break functions would need to be inside a for or while loop. Since you aren't sure how many iterations you need to guess the number, I think a while loop would make sense here
Your functions are never run. On a style point, bring all your 'main' statements down to the bottom so they're together. After the prompt to think of a number, you need to call the guessing() function. When you call it, you should pass the minguess and maxguess values to it.
I can see what you're trying to do with the if...elif statements, but they need to be in a while True: block. So should the three statements preceding them so the script repeatedly asks for new advice from you.
Either bring the content of the midpoint() function into guessing() or make it return the value of z.
You also offer the user a choice of '>1' but don't handle it - and you don't need it as far as I can tell.
You never use minpoint or maxpoint - and you dont need them. Call the midpoint function instead and pass it the appropriate values, e.g., if '>', z = midpoint(z, maxguess).
Also, you're going to spend forever trying to get it to guess as you are using floats. Make sure everything is an integer.
Finally, you should add some code to manage input that isn't expected, i.e., not '<', '>' or '='.
Good luck!
minguess=1
maxguess=100
z=50
count=0
print("Think of a number between 1 and 100")
condition = True
while condition:
z=((maxguess + minguess)//2)
print("Is your number greater (>) , equal (=) ,or less (<) than" ,z,)
print("Please answer <,=, or >! >")
x = input()
if x == (">"):
minguess=z
count += 1
elif x == ("<") :
maxguess=z
count += 1
elif x == ("=") :
print ("I have guessed it!")
count += 1
condition=False
This is my code, The computer is supposed to guess a number between 1 and 100. The computer's guesses should either decrease or increase by half of the previous guess. The third time through the loop going only higher it breaks, or if I use higher after saying lower it breaks. Both ways, it will stop adding its guesses and divide the previous guess by two, instead of adding the previous guess divided by two to the previous guess. i.e instead of 50 + (50/2) = 75 my code does 50/2 = 25. So where it breaks on higher is at 87, instead of adding half of the previous guess, which would be six, it divides 87 by 2 equaling 43. (I have now edited this question, and the code and everything should work besides where I need help. Thank you)
pcguess = 50
useranswer = 50
print("Wanna see a magic trick?")
print("Please think of a random number between 1 and 100.")
print("Now that you have written down your number")
print("I will guess it in ten guesses or less.")
a = print("My first guess is", pcguess)
tries = 0
while tries < 100000:
newguess = pcguess//2
b = input("Was that your number?")
if b == "no":
tries += 1
c = input("Is your number higher or lower than my guess?")
if c == "lower":
print("Then my next guess is:")
print(useranswer - newguess )
useranswer = pcguess - newguess
pcguess = newguess
tries += 1
elif c == "higher":
print("Then my next guess is:")
print(useranswer + newguess)
useranswer = pcguess + newguess
pcguess = newguess
tries += 1
if b == "yes":
print("I got it in", tries, "tries!")
break
You need to narrow down the possible range of numbers based on the user's "higher"/"lower" responses. So you should store the lower and upper bounds as variables, and adjust them as you get responses. Something like this:
lower = 0
upper = 100
while lower < upper:
guess = (lower+upper)//2
print("My guess is ", guess)
# Find out if the correct answer is higher or lower than this guess
if the correct answer is higher:
lower = guess + 1 # This gives a new lower bound
if the correct answer is lower:
upper = guess - 1 # This gives a new upper bound
The first thing I would change in your code is your where you increment your tries variable. In your current while loop, you are incrementing once every time you execute your while loop and then again after whichever if statement gets executed. This means that every iteration, your number of tries goes up by 2 instead of 1. So why don't you just increment tries once at the beginning of your loop instead?
Second, the reason your useranswer variable doesn't become what you expect is simply because you are updating it wrong. For example
if c == "lower":
print("Then my next guess is:")
print(useranswer - newguess )
useranswer = pcguess - newguess # WRONG
pcguess = newguess
since you are updating useranswer, it should be useranswer = useranswer + newguess or more succinctly useranswer += newguess
Do this for the other if statement as well (where your guess is higher than what the computer is guessing)
Thirdly. This is more a matter of styling but your while loop condition should be more accurate (i.e. since you are telling the user that you will guess their number in 10 tries or less, does your loop condition really need to have tries < 100000?
I've written a game where a player tries to guess a random number (see code below). Suggestions such as 'Too low...' and 'Too High...' are also provided. But what about reversing it and letting the computer guess a number that a player has selected. I have difficulty with this and I dont know why. I think I need a 'push' from someone but not the actual code as I need to attempt this myself. I would appreciate it if some would help me on this.
Here is the code(Python 3) where the player has to guess the number:
#Guess my Number - Exercise 3
#Limited to 5 guesses
import random
attempts = 1
secret_number = random.randint(1,100)
isCorrect = False
guess = int(input("Take a guess: "))
while secret_number != guess and attempts < 6:
if guess < secret_number:
print("Higher...")
elif guess > secret_number:
print("Lower...")
guess = int(input("Take a guess: "))
attempts += 1
if attempts == 6:
print("\nSorry you reached the maximum number of tries")
print("The secret number was ",secret_number)
else:
print("\nYou guessed it! The number was " ,secret_number)
print("You guessed it in ", attempts,"attempts")
input("\n\n Press the enter key to exit")
Thanks for your help.
at each iteration through your loop, you'll need a new random.randint(low,high). low and high can be figured out by collecting your computers guesses into 2 lists (low_list) and (high_list) based how the user responds when the computer tells the user it's guess. Then you get low by max(low_list)+1 and you get high by min(high_list)-1. Of course, you'll have to initialize low_list and high_list with the lowest and highest numbers allowed.
You could just keep the lowest of the "too high" guesses and the highest of the "too_low" guesses instead of the lists. It would be slightly more efficient and probably the same amount of work to code, but then you couldn't look back at the computer's guesses for fun :).
You begin with a range from the minimum allowed number to the maximum allowed number, because the unknown number could be anywhere in the range.
At each step, you need to choose a number to query, so dividing the space into two blocks; those on the wrong side of your query number will be dropped. The most efficient way to do this in the minimum number of queries is to bisect the space each time.
I suggest you restrict the game to integers, otherwise you'll end up with a lot of messing about with floating point values regarding tolerance and precision and so on.
Assuming you know the range of numbers it could be is (a,b).
Think about how you would narrow down the range. You'd start by guessing in the middle. If your guess was low, you'd guess between your last guess and the top value. If it was high you'd guess between the lowest possible value and the last guess. By iteratively narrowing the range, eventually you'd find the number.
Here's some pseudo code for this:
loop{
guess = (a+b)/2
if high:
b = guess - 1
else if low:
a = guess + 1
else:
guess = answer
}
I just did this with a different person, use a while loop and use print("<,>,="), then do an if statement. You need a max point, middlepoint and low point and to get the middle point you need to do midpoint=((highpoint=lowpoint)//2) and in the if statement you have to do change the maxpoint and lowpoint.