So I am still learning to code and use python as my primary language. The question is we have two numbers. A and B which we have to take as input. A will be 0 and B is given in two test cases as 30 and 10^9. The system will pick a number (say P) between A(exclusive) and B(inclusive). We have to write a program to guess the number. If our guess is higher than P, the system will output "TOO_BIG" and we have to adjust our next guess. If our guess is lower than P, then we'll get "TOO_SMALL". If it's right, then we'll get "CORRECT". We have N tries to guess the number and N = 30.
This is my code:
import sys
def solve(lower,upper):
guessed_right = False
for _ in range(no_of_guesses):
midpoint = (lower + upper)//2
guess = midpoint
print(guess)
sys.stdout.flush()
judge = input()
if judge == "CORRECT":
guessed_right = True
break
elif judge == "TOO_BIG":
upper = midpoint - 1
elif judge == "TOO_SMALL":
lower = midpoint + 1
elif judge == "WRONG_ANSWER":
sys.exit()
def run():
T = int(input())
for case in range(T):
lower, upper = map(int(input().split()))
no_of_guesses = int(input())
solve(lower + 1, upper)
I am getting wrong answer for this and can't seem to find the problem
Related
I have started a python beginner project where the computer guesses the user's number by entering whether it's higher or lower than x. However, I have managed the first part but my program stops and does not carry on. My guess is that I need to include a loop somewhere to repeat the nextguess() within the code but I cannot figure out where.
This is my code:
maxnum = 1000
min = 1
guess = 500
print("1 = Higher 2 = Lower 3 = Correct")
print("Pick a number dont tell me what it is!")
print("The highest number you can pick is:",maxnum)
print("The lowest number you can pick is:",min)
print("Is it higher or lower than:",guess)
maxnum = maxnum +1;
choice = input()
choiceprop = int(choice)
def nextguess():
guess = (maxnum + min) / 2
print("Is it lower or higher than:", guess)
if choiceprop == 1:
min = guess
nextguess()
maxnum = maxnum +1;
if choiceprop == 2:
maxnum = guess
nextguess()
maxnum = maxnum +1;
if choiceprop == 3:
print("nice!");
Looks like you're trying to use binary search to zero down on the user's number, you'll need to keep an eye on how numbers are rounded and how you shift your boundaries in response to the user's input.
As far as keeping it going beyond the first input, you'll need to put the portions that take the user's input and makes the next guess in a while loop, making sure you have a code stop condition or logic within the loop body to prevent it from looping infinitely.
Here's an example of how it could be done:
import math
def main():
min = 0
max = 1000
print("Pick a number dont tell me what it is!")
print("The highest number you can pick is:", max)
print("The lowest number you can pick is:", min)
while max >= min:
guess = math.ceil((max + min) / 2)
print("Is it higher or lower than: ", guess)
print('1. Higher')
print('2. Lower')
print('3. Correct')
choiceprop = int(input('Option: '))
if choiceprop == 1:
min = guess + 1 # guess can be excluded safely
elif choiceprop == 2:
max = guess - 1
else:
print('nice')
break
main()
Think about what part of the code needs to be repeated: it’s the part that asks for a next input, and generates a next guess.
That’s pretty much all of your code, except for the preamble, and the definition of nextguess:
def nextguess():
guess = (maxnum + min) / 2
print("Is it lower or higher than:", guess)
maxnum = 1000
min = 1
guess = 500
print("1 = Higher 2 = Lower 3 = Correct")
print("Pick a number dont tell me what it is!")
print("The highest number you can pick is:", maxnum)
print("The lowest number you can pick is:", min)
print("Is it higher or lower than:", guess)
while True:
choice = input()
choiceprop = int(choice)
if choiceprop == 1:
min = guess
elif choiceprop == 2:
maxnum = guess
elif choiceprop == 3:
print("nice!")
break
nextguess()
maxnum = maxnum + 1
However, this code still won’t work, because your logic for generating guesses is incorrect: why are you increasing maxnum? Surely the maximum can’t change. Next, your nextguess generates non-integral guesses. You need to restrict this to integer numbers.
Finally, nextguess also won’t change your global variable guess, you need to return your next guess, and assign it:
def nextguess(min, max):
guess = (min + max) // 2
print("Is it lower or higher than:", guess)
return guess
… and now, when calling nextguess you need to pass it a minumum and maximum bound.
With this change, you also don’t need to hard-code your initial guess: just call nextguess at the beginning.
def nextguess(min, max):
guess = (min + max) // 2
print("Is it lower or higher than:", guess)
return guess
max = 1000
min = 1
print("1 = Higher 2 = Lower 3 = Correct")
print("Pick a number dont tell me what it is!")
print("The highest number you can pick is:", max)
print("The lowest number you can pick is:", min)
while True:
guess = nextguess(min, max)
choice = int(input())
if choice == 1:
min = guess
elif choice == 2:
max = guess
elif choice == 3:
print("nice!")
break
guess = nextguess(min, max)
(PS: Don’t use ; in Python.)
Please ignore my un-used import!
I tried to create a list to find min and max of "pa_walk" but I just could figure how to do it, everytime I tried it said error.
import random
from math import sqrt
from math import hypot
import statistics
random.seed(20190101)
def takeOnePaStep():
direction = random.randint(0,3)
if direction == 0:
return (0,1)
elif direction == 1:
return (1,0)
elif direction == 2:
return (0,-1)
elif direction == 3:
return (-1,0)
def randomWalkPa(steps):
pa = [0,0]
for _ in range (steps):
nextStep = takeOnePaStep()
pa[0] += nextStep[0]
pa[1] += nextStep[1]
pasDistance = hypot(pa[0],pa[1])
return pasDistance
# paMean = statistic.mean(distance)
steps = int(input("Please enter the number of steps: "))
tries = int(input("How many times should I perform the experiment? "))
for _ in range(tries):
pa_walk= randomWalkPa(steps)
print(pa_walk)
I gues it is because your function randomWalkPa(steps) returns a float of the distance, that's why you first need to create a list (in the example below I just made pa_walk a list. In your for-loop just .append the distance for every try to that list. Finally you can call the built-in functions max()and min() to get the maximum and minimum distance. I unindented the print commands for the min and max call to just get the results once
pa_walk = []
for _ in range(tries):
pa_walk.append(randomWalkPa(steps))
print(f"The Maximum Distance reached was: {max(pa_walk)}, in trial: {pa_walk.index(max(pa_walk))}")
print(f"The Minimum Distance reached was: {min(pa_walk)}, in trial: {pa_walk.index(min(pa_walk))}")
After recommendation in the comments here is the full code (I changed nothing but the last 5 rows)
import random
from math import sqrt
from math import hypot
import statistics
random.seed(20190101)
def takeOnePaStep():
direction = random.randint(0,3)
if direction == 0:
return (0,1)
elif direction == 1:
return (1,0)
elif direction == 2:
return (0,-1)
elif direction == 3:
return (-1,0)
def randomWalkPa(steps):
pa = [0,0]
for _ in range (steps):
nextStep = takeOnePaStep()
pa[0] += nextStep[0]
pa[1] += nextStep[1]
pasDistance = hypot(pa[0],pa[1])
return pasDistance
# paMean = statistic.mean(distance)
steps = int(input("Please enter the number of steps: "))
tries = int(input("How many times should I perform the experiment? "))
pa_walk = []
for _ in range(tries):
pa_walk.append(randomWalkPa(steps))
print(f"The Maximum Distance reached was: {max(pa_walk)}, in trial: {pa_walk.index(max(pa_walk))}")
print(f"The Minimum Distance reached was: {min(pa_walk)}, in trial: {pa_walk.index(min(pa_walk))}")
Edit:
A minor thing to note, in python it is convention to use underscores rather than camelcase. This means the function randomWalkPa() would be better called random_walk_pa(). This is not necessary to make the code work and totally up to you
I'm trying to program a function to compute Newton's method. Expect I keep getting an error in my code.
This is the prompt that I was given to write a code for
And this is my code that I have written down
import math
def newton(x):
tolerance = 0.000001
estimate = 1.0
while True:
estimate = (estimate + x / estimate) / 2
difference = abs(x - estimate ** 2)
if difference <= tolerance:
break
return estimate
def main():
while True:
x = input("Enter a positive number or enter/return to quit: ")
if x == '':
break
x = float(x)
print("The program's estimate is", newton(x))
print("Python's estimate is ", math.sqrt(x))
main()
And it seems to be working but I keep getting this error when I run checks on Cengage
I'm not really sure what it means because my code seems to be running just fine. Can anyone help explain this?
The issue seems to occur when the input is blank. A potential workaround, assuming you would only want positive numbers as input, would be to set a negative number (or anything else of your choice), like -1 for example, as an exit condition:
x = input("Enter a positive number or enter/return to quit: ")
if not x:
break
x = float(x)
This should avoid the EOFError.
Edit
If you want to use a blank input (hitting the return line) to break out of the loop, you can try this alternative syntax:
x = input("Enter a positive number or enter/return to quit: ")
if not x:
break
x = float(x)
The not x checks if x is blank. It is also more pythonic than x == "". Additional methods to detect a blank input are in this post as well: How do you get Python to detect for no input.
I did mine like this and Cengage accepted it.
import math
tolerance = 0.000001
def newton(x):
estimate = 1.0
while True:
estimate = (estimate + x / estimate) / 2
difference = abs(x - estimate ** 2)
if difference <= tolerance:
break
return estimate
def main():
while True:
x = input("Enter a positive number or enter/return to quit: ")
if x == "":
break
x = float(x)
print("The program's estimate is", newton(x))
print("Python's estimate is ", math.sqrt(x))
if __name__ == "__main__":
main()
I have created a quiz system which tests the user on two different topics. They are can choose whih topics they would like to do and a difficulty they wish to complete it in. If they get the question correct they get a point if they don't it will display the correct answer.
I am struggling to calculate the percentage based on the user's correct answers. For example, I have came up with "percent = score/100 x 100" which doesn't work. Any suggestions of calculating the percentage from these lists?
t = input("Choose 'a' for arithmetics or 'g' for german:")
d = input("Choose 'e' for easy , 'm' for medium , 'h' for hard:")
arithQeasy = [
("What is 4 + 4? Choose 1 or 2: 1) 8 2) 7","1"),
("What is 16 + 16? Choose 1 or 2: 1) 26 2) 32","2"),
]
arithQmedium = [
("How many 6's in 36? Choose 1, 2 or 3: 1) 6 2) 12 3) 3","1"),
("What is the Square root of 100? Choose 1, 2 or 3: 1) 50 2) 100 3) 10","3"),
("What is 0x1000? Choose 1, 2 or 3: 1) 1000 2) 0 3) 100","2"),
]
if t == "a" and d == "e":
questions = arithQeasy
elif t == "a" and d == "m":
questions = arithQmedium
for question, answer in questions:
userInput = input(question + '')
if userInput == answer:
score +=1
print ("correct your score is:",score)
elif:
print ("Incorrect the anseer is:",answer)
The following seems to work. Note there are a couple of issues with your code snippet:
The elif in the for loop needs to be an else.
You need to initialize score to zero before entering the for loop.
I've fixed these problems and added some code at the end illustrating how to compute the percentage of correct answers, as you asked how to do:
...
score = 0
for question, answer in questions:
userInput = input(question + '')
if userInput == answer:
score += 1
print("correct your score is:", score)
else:
print("Incorrect the anseer is:", answer)
percent = round((score / len(questions)) * 100, 2)
print('percent right: {}%'.format(percent))
Explanation
This works because a percentage is "a number or ratio expressed as a fraction of 100" (from the Wikipedia article on percentage), so the expression calculates the ratio of right answers, score, to the total number of questions, len(questions). It then multiples that by 100 since percentages always express this ratio as a "fraction of 100".
I also added a call to round()—which wasn't strictly necessary—to limit the number of digits after the decimal point to two, so long numbers like 6.666666666666666% would get converted to 6.67%. Technically this makes the final value computed slightly less accurate, but I doubt that matters here.
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)