Unable to use int(raw_input()) in python - python

I am trying out this problem in a coding competition. I believe I have solved the problem, but have some problem in taking the input. Help me out here:
Input
The first line of the input contains a single integer T denoting the number of test cases. The description for T test cases follows. Each test case consists of a single line containing two space-separated strings R and S denoting the two recipes.
Now, I have coded the problem and it seems to work, but whenever I directly copy paste the input values, it fails to work by giving this error message
T= int(raw_input())
ValueError: invalid literal for int() with base 10:
'3\nalex axle\nparadise diapers\nalice bob'
Whenever I try to submit the problem, I get an error message. May be they are also copy pasting the input values and checking for the output. My code skeleton goes something like this
def whetherGranama(str1,str2):
return "NO"
#can't give the implementation out yet
T= int(raw_input())
ans=[]
for x in range(0,T):
s=raw_input()
s1,s2=s.split()
ans.append(whetherGranama(s1,s2))
for elem in ans:
print elem
How can I fix the \n error ? I think the entire input is treated as one string.

Split the input, extract the integer the process using the split list
s = raw_input()
s = s.split()
T = int(s[0])
ans=[]
for st in s[1:]:
//Do the rest

If the entire input is being read in as one string, you could try using stdin.readline() instead of raw_input to capture the input stream:
from sys import stdin
T = int(stdin.readline())
Since this is a coding competition however, I'm assuming that speed is of the essence. Since IO operations are computationally expensive, you should actually welcome the opportunity to read all of your input at one time. In other words, it's generally faster to read it in all at once and then parse the input within your code. I guess in your case, it would look something like this (assuming that it comes in all at once by design):
data = raw_input().splitlines()
#(or data = sys.stdin.read().splitlines() or data = list(sys.stdin.readlines()))
T = int(data[0])
S = (s.split() for s in data[1:])

Split your input first and then convert the int:
T, body = raw_input().split("\n", 1)
for x in xrange(int(T)):
...
That will split once and give you the first number item and then the rest of your input string.

Yes the entire string is treated as one input. You can simply store the input as a list and work with the list instead of calling raw_input in your loop, that would look something like this:
def whetherGranama(str1,str2):
return "NO"
#can't give the implementation out yet
input_lines = raw_input().split("\n")
T = int(input_lines[0])
ans=[]
for x in range(1,T):
s = input_lines[x]
s1,s2=s.split()
ans.append(whetherGranama(s1,s2))
for elem in ans:
print elem

Related

Python: Display all even numbers between two integers inclusive, with a limit the number of times the code accepts input

Link to question: https://www.spoj.com/UTPEST22/problems/UTP_Q2/
From what I understand, the question is divided into 2 parts:
Input
The first input is an integer that limits the number of time the user can provide a set of integers.
From the second line onwards, the user provides the sequence of integers up until the specified limit.
The set of integers are arranged in ascending order, separated only by a space each.
Output
For each sequence of integers, the integers in it are looped over. Only those that are even are printed as outputs horizontally.
from sys import stdin
for x in range(1, 1+ int(input())):
# number of cases, number of times the user is allowed to provide input
for line in stdin:
num_list = line.split()
# remove the space in between the integers
num = [eval(i) for i in num_list]
# change the list of numbers into integers each
for numbers in range(num[0], num[-1] + 1):
# the first integer is the lower bound
# the second the upper bound
if numbers % 2 == 0:
# modulo operation to check whether are the integers fully divisible
print(numbers, end = ' ')
# print only the even numbers, horizantally
Can anyone please provide some insights on how to make changes to my code, specifically the loop. I felt so messed up with it. Screenshot of the result.
Any help will be appreciated.
You can use restructure the code into the following steps:
Read each case. You can use the input function here. A list comprehension can be used to read each line, split it into the lower and upper bound and then convert these to integers.
Process each case. Use the lower and upper bounds to display the even numbers in that range.
Using loops: Here is an example solution that is similar to your attempt:
n = int(input())
cases = []
for case in range(n):
cases.append([int(x) for x in input().split()])
for case in cases:
for val in range(case[0], case[1] + 1):
if val % 2 == 0:
print(val, end=' ')
print()
This will produce the following desired output:
4 6 8 10 12 14 16 18 20
2 4 6 8 10 12 14 16
-4 -2 0 2 4 6
100 102 104 106 108
Simplify using unpacking: You can simplify this further by unpacking range. You can learn more about unpacking here.
n = int(input())
cases = []
for case in range(n):
cases.append([int(x) for x in input().split()])
for case in cases:
lower = case[0] if case[0] % 2 == 0 else case[0]
print(*range(lower, case[1] + 1, 2))
Simplify using bit-wise operators: You can simplify this further using the bit-wise & operator. You can learn more about this operator here.
n = int(input())
cases = []
for case in range(n):
cases.append([int(x) for x in input().split()])
for case in cases:
print(*range(case[0] + (case[0] & 1), case[1] + 1, 2))
So first of obviously ask user to input the range however many times they specified, you can just split the input and then just get the first and second item of that list that split will return, by using tuple unpacking, then append to the ranges list the range user inputted but as a Python range object so that you can later easier iterate over it.
After everything's inputted, iterate over that ranges list and then over each range and only print out the even numbers, then call print again to move to a new line in console and done.
ranges = []
for _ in range(int(input())):
start, end = input().split()
ranges.append(range(int(start), int(end) + 1))
for r in ranges:
for number in r:
if number % 2 == 0:
print(number, end="")
print()
Here's my solution:
n = int(input())
my_list = []
for i in range(n):
new_line = input().split()
new_line = [int(x) for x in new_line]
my_list.append(new_line)
for i in my_list:
new_string = ""
for j in range(i[0], i[1]+1):
if (not(j % 2)): new_string += f"{j} "
print(new_string)
Read the first value from stdin using input(). Convert to an integer and create a for loop based on that value.
Read a line from stdin using input(). Assumption is that there will be two whitespace delimited tokens per line each of which represents an integer.
Which gives us:
N = int(input()) # number of inputs
for _ in range(N):
line = input()
lo, hi = map(int, line.split())
print(*range(lo+(lo&1), hi+1, 2))
There are a few issues here but I'm guessing this is what's happening: you run the code, you enter the first two lines of input (4, followed by 3 20) and the code doesn't print anything so you press Enter again and then you get the results printed, but you also get the error.
Here is what's actually happening:
You enter the input and the program prints everything as you expect but, you can't see it. Because for some reason when you use sys.stdin then print without a new line, stdout does not flush. I found this similar issue with this (Doing print("Enter text: ", end="") sys.stdin.readline() does not work properly in Python-3).
Then when you hit Enter again, you're basically sending your program a new input line which contains nothing (equivalent to string of ""). Then you try to split that string which is fine (it will just give you an empty list) and then try to get the first element of that list by calling num[0] but there are no elements in the list so it raises the error you see.
So you can fix that issue by changing your print statement to print(numbers, end = ' ', flush=True). This will force Python to show you what you have printed in terminal. If you still try to Enter and send more empty lines, however, you will still get the same error. You can fix that by putting an if inside your for loop and check if line == "" then do nothing.
There is still an issue with your program though. You are not printing new lines after each line of output. You print all of the numbers then you should go to the newline and print the answer for the next line of input. That can be fixed by putting a print() outside the for loop for numbers in range(num[0], num[-1] + 1):.
That brings us to the more important part of this answer: how could you have figured this out by yourself? Here's how:
Put logs in your code. This is especially important when solving this type of problems on SPOJ, Codeforces, etc. So when your program is doing that weird thing, the first thing you should do is to print your variables before the line of the error to see what their value is. That would probably give you a clue. Equally important: when your program didn't show you your output and you pressed Enter again out of confusion, you should've gotten curious about why it didn't print it. Because according to your program logic it should have; so there already was a problem there.
And finally some side notes:
I wouldn't use eval like that. What you want there is int not eval and it's just by accident that it's working in the same way.
We usually put comments above the line not below.
Since it appears you're doing competitive programming, I would suggest using input() and print() instead of stdin and stdout to avoid the confusions like this one.
SPOJ and other competitive programming websites read your stdout completely independent of the output. That means, if you forget to put that empty print() statement and don't print new lines, your program would look fine in your terminal because you would press Enter before giving the next input line but in reality, you are sending the new line to the stdin and SPOJ will only read stdout section, which does not have a new line. I would suggest actually submitting this code without the new line to see what I mean, then add the new line.
In my opinion, the variable numbers does not have a good name in your code. numbers imply a list of values but it's only holding one number.
Your first if does not need to start from 1 and go to the number does it? It only needs to iterate that many times so you may as well save yourself some code and write range(int(input())).
In the same for loop, you don't really care about the value of variable x - it's just a counter. A standard practice in these situations is that you put _ as your variable. That will imply that the value of this variable doesn't really matter, it's just a counter. So it would look like this: for _ in range(int(input())).
I know some of these are really extra to what you asked for, but I figured you're learning programming and trying to compete in contests so thought give some more suggestions. I hope it helped.
Steps for simple solution
# taking input (number of rows) inside outer loop
# l = lower limit, u = upper limit, taking from user, then converting into integer using map function
# applying logic for even number
# finally printing the even number in single line
for j in range(int(input())):
l, u = map(int, input('lower limit , upper limit').split())
for i in range(l, u+1):
if i%2 == 0: # logic for even number
print(i, end=' ')

Am I using a Python loop wrongly or am I just missing something?

I am currently a beginner in Python. This is my problem: First, the program asks that you input a number.
For example, if I put 1, I get 1 out. If i put 2, i get 12 out. If I put 3, I get 123. If I put 4, I get 1234. That is the gist of this set of problem. However, I developed a mathematical equation that works if I put it through a loop:
if __name__ == '__main__': # ignore this part
n = int(input())
s = 1
while s > n:
z = s*10**(n-s)
s += 1
answer = z
if s == n:
print(z)
When I tried to run this code, I got nothing, even though I added print at the end. What is it that I am doing wrong here? For anyone answering the problem, introduce any concepts that you know that may help me; I want to learn it.
Please enlighten me. Don't exactly give me the answer....but try to lead me in the right direction. If I made a mistake in the code (which I am 100% sure I did), please explain to me what's wrong.
It's because your while loop condition is backwards. It never enters the loop because s is not bigger than n. It should be while s < n
Use a for loop using range() as in
for i in range(1, n+1):
where n is the input so that the numbers from 1 till n can be obtained.
Now use a print() to print the value of i during each iteration.
print() by default will add a newline at the end. To avoid this, use end argument like
print(var, end='')
Once you are familiar with this, you can also use list comprehension and join() to get the output with a single statement like
print( ''.join([str(i) for i in range(1, n+1)]) )
Take the input as you've done using input() and int() although you might want to include exception handling in case the input is not an integer.
See Error handling using integers as input.
Here is the solution:
Using string
a = int(input())
# taking the input from the user
res=''
# using empty string easy to append
for i in range(1,a+1):
# taking the range from 1 (as user haven't said he want 0, go up to
# a+1 number (because range function work inclusively and will iterate over
# a-1 number, but we also need a in final output ))
res+=str(i)
# ^ appending the value of I to the string variable so for watch iteration
# number come append to it.
# Example : 1-> 12-> 123-> 1234-> 12345-> 123456-> 1234567-> 12345678-> 123456789
# so after each iteration number added to it ,in example i have taken a=9
sol = int(res) #converting the res value(string) to int value (as we desire)
print(sol)
In one line, the solution is
a=int(input())
res=int(''.join([str(i) for i in range(1,a+1)]))
Try this,
n = int(input('Please enter an integer'))
s = 1
do:
print(s)
s+=1
while s == n
this works.
(Simple and Short)

Python not detecting a single letter, but detects two letters fine

This is the code I am using to detect if a string contains letters. If none are detected, it allows the program to convert the string to a float. The idea was that I could stop the program from crashing after attempting to convert a string with letters to a float.
for i in range(1, len(argument)):
if argument[i].isalpha():
return False
print("Ran option 1")
else:
return True
print("Ran option 2")
The print lines are just to help me see which part is being executed. As it turns out, neither of them are.
http://puu.sh/ivVI7/8598b82fe8.png
This is a screenshot of the output. In the first half, it detects the "aa" string and does not crash the code. However, in the second half, it fails to detect the single "a" and attempts to convert it to a float, crashing the program. If anybody could lend a hand, it would be greatly appreciated.
If it helps, the rest of the code is here: http://pastebin.com/Cx7HbM4c
You have the print lines after the return command, so they will never be executed. Move the print above the return.
You can also make your code more pythonic and more readable:
for char in argument:
return char.isalpha()
Python strings are 0-based. The test never checks the first character in the string.
for i in range(0, len(argument)):
Filing that knowledge away, the python way (for char in argument) as shown in answers from #DeepSpace and #helmbert seems cleaner.
In Python, arrays are zero-indexed. This means, you need to start iterating at 0, not at 1!
You can reproduce this easily by simply adding a print(argument[i]) into your loop body:
def func(argument):
for i in range(1, len(argument)):
print(argument[i])
func("a") # Prints nothing
func("ab") # Prints "b"
Keeping as closely as possible to your original code, simply start iterating at 0 instead of 1:
for i in range(0, len(argument):
# ...
Easier yet, you can also iterate a string directly:
for character in argument:
print(character) # Will print every single character
# ...
Ok, if you try to find out can you convert string or not, why don't you use function like this:
def convertable(value):
try:
float(value)
return True
except ValueError:
return False
if all you want is to prevent your program from crashing, exceptions are your friends:
argument = "abc"
try:
value = float(argument)
except ValueError as e:
print e, "is unacceptable"
else:
print value, "is acceptable as a float"
finally:
print "alright"
outputs:
could not convert string to float: abc is unacceptable
alright
whereas, if argument = "3.14"
it outputs:
3.14 is acceptable as a float
alright
Of course, you can put all that logic into a function, in case you need to do it many times across your program.
Have fun!

Taking multiple integers on the same line as input from the user in python

I know how to take a single input from user in python 2.5:
raw_input("enter 1st number")
This opens up one input screen and takes in the first number. If I want to take a second input I need to repeat the same command and that opens up in another dialogue box.
How can I take two or more inputs together in the same dialogue box that opens such that:
Enter 1st number:................
enter second number:.............
This might prove useful:
a,b=map(int,raw_input().split())
You can then use 'a' and 'b' separately.
How about something like this?
user_input = raw_input("Enter three numbers separated by commas: ")
input_list = user_input.split(',')
numbers = [float(x.strip()) for x in input_list]
(You would probably want some error handling too)
Or if you are collecting many numbers, use a loop
num = []
for i in xrange(1, 10):
num.append(raw_input('Enter the %s number: '))
print num
My first impression was that you were wanting a looping command-prompt with looping user-input inside of that looping command-prompt. (Nested user-input.) Maybe it's not what you wanted, but I already wrote this answer before I realized that. So, I'm going to post it in case other people (or even you) find it useful.
You just need nested loops with an input statement at each loop's level.
For instance,
data=""
while 1:
data=raw_input("Command: ")
if data in ("test", "experiment", "try"):
data2=""
while data2=="":
data2=raw_input("Which test? ")
if data2=="chemical":
print("You chose a chemical test.")
else:
print("We don't have any " + data2 + " tests.")
elif data=="quit":
break
else:
pass
You can read multiple inputs in Python 3.x by using below code which splits input string and converts into the integer and values are printed
user_input = input("Enter Numbers\n").split(',')
#strip is used to remove the white space. Not mandatory
all_numbers = [int(x.strip()) for x in user_input]
for i in all_numbers:
print(i)
a, b, c = input().split() # for space-separated inputs
a, b, c = input().split(",") # for comma-separated inputs
You could use the below to take multiple inputs separated by a keyword
a,b,c=raw_input("Please enter the age of 3 people in one line using commas\n").split(',')
The best way to practice by using a single liner,
Syntax:
list(map(inputType, input("Enter").split(",")))
Taking multiple integer inputs:
list(map(int, input('Enter: ').split(',')))
Taking multiple Float inputs:
list(map(float, input('Enter: ').split(',')))
Taking multiple String inputs:
list(map(str, input('Enter: ').split(',')))
List_of_input=list(map(int,input (). split ()))
print(List_of_input)
It's for Python3.
Python and all other imperative programming languages execute one command after another. Therefore, you can just write:
first = raw_input('Enter 1st number: ')
second = raw_input('Enter second number: ')
Then, you can operate on the variables first and second. For example, you can convert the strings stored in them to integers and multiply them:
product = int(first) * int(second)
print('The product of the two is ' + str(product))
In Python 2, you can input multiple values comma separately (as jcfollower mention in his solution). But if you want to do it explicitly, you can proceed in following way.
I am taking multiple inputs from users using a for loop and keeping them in items list by splitting with ','.
items= [x for x in raw_input("Enter your numbers comma separated: ").split(',')]
print items
You can try this.
import sys
for line in sys.stdin:
j= int(line[0])
e= float(line[1])
t= str(line[2])
For details, please review,
https://en.wikibooks.org/wiki/Python_Programming/Input_and_Output#Standard_File_Objects
Split function will split the input data according to whitespace.
data = input().split()
name=data[0]
id=data[1]
marks = list(map(datatype, data[2:]))
name will get first column, id will contain second column and marks will be a list which will contain data from third column to last column.
A common arrangement is to read one string at a time until the user inputs an empty string.
strings = []
# endless loop, exit condition within
while True:
inputstr = input('Enter another string, or nothing to quit: ')
if inputstr:
strings.append(inputstr)
else:
break
This is Python 3 code; for Python 2, you would use raw_input instead of input.
Another common arrangement is to read strings from a file, one per line. This is more convenient for the user because they can go back and fix typos in the file and rerun the script, which they can't for a tool which requires interactive input (unless you spend a lot more time on basically building an editor into the script!)
with open(filename) as lines:
strings = [line.rstrip('\n') for line in lines]
n = int(input())
for i in range(n):
i = int(input())
If you dont want to use lists, check out this code
There are 2 methods which can be used:
This method is using list comprehension as shown below:
x, y = [int(x) for x in input("Enter two numbers: ").split()] # This program takes inputs, converts them into integer and splits them and you need to provide 2 inputs using space as space is default separator for split.
x, y = [int(x) for x in input("Enter two numbers: ").split(",")] # This one is used when you want to input number using comma.
Another method is used if you want to get inputs as a list as shown below:
x, y = list(map(int, input("Enter the numbers: ").split())) # The inputs are converted/mapped into integers using map function and type-casted into a list
Try this:
print ("Enter the Five Numbers with Comma")
k=[x for x in input("Enter Number:").split(',')]
for l in k:
print (l)
How about making the input a list. Then you may use standard list operations.
a=list(input("Enter the numbers"))
# the more input you want to add variable accordingly
x,y,z=input("enter the numbers: ").split( )
#for printing
print("value of x: ",x)
print("value of y: ",y)
print("value of z: ",z)
#for multiple inputs
#using list, map
#split seperates values by ( )single space in this case
x=list(map(int,input("enter the numbers: ").split( )))
#we will get list of our desired elements
print("print list: ",x)
hope you got your answer :)

Read two variables in a single line with Python [duplicate]

This question already has answers here:
Get a list of numbers as input from the user
(11 answers)
Closed 20 days ago.
I am familiar with the input() function, to read a single variable from user input. Is there a similar easy way to read two variables?
I'm looking for the equivalent of:
scanf("%d%d", &i, &j); // accepts "10 20\n"
One way I am able to achieve this is to use raw_input() and then split what was entered. Is there a more elegant way?
This is not for live use. Just for learning..
No, the usual way is raw_input().split()
In your case you might use map(int, raw_input().split()) if you want them to be integers rather than strings
Don't use input() for that. Consider what happens if the user enters
import os;os.system('do something bad')
You can also read from sys.stdin
import sys
a,b = map(int,sys.stdin.readline().split())
I am new at this stuff as well. Did a bit of research from the python.org website and a bit of hacking to get this to work. The raw_input function is back again, changed from input. This is what I came up with:
i,j = raw_input("Enter two values: ").split()
i = int(i)
j = int(j)
Granted, the code is not as elegant as the one-liners using C's scanf or C++'s cin. The Python code looks closer to Java (which employs an entirely different mechanism from C, C++ or Python) such that each variable needs to be dealt with separately.
In Python, the raw_input function gets characters off the console and concatenates them into a single str as its output. When just one variable is found on the left-hand-side of the assignment operator, the split function breaks this str into a list of str values .
In our case, one where we expect two variables, we can get values into them using a comma-separated list for their identifiers. str values then get assigned into the variables listed. If we want to do arithmetic with these values, we need to convert them into the numeric int (or float) data type using Python's built-in int or float function.
I know this posting is a reply to a very old posting and probably the knowledge has been out there as "common knowledge" for some time. However, I would have appreciated a posting such as this one rather than my having to spend a few hours of searching and hacking until I came up with what I felt was the most elegant solution that can be presented in a CS1 classroom.
Firstly read the complete line into a string like
string = raw_input()
Then use a for loop like this
prev = 0
lst = []
index = 0
for letter in string :
if item == ' ' or item == '\n' :
lst.append(int(string[prev:index])
prev = index + 1
This loop takes a full line as input to the string and processes the parts in it individually and then appends the numbers to the list - lst after converting them to integers .
you can read 2 int values by using this in python 3.6.1
n,m = map(int,input().strip().split(" "))
You can also use this method for any number of inputs. Consider the following for three inputs separated by whitespace:
import sys
S = sys.stdin.read()
S = S.split()
S = [int(i) for i in S]
l = S[0]
r = S[1]
k = S[2]
or you can do this
input_user=map(int,raw_input().strip().split(" "))
You can use this method for taking inputs in one line
a, b = map(int,input().split())
Keep in mind you can any number of variables in the LHS of this statement.
To take the inputs as string, use str instead of int
And to take list as input
a = list(map(int,input.split()))
in python 3.9 , use a, b = map(int,input().split())
because you will get raw_input() not defined

Categories