Infinite loop in Python while loops [closed] - python

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I don't know whats wrong. When I put in x*x for the left side, and 25 for the right side, it doesnt work. The python shell shows no errors, but after I enter the amount of solutions, nothing happens. I think that it could be in an endless loop, or not be applying x after each run. PLEASE HELP! Here is my code:
#getting input information
print
print "This program cannot solve for irrational or repeating numbers. Please round for them in your equation."
print
print "Make the variable in your equation stand for x"
print
startingLimit=int(raw_input("What is the lowest estimate that your variable could possibly be?"))
print
wholeNumber=raw_input("Do you know if your variable will be a whole number or a fraction? Answer: yes/no")
if (wholeNumber== "yes"):
print
fraction= raw_input("Is it a decimal/fraction? Answer:yes/no")
if (fraction=="yes"):
print
print "This program will only calculate up to the fourth place to the right of the decimal"
xfinder=0.0001
else:
xfinder=1
else:
xfinder=0.0001
x=0
leftEquation=raw_input("Enter your left side of the equation:")
print
rightEquation=raw_input("Enter the right side of the equation:")
print
amountSolutions=raw_input("How many solutions are there to your equation? (up to 20)")
#solving
indivisualCount=0
count=0
x=startingLimit
while (count!=amountSolutions):
while (count==0):
ifstuffleft=eval(leftEquation)
ifstuffright=eval (rightEquation)
if (ifstuffleft!=ifstuffright):
x=x+xfinder
else:
a=x
count=count+1

Why do you have the inner while (count==0): while loop? That will cause it to get stuck on an infinite loop (in the while (count!=amountSolutions): loop) as soon as count is not equal to 0 (since it will never enter that inner while loop).
Once you've fixed that, notice that you don't perform x=x+xfinder if the values are equal to each other. That means you will stay on the same value (in this case -5) until you've satisfied the number of solutions. You thus have to increase the value by xfinder whether or not the values are equal.
You never print the solution or do anything with it. You probably want to replace the a=x line with print "One solution is", x
Finally, when you're posting a question you should strive for a minimal example. All of your input code can be replaced by hardcoding the 5 variables, something like:
startingLimit = -10
xfinder = 1
leftEquation = "x*x"
rightEquation = "25"
amountSolutions = 2
This a) requires 23 fewer lines of code, making your question easier to read and understand, b) makes it easier to test so people can see the problem without answering six questions and c) prevents answerers from having to guess what you put in for startingLimit and amountSolutions.

If any value other than 1 is given for amountSolutions it seems like this code will go into an infinite loop.
while (count!=amountSolutions):
while (count==0):
In the above once one solution is found, count = 1 and thus the inner while loop would be skipped.

Related

how to reduce run tiime for a simple if-else-while program

i had just started learning python,so i was practising some code at codechef
one of the problem i was trying was https://www.codechef.com/problems/CHEFEZQ
"Chef published a blog post, and is now receiving many queries about it. On day i, he receives Qi queries. But Chef can answer at most k queries in a single day.
Chef always answers the maximum number of questions that he can on any given day (note however that this cannot be more than k). The remaining questions (if any) will be carried over to the next day.
Fortunately, after n days, the queries have stopped. Chef would like to know the first day during which he has some free time, i.e. the first day when he answered less than k questions.
Input:
First line will contain T, the number of testcases. Then the testcases follow.
The first line of each testcase contains two space separated integers n and k.
The second line of each testcase contains n space separated integers, namely Q1,Q2,...Qn.
Output:
For each testcase, output in a single line the first day during which chef answers less than k questions.
Constraints
1≤T≤105
1≤ sum of n over all testcases ≤105
1≤k≤108
0≤Qi≤108"
so i wrote my code like this:
i=0
while (i<T):
nk=input()
q=[int(a) for a in input().split(" ")]
n_k=nk.split(" ")
n=int(n_k[0])
k=int(n_k[1])
j=0
l=0
while j<n:
l=l+q[j]-k
if l<0:
print(j+1)
break
j+=1
while j>=n:
l=l-k
if l<0:
print(j+1)
break
j+=1
i+=1
the total time limit is 1sec but my code takes 5 sec
i dont find any method to reduce time,can someone pls help me out
thank you in advance
The second while j >= n is unnecessary if you have already called print, and if you haven't, print(j + l//k + 1) or something similar (please use longer and more meaningful variable names!) will directly calculate the answer.
The while loop j>=n is badly designed: The loop condition never gets False as j is always increased and n never decreased. In general, such a loop may never terminate. In this case, it probably will terminate as l is decreased (hoping that k is always positive) and this eventually leads to a break. But a loop should always be constructed such that the condition eventually becomes False.
At the end of the loop with condition j<n, the new condition j>=n holds anyway and always will (as long as j and n are not manipulated). Thus the new condition may be while l>=0. (I did not check whether this, in particular, solves the actual task, however, but it will at least simplify the given code, apart from improving the style. It does at least with one check less per iteration.)

in a while loop, where should you place a variable for counting?

enter image description here
Please excuse me that I'm posting my code as an image.
This is a simple guessing game expression.
When you look at the last line of the code,
there is 'tries += 1' code to count how many times it's looped.
So my question is,
the result is changing when I put 'tries += 1' right under
the code line 'guess = input("What is your lucky number?")'.
So what is the difference between
putting it at the last line of the code block and right under the start of while loop code.
Thanks for helping :)
Wouldn't it have been far easier to just copy in the text than to print-screen and crop the image? The number of tries is initialized to 1 which is misleading as at that point in the program there hasn't been any tries. Logically it makes more sense to initialize tries to 0 and place the increment immediately after the user input. But because the program hasn't been structured in this way, tries must be incremented after comparing the guess to the target; otherwise, in the case when the user's guess is correct, the output would show a number of tries one greater than the actual number of tries.
What you're misunderstanding is the order in which your code executes. There are three important events inside your loop:
You ask the user for their guess
You process their guess, and if they get it right you display the current value of the variable tries
You increment the variable tries, in the statement tries += 1
These execute in exactly that order. So, when the user guesses correctly, they're told the value of tries before it is incremented again. If you put the line tries += 1 right after the input statement, then that value is now being increased before it is printed. Thus, the displayed value is different.

Minimum and Maximum query not working properly (Python 3.5)

I wonder if you can help because I've been looking at this for a good half hour and I'm completely baffled, I think I must be missing something so I hope you can shed some light on this.
In this area of my program I am coding a query which will search a list of tuples for the salary of the person. Each tuple in the list is a separate record of a persons details, hence I have used two indexes; one for the record which is looped over, and one for the salary of the employee. What I am aiming for is for the program to ask you a minimum and maximum salary and for the program to print the names of the employees who are in that salary range.
It all seemed to work fine, until I realised that when entering in the value '100000' as a maximum value the query would output nothing. Completely baffled I tried entering in '999999' which then worked and all records were print. The only thing that I can think of is that the program is ignoring the extra digit, which I could not figure out why this would be?!
Below is my code for that specific section and output for a maximum value of 999999 (I would prefer not to paste the whole program as this is for a coursework project and I want to prevent anyone on the same course potentially copying my work, sorry if this makes my question unclear!):
The maximum salary out of all the records is 55000, hence why it doesnt make sense that a minimum of 0 and maximum of 100000 does not work, but a maximum of 999999 does!
If any more information is need to help, please ask! This probably seems unclear but like I said above, I dont want anyone from the class to plagiarise and my work to be void because of that! So I have tried to ask this without posting all my code on here!
Given your use of the print function (instead of the Python 2 print statement), it looks like you're writing Python 3 code. In Python 3, input returns a str. I'm guessing your data is also storing the salaries as str (otherwise the comparison would raise a TypeError). You need to convert both stored values and the result of input to int so it performs numerical comparisons, not ASCIIbetical comparisons.
When you read in from standard input in Python, no matter what input you get, you receive the input as a string. That means that your comparison function is resulting to:
if tuplist[x][2] > "0" and tuplist[x][2] < "999999" :
Can you see what the problem is now? Because it's a homework assignment, I don't want to give you the answer straight away.

Random number based on probability python

Hi I have done reseatch and I believe I ended up in the right direction when I ended up at this thread:
http://code.activestate.com/recipes/117241/
Basically my question is: what is the code in the link doing line by line. You could potentially ignore all that I wrote below if your explanation makes me understand what the code in the link does to a satisfactory extent.
I BELIEVE that the code at that link generates a random number BUT the random number is directly related to the probability.
In my own code I am attempting to take a "number" and its probability of appearing, and get an output "number", that will appear according to the probability. I know this is confusing but if you look at the link above then I hope it will be clear what I am trying to do. My code below is in reference to the link above.
so in my program, these are my global variables:
HIGH= 3
MED= 2
LOW= 1
This is the list I am working with:
n= [LOW,lowAttackProb).(MED,medAttackProb),(HIGH,highAttackProb)]
#lowAttackProb,med...,etc. are based on user input are just percents converted to decimals that add up to 1 in every case
This is how I implemented the random code as per the link above:
x= random.uniform(0,1)
for alevel,probability in n:
if x<probability:
break
x=x-probability
return alevel
I am unsure exactly what is happening inside the for loop and what x=x-probability is doing.
Lets say that x=0.90
and that in my list, the chance of the second list entry occuring is 0.60, then, since x (is less than)probability is False(im not too sure what if x(is less than)probability even does), the code moves on to n=n-probability.
I really hope this makes sense. If it does not please let me know what is unclear and I will try to fix it up. Thank you for any and all help.
This code implements the selection of event taking probabilities of possible events into account. Here is the idea behind it.
There are three events (or levels as you call them), LOW, MED, HIGH, with certain nonzero probability each, and all probabilities sum up to exactly 1. Using standard means of Python one can generate a random number between 0 and 1. So how can we "map" them to each other? Lets align our probabilities (lets call them L, M, and H for brevity) along the numbers line the following way:
0__________________L______________L+M_________________________L+M+H ( = 1)
Now taking our randomly generated number x we can say that
If x lies in interval [0, L] then the first event occurred.
If x lies in half-interval (L, L+M] then the second event occurred.
If x lies in half-interval (L+M, L+M+H] then the third event occurred.
The code you are asking about simply matches x to one of the intervals and returns the corresponding event (or level).

Transform game pseudo code into python

Make the computer guess a number that the user chooses between 1 and 1000 in no more than 10 guesses.This assignment uses an algorithm called a binary search. After each guess, the algorithm cuts the number of possible answers to search in half. Pseudocode for the complete
program is given below; your task is to turn it into a working python program.
The program should start by printing instructions to the screen, explaining that the user
should pick a number between 1 and 1000 and the computer will guess it in no more than
10 tries. It then starts making guesses, and after each guess it asks the user for feedback.
The user should be instructed to enter -1 if the guess needs to be lower, 0 if it was right,
and 1 if it needs to be higher.When the program guesses correctly, it should report how many guesses were required. If the user enters an invalid response, the instructions should be repeated and the user allowed to try again.
Pseudocode
- Print instructions to the user
-Start with high = 1000, low = 1, and tries = 1
- While high is greater than low
- Guess the average of high and low
- Ask the user to respond to the guess
- Handle the four possible outcomes:
- If the guess was right, print a message that tries guesses were required and quit the program
- If the guess was too high, set high to one less than the guess that was displayed to the user and increment tries
- If the guess was too low, set low to one more than the guess that was displayed to the user and increment tries
- If the user entered an incorrect value, print out the instructions again
- high and low must be equal, so print out the answer and the value of tries
I need some serious help! I don't understand any of this stuff at all!
This is all I have
def main(x, nums, low, high):
input("Enter -1 if the guess needs to be lower, 0 if the guess was right, or 1 if the guess needs to be higher: ")
for i in range (1, 1001):
main()
and I don't even know if it's right!
Before thinking about how to implement this in python (or any language) lets look at the pseudocode, which looks like a pretty good plan to solve the problem.
I would guess that one thing you might be getting stuck on is the way the pseudocode references variables, like high and low. The way to understand variables is to consider them slots that values can be stored. At any given time, a variable has some value, like the number 5, or a reference to an open file. That value can be summoned at any time by using its name, or it can be given a new value by assigning to it, and the old value will be forgotten with the new value taking its place.
The pseudocode references three variables, high, low and tries. It also tells you what their initial values should be. After the second line has executed, those values are set to 1000, 1 and 1, respectively, but they take on new values as the program progresses.
Another feature of the pseudocode is a conditional loop, and a case analysis of the user input. Your translation of the pseudocode's loop is incorrect. In your case, you have created a new variable, i and have instructed your program to run the loop body with every value of i between 1 and 1000. Obviously this doesn't have a whole lot to do with the pseudocode.
Instead what you want to do is loop forever, until some condition (which changes in the loop body) becomes false. In python, the while statement does this. If you're familiar with an if statement, while looks the same, but after the body is done, the condition is re-evaluated and the body is executed again if it is still true.
Finally, the case analysis in the body of the loop requires comparing something to expected values. Although some other languages have a number of ways of expressing this, in python we only have if-elif-else clauses.
Outside of transforming pseudocode to working code, it is probably useful to understand what the program is actually doing. The key here is on line 4, where the program guesses the average of two values. after that the program acts on how well the guess worked out.
In the first run through the loop, with high containing 1000 and low containing 1, the average is 500 (actually the average is 500.5, but since we're averaging whole numbers, python guesses that we want the result of the division to also be an integer). Obviously that guess has only a 0.1% chance of being right, but if it's wrong, the user is expected to tell us if it was too high, or too low. Either way, that answer completely eliminates 50% of the possible guesses.
If, for instance, the user was thinking of a low number, then when the program guessed 500, the user would tell the program that 500 was too high, and then the program wouldn't ever have to guess that the number was in the range of 501 thru 1000. That can save the computer a lot of work.
To put that information to use, the program keeps track of the range of possible values the goal number could be. When the number guessed is too high, the program adjusts its upper bound downward, just below the guess, and if the guess was too low, the program adjusts its lower bound upward to just above the guess.
When the program guesses again, the guess is right in the middle of the possible range, cutting the range in half again. The number of possible guesses went from the original 1000 to 500 in one guess, to 250 in two guesses. If the program has terrible luck, and can't get it two (which is actually pretty likely), then by the third, it has only 125 numbers left to worry about. After the fourth guess, only 62 numbers remain in range. This continues, and after eight guesses, only 3 numbers remain, and the program tries the middle number for its ninth guess. If that turns out to be wrong, only one number is left, and the program guesses it!
This technique of splitting a range in half and then continuing to the closer half is called bisection and appears in a wide range topics of interest to computer science.
How about some CODE! Since i don't want to deprive you of the learning experience, I'll just give you some snippets that might help you along. python is a language designed for interactive exploration, so fire up your interpreter and give this a shot. I'll be posting examples with the prompts shown, don't actually type that.
Here's an example using the while clause:
>>> x = 1000
>>> while x > 1:
... x = x/2
... print x
...
500
250
125
62
31
15
7
3
1
>>> x
1
Getting console input from the user should be done through the raw_input() function. It just returns whatever the user types. This is a little harder to show. To simplify things, after every line of python that requires input, I'll type "Hello World!" (without the quotes)
>>> raw_input()
Hello World!
'Hello World!'
>>> y = raw_input()
Hello World!
>>> print y
Hello World!
>>>
How about some combining of concepts!
>>> myvar = ''
>>> while myvar != 'exit':
... myvar = raw_input()
... if myvar == 'apples':
... print "I like apples"
... elif myvar == 'bananas':
... print "I don't like bananas"
... else:
... print "I've never eaten", myvar
...
apples
I like apples
mangoes
I've never eaten mangoes
bananas
I don't like bananas
exit
I've never eaten exit
>>>
Oops. little bit of a bug there. See if you can fix it!
I don't understand any of this stuff at all!
That's pretty problematic, but, fine, let's do one step at a time! Your homework assignment begins:
Print instructions to the user
So you don't understand ANY of the stuff, you say, so that means you don't understand this part either. Well: "the user" is the person who's running your program. "Instructions" are English sentences that tell him or her what to do to play the game, as per the following quote from this excellently clear and detailed assignment:
The program should start by printing instructions to the screen, explaining
that the user should pick a number between 1 and 1000 and the computer will
guess it in no more than 10 tries.
"print" is a Python instruction that emits information; for example, try a program containing only
print "some information"
to see how it works. OK, can you please edit your answer to show us that you've gotten this point, so we can move to the next one? Feel free to comment here with further questions if any words or concepts I'm using are still too advanced for you, and I'll try to clarify!
You're obviously very new to programming, and I guess that is one of the reasons for a delayed response from the community. It's tough to decide where to start and how to guide you through this whole exercise.
So, before you get a good answer here that includes making you understand what's happening there, and guiding you through building the solution yourself (ideally!) I would suggest you visit this page to try to get a grasp of the actual problem itself.
http://www.openbookproject.net/pybiblio/gasp/course/4-highlow.html
In the meantime, look at all the answers in this thread and keep editing your post so that we know you're getting it.
Doesn't match the psudocode exactly but it works. lol ;)
I know this is a wicked old post but this is the same assignment I got also. Here is what I ended up with:
high = 1000
low = 1
print "Pick a number between 1 and 1000."
print "I will guess your number in 10 tries or less."
print "Or at least i'll try to. ;)"
print "My first guess is 500."
guess = 500
tries = 0
answer = 1
print "Enter 1 if it's higher."
print "Enter -1 if it's lower."
print "Enter 0 if I guessed it!"
print ""
while (answer != 0):
answer = int(raw_input("Am I close?"))
if answer == 1:
tries = tries + 1
low = guess
guess = (high + low) / 2
print "My next guess is:"
print guess
elif answer == -1:
tries = tries + 1
high = guess
guess = (high + low) / 2
print "My next guess is:"
print guess
elif answer == 0:
tries = tries + 1
print "Your number is:"
print guess
print "Yay! I got it! Number of guesses:"
print tries
Okay, the nice part about using Python is that it's almost pseudocode anyway.
Now, let's think about the individual steps:
How do you get the average between high and low?
How do you ask the user if the answerr is correct
What do "if" statements look like in Python, and how would you write the pseudocode out as if statements?
Here's another hint -- you can run python as an interpreter and try individual statements along, so, for example, you could do
high=23
low=7
then compute what you think should be the average or midpoint between them (hint: 15)
Welcome to Stack Overflow!
The trick here is to realize that your Python program should look almost like the pseudocode.
First let's try to understand exactly what the pseudocode is doing. If we had to interact with the program described by the pseudocode, it would look something like this:
Think of a number between 1 and 1000 and press Enter.
>>>
Is it 500? Enter -1 if it's lower, 0 if I guessed right, or 1 if it's higher.
>>> 1
Is it 750? Enter -1 if it's lower, 0 if I guessed right, or 1 if it's higher.
>>> -1
Is it 625? Enter -1 if it's lower, 0 if I guessed right, or 1 if it's higher.
etc.
When we first think of our number, the program knows only that it is between 1 and 1000. It represents this knowledge by setting the variable 'low' to 1 and the variable 'high' to 1000. Its first guess is the average of these numbers, which is 500.
After we tell the program that our number is greater than 500, it updates the value of 'low' to 501. In other words the program then knows that our number is between 501 and 1000. It then guesses the average of 501 and 1000, which is 750. We tell it that our number is lower, so the program updates the value of 'high' to 749 and guesses the average of 501 and 749 next, and so on until it guesses right, or it has narrowed the possible range down to a single number (meaning its next guess will be right).
So back to writing the program in Python: We basically just translate the pseudocode line for line. For example our program loop should look just like it does in the pseucode:
while high > low:
# Guess (high + low) / 2 and ask user to respond
# Handle user response
There is no need for a for-loop as you have in your code.
To take input we can do something like this:
guess = (high + low) / 2
response = input('Is it ' + str(guess) + '? Enter -1 if it's lower, 0 if I guessed right, or 1 if it's higher.')
Now the user input is stored in the variable 'response', and we can handle the possibilities with if statements like 'if response == -1:' for example.
Just remember to print the instructions and set 'high' and 'low' to their initial values before entering the while loop and you should be all set.
Good luck!
Here's a few hints to get you started:
Average = Value + Value + Value [...] / Number of Values; (for instance, ((2 + 5 + 3) / (3))
Many programming languages use different operator precedence. When I am programming, I always use parentheses when I am unsure about operator precedence. In my example above, if you only did 2 + 5 + 3 / 3, the program would do division operations before addition - so it would evaulate to 2 + 5 + (3 / 3), or 2 + 5 + 1 == 7.
Skip this for python users
/*
Secondly: your earliest programs can benefit from const correctness (here is a good explanation of what it is and why it is EXTREMELY good practice). Please read through that and understand why you should use constants (or whatever the python equivalent is). Also look up "magic numbers," which is a big area where constants are used.
*/
Google "Please Excuse My Dear Aunt Sally" (NOTE: this only deals with mathematical operators, and mostly holds true for programming languages; for a more comprehensive study of operator precedence, look up your chosen language's documentation for precedence - also note that most programs don't have built in power operators, but most standard libraries have pow functions).
Speaking of standard library: Get acquainted with standard library functions (I have never used Python, I don't know how it implements a SL, but I would be extremely surprised if a language that popular didn't have a well developed SL). If you don't know what that is, and your book/tutorial doesn't have it, get a new one. Any resource that doesn't reference a standard library is not worth the time.
Lastly: while this post may look like I know what I'm talking about, I really am still in the early phases of learning, just like you. A few things you might want to get used to early on (when I skipped these parts, it slowed my learning a lot): The use of references and pointers (Q for comments: does Python have pointers?), the difference between the data IN a memory location and the actual memory location (often times, the location of the value in memory will be more useful than the value itself, at least when writing data structures). Especially get used to the standard library; look for copy, find, etc. type functions useful in string manipulation.
Actually, rereading your original post, I did not realize this was a homework type assignment. If you aren't doing this for fun, you will probably never take my advice. Just remember that programming can be extremely fun, if you don't make it a chore - and don't get frustrated when your code doesn't compile (or...interpret), or you get unexpected results, etc.

Categories

Resources