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

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

Related

How can I distribute the output of a list I made in python in my notepad

I was trying to solve up a problem that was going on cause my IDE could not retain a sequence of numbers cause of the range function which works as so.
And i made a Previous question about it so this is a follow-up to the question. Here's my list comment on the previous question.
I actually made some adjustments by adding a line; 'My_list = list(range(100)) before applying your code so it actually worked. But it combines the answers without commas, for example 10 does this '0123456789' instead of '0,1,2,3,4,5,.....8,9'. any suggestions?
I decided to post this question not to allow the other question go out of context (as i was advised to).
Any suggestions?
You need to understand how strings works in Python.
Strings are constants (literals) kept in a closed bucket. In official docs you can find that "Strings are immutable sequences of Unicode code points".
But programmers need to change or manipulate text in a programmable way. In your case you want:
"[x1][space][comma][x2][comma]...[xn][space][comma]"
where "xn" is a number, and " ," is constant.
In order to achieve this, in a programmable way, programmers can use "masks" to tell the software where they want to place their changes. One can use string format operators:
"%d , %f" %(my_first_integer, my_float)
[0][1][2][3][4][\0]
# Hey Python, return a string, using the above template,
# but place useful stuff where you find magic keywords.
Which means:
Create a 6 positions sequence;
In [0], place my_integer of type int converted into chr;
In [1], copy " ";
In [2], copy ",".
In [3], copy " ";
In [4], place my_float of type float converted into chr;
In [5], place "\0" so the string is over. (Automatically placed in Python)
There are other ways to do this, i.e., the string object has a handy method called formatto handle this construction:
my_integer = 2
my_string = "{0}*pi = {1}".format(my_integer, my_integer*3.14)
print(my_string)
# 2*pi = 6.28
The programmer will achieve the same final result using one or another startegy.
In Python, as well as in other languages, one can combine strings, concatenate, get sub-strings and so on, using specific methods and/or operators.
In order to keep readability you maybe (I guess) want to place each value in a line. In strings you can use special characters like \n for new lines.
my_list = list(range(100))
# ... useful code here and there ...
with open("output.txt", "w") as o:
o.write("My list:\n")
o.write("\tSize: {0}\n\n".format(len(my_list)))
o.write("\t----start----\n")
for i in range(len(my_list)):
o.write("%d\n" % my_list[i])
o.write("\n\t----end----\n")
# That writes:
# My list:
# Size: 100
#
# ----start----
# 0
# 1
# 2
# 3
...
# 99
#
# ----end----
Remember, this is not a comprehensive guide, but a layman one. I'm skipping a lot of boring words and technical details that you'll better find in Python books and courses.
You just need to insert a comma after printing each number:
my_list = list(range(100))
with open("output.txt", "w") as o:
for i in range(len(my_list)):
o.write("%d," % my_list[i]) # Here, after '%d' you can place a comma, or any text you want

How can i read defined values from a string in python, like i can do in C with scanf

I have a String, which is formatted as following str="R%dC%d" for example Str=R150C123 and i want to save the numeric values in a variable for example in C Language this would be as following:
int c,r;
sscanf(Str,"R%dC%d",&r,&c);
in python i do it like this
c = int(str[str.find("C") + 1:])
r = int(str[:str.find("C")])
is there any other way to do this in python similler to how i've done it in C?
because my way in python takes a to much time to execute.
another example for another String format is: Str="%[A-Z]%d", for example Str= ABCD1293
i want to save 2 values, the first one is an Array or a String and the second one is the numbers
in C i do it like this:
int r;
char CC[2000];
sscanf(s,"%[A-Z]%d",CC,&r)
in Python like this:
for j in x:
if j.isdigit():
r = x[x.find(j):]
CC= x[:x.find(j)]
break
I dont think, that this is an elegant way to solve this kind of task in python.
Can you please help me?
As Seb said, regex!
import re
regex = r"R(\d+)C(\d+)"
test_str = "R150C123"
match_res = re.fullmatch(regex, test_str)
num_1, num_2 = match_res.groups()
num_1 = int(num_1)
num_2 = int(num_2)
you could also do this in a one liner with regex:
import re
s = 'R150C123'
r,c = list(map(int,re.findall('\d+',s)))
the re.findall function creates a list of all the numbers embedded in the string
the map(int,...) function converts each matched number to a int
finally list returns the ints as a list, allowing r&c to be defined in one assignment

Numerical String Conversions in Python Function

I'm currently learning python so I apologize in advance for the messiness of my code. My function is meant to take in a single string and add the string numbers together. i.e. A string argument of 123 will become 1 + 2 + 3 and return 6.
My issue is when I iterate through my list - python keeps indicating that the variable has been referenced before any value has been assigned. However when I print out the values being calculated they are correct. Even more confusing is that when I return them - they are incorrect. I can't seem to work out where I'm going wrong. Could anyone tell me what the issue may be?
Thank you!
listy = []
global total
#Convert number to a list then cycle through the list manually via elements and add them all up
def digit_sum(x):
number= []
number.append(x)
print number
for i in range(len(number)):
result = str(number[i])
print result
#Now it has been converted to a string so we should be able to
#read each number separately now and re-convert them to integers
for i in result:
listy.append(i)
print listy
#listy is printing [5,3,4]
for i in listy:
total += int(i)
return total
print digit_sum(x)
I'm not really sure what's going on in your code there, especially with the messed up indentation, but your problem is easily sovled:
sum(map(int, str(534)))
It makes the number a string, then converts each digit to an int with map, then just sums it all.
If your concern is only about summing a string of numbers, then list comprehension itself would do or as #Maltysen suggested you could use map
sum([int(x) for x in "534"])
pretty simple:
You can use a map or a list comprehension. They are pretty much equivalent. Other people gave an answer using map but I decided to use a list comprehension.
s = "1234567"
sum([int(character) for character in s])
I believe I have worked out what was wrong with my code. As I am still new to Python, I made some very novice mistakes such as not realizing declaring a variable outside the local function would result in the solution not being what I had expected.
Due to my returns being placed incorrectly as well as my listy [] variable being instantiated outside my function, instead of reading each number once, it would read it three times.
This has now been corrected in the code below.
#Convert number to a list then cycle through the list manually via elements and add them all up
def digit_sum(x):
total = 0
number= []
number.append(x)
print number
for i in range(len(number)):
result = str(number[i])
print result
#Now it has been converted to a string so we should be able to
#read each number separately now and re-convert them to integers
for i in result:
listy = []
listy.append(i)
# print listy
#listy is printing [5,3,4]
for i in listy:
print i
total+= int(i)
print total
break
return total
print digit_sum(111)

How do I use variables in a loop with range()? (Python)

I've been searching for quite a while, and I can't seem to find the answer to this. I want to know if you can use variables when using the range() function. For example, I can't get this to work:
l=raw_input('Enter Length.')
#Let's say I enter 9.
l=9
for i in range (0,l):
#Do something (like append to a list)
Python tells me I cannot use variables when using the range function. Can anybody help me?
Since the user inputs is a string and you need integer values to define the range, you can typecast the input to be a integer value using int method.
>> l=int(raw_input('Enter Length: ')) # python 3: int(input('Enter Length: '))
>> for i in range (0,l):
>> #Do something (like append to a list)
You ask user to input a number
l = raw_input('Enter Length: ')
But the problem is that entered number will be presented as a string instead of int. So you have to convert string 2 int
l = int(raw_input('Enter Length: '))
If you use Python 2.X you also can optimize your code - instead of range you might use xrange. It works much faster.
for i in xrange (l):
#Do something (like append to a list)
In Python 3.X xrange was implemented by default
Try this code:
x = int(input("the number you want"))
for i in range(x):

Unable to use int(raw_input()) in 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

Categories