Python program keeps taking input - python

def main():
n = int(input().strip())
a = list(map(int, input().rstrip().split()))
b = list(map(int, input().rstrip().split()))
a.sort()
b.sort()
total=0
i=0
j=0
while i!=len(a):
while j!=len(b):
# print('a[i]', a[i],'b[j]',b[j])
if a[i]<b[j]:
# print('in a[i]<b[j]')
i+=1
break
if a[i]==b[j]:
total+=1
i+=1
j+=1
# print('total is ',total)
break
else:
# print('in else')
j+=1
if total==n:
print(n)
else:
print(total+1)
main()
Input:
4
1 2 3 4
1 2 3 3
The program keeps asking for input even after i press the "enter" button on my keyboard. while for other types of input it works perfectly fine

Your program is not taking any more inputs, it just runs in an infinite loop in your while statement because of the last digits of a and b namely 4 and 3.
For the first 3 digits 1 2 3, the value of i and j are both 3.
Then while comparing the last digits 4 and 3, it isn't True for this
if a[i]<b[j]:
Nor this
if a[i]==b[j]:
Thus it executed else which only increments j making i=3 and j=4.
Now you're stuck because it will never go inside the inner while loop (since j is already 4) which means it will never increment i again thus will never reach the length of 4.
while i!=len(a):
while j!=len(b):
Want proof? switch your inputs for a and b
1
1 2 3 3
1 2 3 4

def getInput(n): #another method.
a = list()
for x in range(n):
a.append(input().rstrip().split())
return a
def main():
n = int(input().strip())
a = getInput(n)
b = getInput(n)
a.sort()
b.sort()
total=0
i=0
j=0
while i!=len(a):
while j!=len(b):
# print('a[i]', a[i],'b[j]',b[j])
if a[i]<b[j]:
# print('in a[i]<b[j]')
i+=1
break
if a[i]==b[j]:
total+=1
i+=1
j+=1
# print('total is ',total)
break
else:
# print('in else')
j+=1
if total==n:
print(n)
else:
print(total+1)
main()
The first problem is that your question is quite imprecise. You've said it stops taking input but have also expressed the idea that it runs infinitely. These cannot both be true given what we have here.
The problem with getting input was that you called map() with int and list().rstrip().split(), as 1st and 2nd arguments when the Python library states that the function requires the method you want to call as 1st arg and the 2nd must be an iterable, or a collection as per:
https://docs.python.org/3/library/functions.html#map
So if you wanted to use map() you also needed to have a list full of items because map() uses the provided function on each value in the given list. in other words: you needed data to run map() on prior to calling it.
I am assuming that you're implementing an algorithm and the print()'s executed properly when I ran it with them uncommented. My solution above should at least allow you to get back to developing your algorithm.
I simply deferred the call to a method defined called getInput() which takes the number of values to take (n) and returns the list of them retrieved from the input.

Related

Need help properly executing a "break" statement in python

I have some code which gives me the answer I want, but I'm having trouble stopping it once I get the
answer I want.
Here's my code:
multiples = range(1,10)
n = 1
while n>0:
for i in multiples:
if n%i!=0:
n = n + 1
continue
elif n%10==0:
print(n)
This is an attempt at solving problem 5 of Project Euler. Essentially, I'm supposed to get the smallest multiple of all the digits within a given range.
Now, when i run the above code using the example given (1-10 should yield 2520 as the smallest multiple), i get the answer right. However, the code continues to run infinitely and print the answer without breaking. Also, the moment I add the break statement to the end like so:
multiples = range(1,10)
n = 1
while n>0:
for i in multiples:
if n%i!=0:
n = n + 1
continue
elif n%10==0:
print(n)
break
The code just keeps spamming the number 30. Any ideas why this is happening. For the record, I'm not really looking for an alternative solution to this question (the goal is to learn after all), but those are welcome. What I want to know most of all is where I went wrong.
You never break out of your while loop. The for is the entire while body. break interrupts only the innermost loop; you have no mechanism to leave the while loop. Note that your continue doesn't do anything; it applies to the for loop, which is about to continue, anyway, since that's the last statement in the loop (in that control flow).
I can't really suggest a repair for this, since it's not clear how you expect this to solve the stated problem. In general, though, I think that you're a little confused: you use one loop to control n and the other to step through divisors, but you haven't properly tracked your algorithm to your code.
One way to deal with this is to have an exception. At best a custom one.
multiples = range(1,10)
n = 1
class MyBreak(Exception):
pass
while n>0:
try:
for i in multiples:
if n%i!=0:
n = n + 1
continue
elif n%10==0:
print(n)
raise MyBreak()
except MyBreak:
# now you are free :)
break
With this brake you stop only for loop, to exit whole cycle you should create trigger variable, for example:
multiples = range(1,10)
n = 1
tg = 0
while n>0:
for i in multiples:
if n%i!=0:
n = n + 1
continue
elif n%10==0:
print(n)
tg = 1
break
if tg != 0:
break
Or it'll be better to use a function and stop a cycle by return:
def func():
multiples = range(1,10)
n = 1
while n>0:
for i in multiples:
if n%i!=0:
n = n + 1
continue
elif n%10==0:
print(n)
return n

Change in variable values upon recursion, Python 3

Hey so im pretty new to programming in general and I was having a crack at a question I found for the collatz function,
The code I wrote after some trial and error is as follows:
def collatz(number):
if number % 2 == 0:
number = number//2
print(number)
return number
elif number%2 != 0:
number = 3*number + 1
print(number)
return number
n = int(input("plz enter the number:"))
while n != 1:
n = collatz(n)
Output:
plz enter the number:3
10
5
16
8
4
2
1
This code works but im not sure how the variable values are being alloted, cuz after running this program I can see that in the shell "number = 3" but "n = 1", why is this the case? Shouldnt "number" also equal to 1? Because I am returning the value of number within the function?
Also just to clear my concepts, at the initial moment when I input n = 3, at that moment n = number = 3, then does this returned value of "number" automatically become the new value of n, when i call it in the while loop?
Just wanted to check cuz im a little weak when it comes to doing stuff that needs to pass parameters.
edit:
Why is this case diff then what was just answered?
def testfile(number):
number = number -1
print(number)
return number
n = int(input("enter:"))
while n != 2:
n = testfile(n)
Output:
enter:5
4
3
2
When the input is given as n = 5, then why does number = 3 instead of 5 as was just explained below?
Here's how your program works.
You ask for a number and store it in variable n.
You open a loop which continues until n is 1
Every time the loop repeats, you're calling your function and passing a COPY of n. If you add one to the copy inside the function, your original n will not change.
The COPY is called number. You perform your little tricks with number, output it to the screen, and here's the confusing part: you return a copy of number right back to your loop. And where does it go? It goes right back to n. This overwrites whatever was in n previously.

python for loop function output bring the same result over and over

I wrote a function that check the validity of id
there is an algorithm that perform few calculation-first make sure that the len of the id is 9 then other calculation, the result should be divided by 10 and then the output will be True or False
list6 includes list of if list6=[21544622,301038725]
calling the function manually will bring the right result True or False, however in the loop something go wrong and get the same result
l=[]
ls=[]
count=0
num=[1,2,1,2,1,2,1,2,1]
d=[]
list3=[]
def check_id(s):
b=0
z=0
s=str(s)
if len(s)<6:
print("wrong id")
elif len(s)==6:
s='000'+s
elif len(s)==7:
s='00'+s
elif len(s)==8:
s='0'+s
else:
pass
for digit in s:
l.append(int(digit))
b=list(zip(l,num))
for k,v in b:
d.append(k*v)
for n in d:
n=str(n)
if len(n)==2:
n=int(n[0])+int(n[1])
else:
n=int(n)
list3.append(n)
z=sum(list3)
return z%10==0
for x in list6:
check=0
check=check_id(s=x)
print(check)
after few testing while I printed each step , I found my problem
I need to split each ID to different digits and then multiply it by 1 or 2
I missed this step and now this should work

Collatz Conjecture in Python

I'm relatively new to Python and I decided to try and code a relatively simple collatz conjecture where the user enters a number (integer). The code is just a simple function that calls itself. i is a list that should have every number that the function calculates appended to it. I'm new to executing Python scripts and I have tried using the IDLE shell to run the code. It asks me what number I want but when I enter a number nothing is printed? I'm sure I just need to edit a small bit of this code (or maybe it's all wrong yikes) but does anybody have any idea why my script returns nothing? Sorry about this and thanks.
Here's the code:
l = input("Enter a number: ")
l = int(l)
i = []
def collatz(n):
if n==1:
return i
if n%2 == 0:
n = n/2
i.append(n)
return collatz(n)
else:
n = ((n*3) + 1) / 2
i.append(n)
return collatz(n)
print(i)
collatz(l)
There are three returns before your print and one of them is inside an else statement, which means that at least one of them will be executed, so your print won't even be reached to be executed, you should move it right after the function definition to see something:
def collatz(n):
print(i) # <= print here
if n==1:
....
See more about the return statement. A snippet:
return leaves the current function call with the expression list (or None) as return value.
As others have mentioned, all of the execution paths in your function end in a return statement, so that print call is unreachable. So if you want each value of n or i to be printed you need to move the call to somewhere that it will be reachable. ;)
Also, there's a little bit of redundancy in that code. You don't need
i.append(n)
return collatz(n)
in both the if and else branches, you can move them outside the if...else block.
Here's a modified version of your code. I've also changed the / operators to // so that the results of the divisions will be integers.
i = []
def collatz(n):
print(n)
if n==1:
return i
if n%2 == 0:
n = n // 2
else:
n = ((n*3) + 1) // 2
i.append(n)
return collatz(n)
# Test
print(collatz(12))
output
12
6
3
5
8
4
2
1
[6, 3, 5, 8, 4, 2, 1]

Square number sequence in Python

I'm new to python and I am trying to make a code to print all the square numbers until the square of the desired value entered by the user.
n = raw_input("Enter number")
a = 1
while a < n:
a = 1
print(a*a)
a += 1
if a > n:
break
When I run this code it infinitely prints "1" ... I'm guessing that the value of a does not increase by += so it's a=1 forever. How do I fix this?
There are some problems. First, your input (what raw_input() returns) is a string, so you must convert it to integer:
n = int(raw_input(...))
Second, you are setting a = 1 each iteration, so, since the loop condition is a < n, the loop will run forever ( if n > 1). You should delete the line
a = 1
Finally, it's not necesary to check if a > n, because the loop condition will handle it:
while a < n:
print a * a
a += 1
# 'if' is not necessary
There is a small error in your code:
while a < n:
a=1 # `a` is always 1 :)
print a*a
a += 1
if a > n:
break
You're setting the value of a back to 1 on every iteration of the loop, so every time it checks against n, the value is 2. Remove the a=1 line.
As others have noted, your specific problem is resetting a each time you loop. A much more Pythonic approach to this is the for loop:
for a in range(1, n):
print(a ** 2)
This means you don't have to manually increment a or decide when to break or otherwise exit a while loop, and is generally less prone to mistakes like resetting a.
Also, note that raw_input returns a string, you need to make it into an int:
n = int(raw_input("Enter number: "))
an even better idea is to make a simple function
def do_square(x):
return x*x
then just run a list comprehension on it
n = int(raw_input("Enter #:")) #this is your problem with the original code
#notice we made it into an integer
squares = [do_square(i) for i in range(1,n+1)]
this is a more pythonic way to do what you are trying to do
you really want to use functions to define functional blocks that are easy to digest and potentially can be reused
you can extend this concept and create a function to get input from the user and do some validation on it
def get_user_int():
#a function to make sure the user enters an integer > 0
while True:
try:
n = int(raw_input("Enter a number greater than zero:"))
except TypeError:
print "Error!! expecting a number!"
continue;
if n > 0:
return n
print "Error: Expecting a number greater than zero!"
and then you can build your input right into your list
squares = [do_square(i) for i in range(1,get_user_int()+1)]
and really do_square is such a simple function we could easily just do it in our loop
squares = [x*x for x in range(1,get_user_int())]
The first line in your loop sets's a to one on every iteration.
You assign a=1 inside the loop. That means it's overwriting the a+=1.
try this:
n = eval(raw_input("Enter number"))
a=1
while a < n:
print a*a
a += 1
The issue here is that the value of a gets overridden every time you enter in the loop
Problem is in the condition of the while loop, to print squares of numbers upto a limiting value, try this..
def powers(x):
n=1
while((n**2)<=x):
print(n**2, end =' ')
n +=1

Categories

Resources