I need to create a program that runs constantly unless the user presses q to end it. The program asks the user for a number and puts the number in a queue, then it prints the queue with the new element at the end. If the number is with 01,02 then it will be added at the left hand side without the 0 at the beginning, otherwise at the right hand side. The user can remove an item from the end of the queue by typing r.
I got the starting point where it asks the user and goes until 'q' is pressed.
while True:
if input("\n\n\nType a number to add it to the queue or q to exit: ") == 'q':
break
Separate out the input call from the logic that depends on the value it returns. Instead, assign the value to a variable that you can examine several times:
while True:
val = input(...)
if val == 'q':
break
if val.startswith('0'):
...
else:
...
Related
I have a stack S containing n elements and a queue Q that is initially empty. I have to implement an algorithm that uses Q to scan S to see if it contains a certain element x, with the additional constraint that my algorithm must return the elements back to S in their original order. The compulsion is that I may only use S, Q, and a constant number of other variables.
I have implemented this algorithm having used a temporary stack to hold elements and then return them to the original stack in their original order but how do I accomplish this task without using a temporary stack?
if __name__ == '__main__':
def scan(S, Q, x):
for i in range(10):
S.push(i)
S1 = ArrayStack()
flag = False
for i in range(len(S)):
Q.enqueue(S.pop())
if Q.first() == x:
flag = True
print("Your desired element has been found:", Q.first())
S1.push(Q.dequeue())
break
else:
S1.push(Q.dequeue())
if flag == False:
print("Sadly, your desired element could not be found.")
for i in range(len(S1)):
S.push(S1.pop())
scan(ArrayStack(), LinkedQueue(), 9)
The trick is to first put the elements from the queue back on the stack -- which will put them in reversed order -- but then repeat the process again for the same number of values: pop them from the stack into the queue and then flush the queue back to the stack again. Now they will be back in their original order.
Not sure whether the function's signature has been given to you like that, but I would not pass Q as argument, since it only serves the function's algorithm, not the caller. On the other hand, I would not initialise the stack inside the function, but let the caller deal with populating the stack. That way the caller controls which stack data to call the function with.
So this is what you could do:
def scan(S, x):
Q = LinkedQueue() # Create the queue here
found = False
for i in range(len(S)):
Q.enqueue(S.pop())
found = Q.first() == x
if found:
break
i += 1 # The number of values that are currently in the queue
# Flush the queue on the stack
for j in range(i):
S.push(Q.dequeue())
# They are reversed on the stack, so remove them again
for j in range(i):
Q.enqueue(S.pop())
# and finally flush the queue again
for j in range(i):
S.push(Q.dequeue())
return found
Call like this:
S = ArrayStack()
# Initialise the stack here
for i in range(10):
S.push(i)
# Get the boolean result from the function call
found = scan(S, 12)
# Use it to display a message
if found:
print("Your desired element has been found")
else:
print("Sadly, your desired element could not be found.")
Could anyone provide insight into why my program keeps terminating when I am trying to break?
Below is the prompt:
Write a function that returns a list of numbers, say make_list. make_list will not take any arguments. In the function body, construct an empty list and then prompt the user to enter a nonnegative number, -999 to quit. You will need a loop. If the user enters a number other than -999, add it to the list. Once the user enters -999, quit the loop and return the list. (Do not include -999 in the list.)
Write another function, say sum_list, that takes a list of numbers as an argument and returns the sum of the list of numbers. If the list is empty return 0. Do not use the built-in sum function. Use a loop.
You need to call both functions. First call the make_list function. Then use the returned list as the argument for the sum_list function. Print the result.
My solution:
def make_list():
i=[]
while(True):
n=int(input("Enter a number (-999 to quit): "))
if n==-999:
break
i+=[n]
return i
def sum_list(i):
if len(1)==0:
return 0
sum1=0
for k in i:
sum1+=k
return sum1
i=make_list()
s=sum_list(i)
print("Sum :", s)
Write a loop that reads positive integers from standard input and that terminates when it reads an integer that is not positive. After the loop terminates, it prints out, on a line by itself, the sum of all the even integers read.
number =int(input())
even_number = 0
while number >= 0:
if number % 2 == 0:
even_number += number
print(even_number)
number = int(input())
it says:
Exception occurred(, EOFError('EOF when reading a line',), )
Exception occurred(, EOFError('EOF when reading a line',), )
The value of _stdout is incorrect.
We think you might want to consider using: >
We think you might want to consider using: sum
We think you might want to consider using: +
Solutions with your approach don't usually use: +=
After the loop terminates, it prints out, on a line by itself, the sum of all the even integers read.
You seem to be printing each time the sum is updated, instead of just once at the end of the loop. Try moving the print to after the while block.
I read such a minimal demonstration about coroutine A Curious Course on Coroutines and Concurrency
def countdown(n):
print("Counting down from", n)
while n > 0:
yield n
n -= 1
#why it stop?
x = countdown(10)
#no output was produced
I print no result, when first call it.
In [10]: x
Out[10]: <generator object countdown at 0x1036e4228>
but should
In [14]: next(x)
Out[14]: Counting down from 10
In [15]: next(x)
Out[15]: 1
In [16]: next(x)
Why print("Counting down from", n)not executed directly when i invoke the function countdown().
I think the Counting down from 10 should be executed whatever yield, it is a sequential process.
What stop print("Counting down from", n) running, I am aware that
do something yield
yield will stop the action ahead of it,
but in the countdown example, how could yield stop print("Counting down from", n) by penetrating the while loop
If I understand your question correctly, you expect to see the Counting down from 10 text printed out immediately when you call countdown(10). But that reflects a misunderstanding of how generator functions work.
A yield expression isn't something that just interrupts the control flow of a normal function. Rather, any function that contains a yield anywhere in it becomes a generator function, which works differently than a normal function.
When you call a generator function, none of its code runs immediately. Instead, Python just creates a generator object that encapsulates the state of the function call (which at first will just record that you're at the very top of the function which hasn't started running yet). The generator object is what gets returned to the caller.
It is only after you call next on the generator object that function's code starts to run. It will run until it comes to a yield expression, and the value being yielded is what the next will return. The state of the running function is saved as part of the generator object, and it remains paused until you call next on it again.
The important thing to note is that the generator object doesn't ever run ahead of a yield until the outside code is done with the yielded value and asks for another one. We use generator functions specifically because they are lazy!
Here's a simple script that might help you understand how it works better than your example generator that tries to do something more useful:
import time
def generator_function():
print("generator start")
yield 1
print("generator middle")
yield 2
print("generator end")
print("creating the generator")
generator_object = generator_function()
print("taking a break")
time.sleep(1)
print("getting first value")
val1 = next(generator_object)
print("got", val1)
print("taking a break")
time.sleep(1)
print("getting second value")
val2 = next(generator_object)
print("got", val2)
print("taking a break")
time.sleep(1)
print("try getting a third value (it won't work)")
try:
val3 = next(generator_object) # note, the assignment never occurs, since next() raises
print("got", val3) # this line won't ever be reached
except Exception as e:
print("got an exception instead of a value:", type(e))
The print statements from the generator will always appear between the "getting" and "got" messages from the outer code.
I am new to python and i have written the code below but there are 2 to 3 problems with it .
While loop does not print the else statement when
ever i enter 6 or 7 it again asks for input .
Once while loop was started for one function for
example addTwoNumbers it would remain in it that i have handled
through the return is there any other way to do that also ?
Thanks
def main():
choice=menu()
while choice!='5':
num1=int(input("enter first number: "))
num2=int(input("enter the second number: "))
if choice=='1':
total= addTwoNumber(num1,num2)
print("sum of two numbers is: ",total)
conti=contin()
return
elif choice=='2':
sub=minTwoNumber(num1,num2)
print("num1-num2",sub)
conti=contin()
return
elif choice=='3':
quo,remain=qrTwoNumber(num1,num2)
print(quo)
print(remain)
conti=contin()
return
else:
print("Wrong Option.Kindly choose between 1 to 4 : ")
choice=menu()
def menu():
print("Welcome to the menu.Kindly choose from below: ")
print("1.To add two numbers: ")
print("2.To subtract two numbers: ")
print("3.For quotient and remainder :")
print("4.Exit Program")
opt=input("Enter number between 1-4")
if opt=='4':
print('Exiting program')
return opt
def addTwoNumber(n1,n2):
sum=n1+n2
return sum
def minTwoNumber(a1,a2):
minus=a1-a2
return minus
def qrTwoNumber(q1,q2):
quotient=q1//q2
remainder=q1%q2
return quotient,remainder
def contin():
con=input("Do you want to continue (Y/N):")
if con=='y' or con=='Y':
choice=menu()
else:
print("Exiting program")
sys.exit()
main()
These are some mistakes:
while choice!='5' should be while choice!='4'
You are returning after if statements. That exits from the loop.
In that if statements you are calling contin() but storing the return value in conti but you are not using it. It should be choice.
In the contin() you are not returning the choice.
Your problems are related, the control flow of your program is mixed up, and you need to be aware of variable scope. As a short example your menu is doing this:
def main():
choice = 5
print(choice)
contin()
print(choice)
def contin():
choice = 10
main()
It sets 'choice' in the top main function, and then tries to change it later on in the contin function. Those are actually two different variables with the same name. The variable scope is only inside the function where the value was set.
Therefore, since the value of choice never changes in main(), the while loop can never quit, the math function can never be different, and you are stuck doing the same math function over and over again.
And the way the program needs to work is like this:
menu
-> choice
-> numbers
-> math
<-
menu
-> choice
-> numbers
-> math
<-
menu
-> choice
-> numbers
-> math
<-
menu
# you quit here, and the program exits
But your code goes into conti() which then goes into main() again, so it gets more and more nested, like this:
menu
-> choice
-> numbers
-> math
-> menu
-> choice
-> numbers
-> math
-> menu
-> choice
-> numbers
-> math
-> menu
# you try to quit here but end up
choice #back at this level
That means that when you eventually press 7 to quit the menu, instead of exiting the program, you exit the last conti() call and are put back up to the top of the while loop, and prompted for more numbers.
The real issue with your code is that the control flow doesn't work how you think it does.
Pretend to be your computer. Take a hard look at your code, looking at it line by line.
The first bit of code that is run is main(). So look at that function.
Inside main, you first call your menu and get a number from your user.
Next, you set up a loop. As long as this first number from the user isn't 5, your loop will run. For now, we'll pretend the user entered 1.
Then you get two numbers as input from your user. That works fine.
Since they entered 1 as the choice, the condition for your first if statement (choice=='1') is true, so the code inside gets run.
You addTwoNumber function is run, and the returned output is stored in total.
Next, you call contin() and store its output in conti. But take a look inside contin(), let's go line-by-line in this function.
You ask the user if they want to continue, and if they enter y (or Y), you call menu() again and store its output in choice, which your loop checks, right? Well, that's not quite right. The thing is, whenever you define a variable in a function, that variable only exists inside that function. Functions can't see the variables inside other functions (unless you pass them as parameters, or you use global variables... but you really shouldn't use global variables). So the choice variable you're using in contin belongs to that function, but there's another, separate variable that also has the name choice for the main function!
To fix this, you can change the choice=menu() line to return menu(). Then change conti=contin() to choice=contin().
Also, you don't need those returns after you call contin(). If you return there, your function will exit, and your loop will stop running.
Here's a portion of your code with the fixes I mentioned. Do you understand why it works? Can you figure out what else has to be changed for everything to be fixed?
def main():
choice = menu()
while choice != '5':
num1 = int(input("enter first number: "))
num2 = int(input("enter the second number: "))
if choice == '1':
total = addTwoNumber(num1, num2)
print("sum of two numbers is: ", total)
choice = contin()
elif choice == '2':
and
def contin():
con = input("Do you want to continue (Y/N):")
if con == 'y' or con == 'Y':
return menu()
else: