Bisection search code doesnt work [closed] - python

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
Could you explain where i'm going wrong with this code? I want to do a bisection search which takes input number and repeats bisection search until it finds the same number as input and prints out various statements.
num =int( input("Please think of a number between 0 and 100!"))
maximum = num
minimum = 0
average = (minimum+maximum)/2.0
while(average<num):
print ("Is your secret number ", +average, "?")
cond = 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( cond == "h"):
maximum = minimum
minimum = 0
elif(cond == "l"):
minimum = maximum
maximum = 100
elif(cond == "c"):
print("Game over. Your secret number was: ", +average)
break

Firstly, you don't need to input a guess. You are always going to start at the mid-point of your range.
So, instead, wait for the user to think of a number, then guess.
import time
minimum = 0
maximum = 100
print("Please think of a number between {} and {}!".format(minimum, maximum))
time.sleep(3)
average = (minimum + maximum)/2.0
while(True):
print ("Is your secret number ", +average, "?")
cond = 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.")
Second problem, you need to "divide" your search space. If the guess is too high, set that guess as the maximum, if too low, set that as the minimum. No need to set the other value in either case; it stays the same.
if( cond == "h"):
maximum = average
elif(cond == "l"):
minimum = average
elif(cond == "c"):
print("Game over. Your secret number was: ", +average)
break
And lastly, you need to update average each time through the loop to generate a new guess.
average = (minimum + maximum) / 2.0

Related

Why the While loop continues and how to calculate the average based on numbers input? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed last month.
Improve this question
Hi I'm trying to solve this coding homework:
Write a program that always asks the user to enter a number. When the user enters the negative number -1, the program should stop requesting the user to enter a number. The program must then calculate the average of the numbers entered excluding the -1.
I define the while loop to make sure it keeps asking, as:
while n != -1
str(input("enter your number:"))
But whenever I try to input -1, it just keeps on asking to enter the number regardless.
Also, I'm not sure what is the best way to define the average excluding -1, none of the lessons prior to this assignment talked about this. I have Googled about it but none of the examples match this particular assignment, even fumbling around did not help.
Thank you for your help :)
Presumably n is meant to be the user input, but you're never assigning a value to n. Did you mean to do this?
n = str(input("enter your number:"))
Also, you're comparing n to -1, but your input isn't a number; it's a string. You can either convert the input to a number via n = int(input(...)), or compare the input to a string: while n != '-1'.
You could ask for a number the if it is not equal to -1 enter the while loop. So the code would be:
n = float(input("What number?"))
if n != -1:
sum += n
nums_len = 1
while n != -1:
sum += 1
nums_len += 1
n = float(input("What number?"))
print("The average is", str(sum/nums_len))
Thanks everyone, this is the final code with the correct values that gives the average of user inputs
n = float(input("What number?"))
if n != -1:
sum = 0
nums_len = 0
while n != -1:
sum += n
nums_len += 1
n = float(input("What number?"))
print("The average is", float(sum/nums_len))

Python: Guessing a number is User's mind

I am stuck on a question from my Introduction to Python course. I have to write a code wherein the user keeps an integer in their mind, and the computer guesses. If the user's number is higher than the computer's guess, the user types "+", and the computer guesses higher. If the user's number is lower, the user types "-", and the computer guesses lower numer. If the computer guesses correctly, the user types "y", and the program ends.
Use the builtin function "input" to get a text from the user. If the user types anything other than "+", "-", or "y", the function should throw an exception.
Your function should take no arguments and return nothing.
I have to write the code in python.
The problem I am facing is that after checking for the input the first time, how to change the range and make the user enter their response again. I have just started coding, so please forgive me if it is a very basic question.
I was having the same problem you have and here is my solution for it:
import random
low = 1
high = 100
int(input("Enter the number for computer to guess: "))
while low != high:
guess = low + (high - low) // 2
high_low = input(f"Computer guess is: {guess} \n "
f"Press (H) for higher, (L) for lower and (C) for correct: ").casefold()
if high_low == "h":
low = guess + 1
elif high_low == "l":
high = guess - 1
elif high_low == "c":
print(f"I got it the number is {guess}")
break
else:
print("Please enter h, l or c")
else:
print(f"Your number is {low}")
Here I was using Binary Search algorithm with formula: guess = low + (high - low) // 2. To be more clear, what this formula does it starts of with guessing the mid point between high and low values. If we are told to guess higher that must mean our answer must be between 50 - 100. So the lowest it can be is 51 and that is our new lowest value for the range the mid point now becomes 51+(100-51)//2 (answer from this calculation is 75.5 integer division rounds down) so the result is 75. And If we are told now to guess lower that means answer must be somewhere between 51 and 75, so we know the answer is less than 75, the mid point now becomes 50+(75-51)//2
which is 62 and so on continues with that pattern. You can change H with +, L with -, and C with y and you will get your solution. I hope you find this useful :).
There are several solutions here, and some are more sophisticated than others.
The simplest solution in my opinion would simply be something like this (without validations):
if user_input == "+":
number = number + 1
elif user_input == "-":
number = number - 1
elif user_input = "y":
print("Number guessed correctly.")
Depending on the user input, the program will simply add or subtract 1 from the number. That way, you don't require range checks or anything the like.
Let me know if this approach is acceptable.

Python 'Guess Your Age' Remember Last Integer

I am relatively new to programming with python (actually programming in general). I am making this 'Guess My Age' program that only has one problem:
import random
import time
import sys
print("\tAge Guesser!")
print("\t8 tries only!")
name = input("\nWhat's your name? ")
num = 80
min_num = 6
tries = 1
number = random.randint(min_num, num)
print("\nLet me guess... You are", number, "years old?")
guess = input("'Higher', 'Lower', or was it 'Correct'? ")
guess = guess.lower()
while guess != "correct":
if tries == 8:
print("\n I guess I couldn't guess your age....")
print("Closing...")
time.sleep(5)
sys.exit()
elif guess == "higher":
print("Let me think...")
min_num = number + 1 #### Here is my trouble - Don't know how to limit max number
time.sleep(3) # pause
elif guess == "lower":
print("Let me think...")
num = number - 1
time.sleep(3) # pause
number = random.randint(min_num, num) #<- Picks new random number
print("\nLet me guess... You are", number, "years old?")
guess = input("'Higher', 'Lower', or was it 'Correct'? ")
guess = guess.lower() #<- Lowercases
tries += 1 #<- Ups the tries by one
print("\nPfft. Knew it all along.")
time.sleep(10)
As you can see, I have 'num' as the max number for the random integer getting picked, but with:
elif guess == "higher":
print("Let me think...")
min_num = number + 1
it can go back up to however high it wants.
I want it to remember the last integer that 'num' was.
Say the program guessed 50 and I said 'Lower'. Then it said 30 and I said 'Higher'
I know I am probably sounding confusing, but please bear with me.
You need to define a maximum number as well as a minimum number. If they say their age is lower than a given age, you should set that age minus 1 as the maximum.
Of course, you also need to set an initial maximal age.
You might find it more useful to look into recursive functions for this kind of problem. If you define a function which takes min_age, max_age and tries_left as parameters, which comes up with a random number with between min_age and max_age and queries the user, you can then rerun the function (within itself) with a modified min_age, max_age and tries_left - 1. If tries_left is zero, concede defeat. This way you might get a better understanding of the logical flow.
I have left code out of this answer because, as you are a beginner, you will find it a useful exercise to implement yourself.
Cant you split out your guess into something like
max_num = 0
min_num = 0
elif guess =="lower":
max_num = number
if min_num!=0:
number = min_num+(max_num-min_num)/2
else:
number = max_num-1
elif guess =="higher":
min_num = number
if max_num!=0:
number=min_num+(max_num-min_num)/2
else:
number=min_num+1
Sorry it's not meant to be fully rigorous, and its a slight change on the logic you have there, but splitting out your variables so you have a higher and lower cap, that should help a lot?
Cheers
Please let me know if you need more elaboration, and I can try to write out a fully comprehensive version
It seems as though I was wrong in the fact that it did not remember the older integers. Before when running the program it would guess a number higher than the 'num' had specified. I don't know what I changed between then and now? But thank you for the help! #.#
This seems to work.
The only changes I really made:
-Variable names were confusing me, so I changed a couple.
-Note that if you try to mess with it (lower than 5, higher than 3... "Is it 4?" if you say it's higher or lower, you'll get an error).
The first time you set min and max numbers, you do it outside of the loop, so this script does "remember" the last guess and applies it to the new min, max inside of the loop. Each time it runs, the min will get higher or the max will get lower, based on the feedback from when the user checks the guess. If you had stuck the "min_num=6" and the "num=80" inside of the loop, the guesses would never get better.
import random
import time
import sys
print("\tAge Guesser!")
print("\t8 tries only!")
name = input("\nWhat's your name? ")
max_num = 10
min_num = 1
tries = 1
guess = random.randint(min_num, max_num)
print("\nLet me guess... You are", guess, "years old?")
check = raw_input("'Higher', 'Lower', or was it 'Correct'? ")
check = check.lower()
while check != "correct":
if tries == 8:
print("\n I guess I couldn't guess your age....")
print("Closing...")
time.sleep(5)
sys.exit()
elif check == "higher":
print("Let me think...")
min_num = guess + 1
time.sleep(3) # pause
elif check == "lower":
print("Let me think...")
max_num = guess - 1
time.sleep(3) # pause
guess = random.randint(min_num, max_num) # <- Picks new random number
print("\nLet me guess... You are", guess, "years old?")
check = input("'Higher', 'Lower', or was it 'Correct'? ")
check = check.lower() # <- Lowercases
tries += 1 # <- Ups the tries by one
print("\nPfft. Knew it all along.")
time.sleep(10)

Python: Loop Sentinel Value [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I'm supposed to write a program with a loop that lets the user enter a series of integers, followed by -99 to signal the end of the series. After all the numbers have been entered, the program should display the largest and smallest numbers entered.
This is what I have so far:
def main():
user_input = 1
while user_input != -99:
user_input = int(input("Enter your number or -99 to end."))
bigger = largest(user_input)
tinier = smallest(user_input)
print('The largest number is ', bigger, "and the smallest is ", tinier, ".")
def largest(number):
largest = 0
if number > largest:
largest = number
return largest
def smallest(number):
smallest = 10000
if number < smallest:
smallest = number
return smallest
main()
For some reason the sentinel value (-99) is entering the loop, I have no clue how, and becoming the smallest value. On top of that, the biggest value isn't ever the right one. Help much appreciated!
The quickest change to make to your code to fix this would be
def main():
user_input = 1
while user_input != -99:
user_input = int(input("Enter your number or -99 to end."))
if use_input == -99:
break
bigger = largest(user_input)
tinier = smallest(user_input)
print('The largest number is ', bigger, "and the smallest is ", tinier, ".")
The problem is, if the user enters -99, you complete the rest of the lines for that iteration of the loop. It will not terminate the while loop until the next time around, but it has already performed largest and smallest at that point so it is already overwritten.
Your Indentation is important in python so your smallest value and largest value functions return statement is improperly indent
def largest(number):
largest = 0
if number > largest:
largest = number
return largest
def smallest(number):
smallest = 10000
if number < smallest:
smallest = number
return smallest
Pretty simple if you use a list to store the numbers and rely on max/min functions from the standard library:
def main():
numbers = []
while True:
user_input = int(raw_input("Enter a number"))
if user_input == -99:
break
else:
numbers.append(user_input)
print('Largest is {}, smallest is {}'.format(max(numbers), min(numbers)))
You have two problems as far as I can see: your input is being processed before being checked, and there are issues in your largest() and smallest() functions. When you scan for user input, you immediately go into your functions before verifying. Restructure your loop like this:
input()
while(){
...
...
input()
}
For the second part, your functions aren't working because you initialize the values every time they run. Initialize your functions in the header at the top of your file, then just compare them. So for example, move the line largest=0 to the top of your file right below your import statements. Other than that, I think it should work.

Python number guessing game

I have found some practice problems online and I got most of them to work, but this one has stumped me. Its not homework so I'm not getting a grade. However, there isn't a solution provided so the only way to get the answer is by doing it.
The task asks for you to write a problem that plays a number guessing game for numbers 1-100. However, this one tries to guess the users number by interval guessing, such as [1, 100] and generates the next question by using first+last/2.
I have a sample run from the site.
Think of a number between 1 and 100 (inclusive).
Answer the following questions with letters y or Y for yes and n or N for no.
interval: [1,100]. Is your number <= 50? y
interval: [1,50]. Is your number <= 25? y
interval: [1,25]. Is your number <= 13? y
interval: [1,13]. Is your number <= 7? n
interval: [8,13]. Is your number <= 10? n
interval: [11,13]. Is your number <= 12? y
interval: [11,12]. Is your number <= 11? y
Your number is: 11
Here is my code so far, but I don't even quite know where to start because a while-loop constantly gives me an infinite loop. I know the "middle" number needs to be an integer or else it'll be an infinite loop, but I can't seem to figure out how to do that.
x = input("Is your numbr <=50?")
count = 100
while x=="y" or "Y":
count = count/2
x = input("Is your number <=",count,"?")
print(count)
If anyone has any tips it would be greatly appreciated.
The issue is here:
while x=="y" or "Y":
the expression "Y" will always evaluate to true.
You want
while x == "y" or x == "Y":
Even then, this will end the loop when the user types an "N". A working loop would be something like:
finished = False
while not finished:
if x == "y":
upper -= (upper-lower)/2
# prompt for input
elif x == "n":
lower += (upper-lower)/2
# prompt for input
if upper == lower or (upper - 1) == lower:
finished = True
# final output
You should be able to fill in the blanks from there.
The entire idea of the problem is to keep both "bounds" starting at 1 and 100, and each time you make a question "is you number <= X" you discard half of the range according to the answer, you are not doing this in your current solution.
like this.
lower = 1
high = 100
mid = (high + lower)/2 -> at start it will be 50
If the user answers Yes then you take the range from the current lower bound to the mid of the range, otherwise you continue with the range starting on mid+1 to the end, like this:
If user answers Yes:
high = mid
If user answers No:
lower = mid +1
The last part of the idea is to detect when the range lower-high contains only 2 numbers, or are the same number like this [11,12], you use the final answer of the user to choose the correct answer and the program terminates, the full code is here so you can test it:
found = False
range_lower_bound = 1
range_high_bound = 100
print "Think of a number between 1 and 100 (inclusive)."
print "Answer the following questions with letters y or Y for yes and n or N for no."
while not found:
range_mid = (range_high_bound + range_lower_bound) / 2
x = raw_input('interval: [%s,%s]. Is your number <= %s? ' % (range_lower_bound, range_high_bound, range_mid))
if x.lower() == 'y':
# Check if this is the last question we need to guess the number
if range_mid == range_lower_bound:
print "Your number is %s" % (range_lower_bound)
found = True
range_high_bound = range_mid
# here i'm defaulting "anything" no N for simplicity
else:
# Check if this is the last question we need to guess the number
if range_mid == range_lower_bound:
print "Your number is %s" % (range_high_bound)
found = True
range_lower_bound = range_mid + 1
Hope it helps!
One good idea would be to have a simple while True: loop, inside which you maintain a maximum guess and a minimum guess. You then ask the user whether their number is greater than the average of the two. If it is, update your minimum guess to the average. If not, you lower your maximum guess to the average. Repeat until the two guesses are equal, at which point you have found the number, and can break out of the infinite loop.
You'll have to do some simple parity checking of course, to make sure you actually change your guesses in each round. You should really use raw_input() for strings, input() is for python-formatted data.

Categories

Resources