Multiline user input with list comprehension in Python 3 - python

Total newb to Python here. I'm working on CodeAbbey's problems using Python 3, and I'd like help to make the code for user input shorter.
Let's say I want to get this input from the user:
3
2 3
4 5
6 7
First line is number of cases, and each of the following lines are the cases themselves with 2 parameters. I've figured out to do it in this way so far:
N=int(input('How many cases will you calculate?\n'))
print('Input parameters separated by spaces:')
entr = [list(int(x) for x in input().split()) for i in range(N)]
The thing is I'd rather to ask all the input in the list comprehension, and then assign N=entr[0]. But how do I get the list comprehension to break the input into lines without using range(N)?
I tried:
entr = [list(int(x) for x in input().split()) for x in input()]
but it doesn't work.

I don't see the benefit of doing this in a list comprehension, but here is a solution that allows all data to be copy-pasted in:
entr = [list(int(x) for x in input().split())
for i in range(int(input()))]
N = len(entr)
Your solution was pretty close. The outer iteration just needed to be given something to iterate on (using range()) rather than a single number.

Yeah you can try this in the list comprehension
cases = [input().split() for _ in range(int(input()))]
flatList = [int(item) for elem in cases for item in elem]
print(flatList)

I simply used this for python list input
n = int(input())
a = [list(map(input().split())) for i in range(n)]
print(a)
'''
3
2 3
4 5
6 7
[[2, 3],[4, 5], [6,7]]
'''
arr = []
for i in range(int(input())):
a = list(map(int,input().split()))
arr.append(a)
print(arr)
'''
3
2 3
4 5
6 7
[[2, 3],[4, 5], [6,7]]'''
''' or in single list '''
arr = []
for i in range(int(input())):
a,b = map(int,input().split())
arr += [a,b]
print(arr)
'''
3
2 3
4 5
6 7
[2,3,4,5,6,7]'''
Im newbie, how can i use this editor for python output console?

Here input is taken as int . But you can change it acc. To your need of input.
And 4 is the no. Of input() you will insert that can also edit acc. To your need
'''enter = list(i for i in (int(input() for i in range(4)))
print(enter)'''

Related

Program that takes two lists and outputs similarity between lists [duplicate]

This question already has answers here:
Get a list of numbers as input from the user
(11 answers)
Closed 10 months ago.
I am writing a program where a user inputs data for two lists ( numbers ) and then the program outputs the matching numbers from both of the lists.
I have written a bit of code to manually achieve this but I need to implement a way where the user can input numbers for themselves instead of just hardcoding them in.
see below desired output:
List 1: 1 2 3 4
List 2: 4 2 0 0
output: [4 , 2 ]
My bellow code achieves the desired result but not how it's intended, my code takes values from a list and calculates the intersection, and prints the result but not as outlined as above.
a = [1,2,3,4]
b = [4,2,0,0]
c = set(a) & set(b)
print('Output:',c)
could you please help and explain how this is achieved. thanks
If you need to keep the order in the list, you can work directly on the lists and use a simple list comprehension:
a = [1,2,3,4]
b = [4,2,0,0]
c = [el for el in b if el in a]
print('Output:',c)
Output:
[4, 2]
EDIT 1. If you want the user to input the numbers one by one, you can do something like this:
n = int(input('Provide the amount of numbers for each list: '))
a = [int(input(f'List a, element {i+1}: ')) for i in range(n)]
b = [int(input(f'List b, element {i+1}: ')) for i in range(n)]
c = [el for el in b if el in a]
print('Output:',c)
For more variants, you can use this as a baseline and add up type checks or variable length arrays (by making user input two initial numbers n and m) and similar.
EDIT 2. If you want the user to input the lists directly, you can do something like this:
a = map(int, input('List 1: ').strip().split()) # e.g. "1 2 3 4"
b = map(int, input('List 2: ').strip().split()) # e.g. "4 2 0 0"
c = [el for el in b if el in a]
print('Output:',c)
I wouldn't recommend this solution as this is easily more prone to user input errors.

How to print two input lists within a list in separate lines without using NumPy?

I have a program which adds two matrices (lists) and prints the sum.
First, the program asks to specify the number of rows and columns as dimensions of the matrices.
Then it asks to enter the specified number of digits as rows and columns, as follows:
dimension: 2 3
numbers in the list: 1 2 3
numbers in the list: 4 5 6
dimension: 2 3
numbers in the list: 7 8 9
numbers in the list: 7 8 9
I am trying to print the sum of two input lists (matrices) exactly in the following format - two rows in separate lines, three columns, without square brackets:
8 10 12
11 13 15
but end up with this output:
[8, 11, 10, 13, 12, 15]
I have tried several other solutions suggested in other similar posts but haven't been able to make them work.
Without using NumPy, map() or lambda functions, how can I get the desired output?
# input the number of rows and columns (dimensions of the matrix)
rows_cols = input().split()
# save the dimensions as integers in a list
matrix_dim = [int(i) for i in rows_cols]
numbers = 0
matrix_A = []
matrix_B = []
matrices = []
# take the row times the input for the rows of matrix_A
for _ in range(matrix_dim[0]):
numbers = input().split()
matrix_A.append([int(i) for i in numbers])
rows_cols = input().split()
matrix_dim = [int(i) for i in rows_cols]
# take the row times the input for the rows of matrix_B
for _ in range(matrix_dim[0]):
numbers = input().split()
matrix_B.append([int(i) for i in numbers])
# add matrices matrix_A and matrix_B
matrices = [matrix_A[i][k] + matrix_B[i][k] for k in range(len(matrix_A[0])) for i in range(len(matrix_A))]
# print ERROR if the number of columns entered exceed the input number for columns
if len(numbers) != matrix_dim[1]:
print("ERROR")
else:
print(matrices)
The easy way to do this will be to start with the fix suggested by nathan:
matrices = [[matrix_A[i][k] + matrix_B[i][k] for k in range(len(Matrix_A[0]))] for i in range(len(matrix_A))]
That gives you a 2-d array rather than a 1-d array
[[a, b, c], [d, e, f]]
but now we need to print it nicely. Here's a function to turn the matrix into a pretty string:
def prettyString(matrix):
result = ''
for row in matrix:
for value in row:
result += value
result += '\n'
return result
Finally, in your code, you can use the new function:
print(prettyString(matrices))
All you have to do is change how you sum the matrices:
matrices = [[matrix_A[i][k] + matrix_B[i][k] for k in range(len(Matrix_A[0]))] for i in range(len(matrix_A))]
Then to print:
for row in matrices:
# print(row)
print(" ".join(row))
Or
from pprint import pprint
pprint(matrices)
Try this -
First calculate the sum list of lists as output, then join the elements of sublist with spaces and join those sublists strings with \n (newline character). When you then print it, it will print it out one sublist at a time.
output = [[a[i][j] + b[i][j] for j in range(len(a[0]))] for i in range(len(a))]
print_out = '\n'.join([' '.join([str(j) for j in i]) for i in output])
print(print_out)
#sample output
1 2 3
4 5 6
zip function can be helpful when you try to combine lists of lists. This will work for any n x m matrices.
m1 = [
[1,2,3],
[4,5,6]]
m2 = [
[7,8,9],
[7,8,9]]
for row1,row2 in zip(m1,m2):
print(*[el1+el2 for el1,el2 in zip(row1,row2)])
Output:
8 10 12
11 13 15

What is the most efficient way to take user input in python list?

My input will be something in the form of:
10
3 6 7 5 3 5 6 2 9 1
2 7 0 9 3 6 0 6 2 6
here 10 is the total number of elements. followed by two lines of input for two separate lists.
I am using the following lines to take the input:
n=int(input())
m=list(map(int,input().split()))[:n]
q=list(map(int,input().split()))[:n]
furthermore, I'll be sorting them using
m.sort()
q.sort()
It would be of great help if anyone could help me to find the most efficient method of doing the above steps.
I did a few searches and landed onto various alternatives of taking the input but nowhere did I find as to what would be the most efficient way of solving this.
By efficiency, I mean in terms of time complexity. The above steps are fine when the numbers are small and the size of the list is small too. But I would have to feed a lot of much larger numbers and a much larger list thus affecting the efficiency of the code.
That's about as optimal as it gets.
If you're doing programming competitions, your bottleneck won't just be I/0, it will be your overall python runtime. It's inherently slower than C++/java, and some online judges fail to correctly account for this in the time limits.
We often encounter a situation when we need to take number/string as input from user. In this article, we will see how to get as input a list from the user.
Examples:
Input : n = 4, ele = 1 2 3 4
Output : [1, 2, 3, 4]
Input : n = 6, ele = 3 4 1 7 9 6
Output : [3, 4, 1, 7, 9, 6]
Code #1: Basic example
<!-- language: lang-phyton -->
# creating an empty list
lst = []
# number of elemetns as input
n = int(input("Enter number of elements : "))
# iterating till the range
for i in range(0, n):
ele = int(input())
lst.append(ele) # adding the element
print(lst)
Code #2: With handling exception
<!-- language: lang-phyton -->
# try block to handle the exception
try:
my_list = []
while True:
my_list.append(int(input()))
# if input is not-integer, just print the list
except:
print(my_list)
Code #3: Using map()
<!-- language: lang-phyton -->
# number of elements
n = int(input("Enter number of elements : "))
# Below line read inputs from user using map() function
a = list(map(int,input("\nEnter the numbers : ").strip().split()))[:n]
print("\nList is - ", a)
**Code #4: List of lists as input**
<!-- language: lang-phyton -->
lst = [ ]
n = int(input("Enter number of elements : "))
for i in range(0, n):
ele = [input(), int(input())]
lst.append(ele)
print(lst)

How can take input of n number of lists in python?

How can we take input of n number of lists in python
for example
2
1 2 3
4 5 6 7
here 2 is specifying number of lists that are going to input
1 2 3 is one list
4 5 6 7 is second list
another example
3
1 2 3
4 5 6 8
2 3 5 7
3 indicates 3 lists are going to input
1 2 3 is list one
4 5 6 8 is list two
2 3 5 7 id list three
i have done this code
n=input()
for i in range(n):
b=map(int,raw_input().split())
i am struck with this how can i take input for n number of lists i able to take only one list into one variable i want take to different different variables
i want take to different different variables
You can not assign the input to "different" variables in the loop, particularly if you do not know how large n will be. Instead, you should append the different values of b to a list of lists, e.g. bs.
n = input()
bs = []
for i in range(n):
bs.append(map(int, raw_input().split()))
Or use a list comprehension:
bs = [map(int, raw_input().split()) for _ in range(n)]
do you want to read from file or cli?
If you read from file, you can iterate over its content line by line and work only in the specific lines.
The lines input you can split to get the single numbers into a list.
nums=[]
with open(infile.txt) as f:
n=0
for i, line in enumerate(f):
if i==1:
n == 1
elif i <= n
nums[i] = line.split()
There are a few things to fix:
You need to convert your input 'n' to an integer.
Your 'b' gets overwritten with every iteration of the loop.
Why are you using 'raw_input' in the second case? 'input' will give you a sanitized version of the input which is preferable in this case (so that a malicious user cannot inject code).
Keep it simple and use lists instead of a map.
n = int(input())
rows = [] # will contain the input as a list of integers
for i in range(n):
row_string = input()
row = [int(num) for num in row_string.split()]
rows.append(row)

How to get n variables in one line?

I have a number n and I need to get from a user n variables in one line.
As far as i know, it's pretty easy to do if you know exactly how many variables you have.
*variables* = map(int, input().split())
But if I don't know how many variables there are, what should I do?
Also, I'm asked to put the result in array.
Unfortunately, I've just started learning Python, so I have absolutely no idea how to do it and can't show any code I've tried.
User input being taken as a space separated string:
1 2 3 4 5
This being the code you are dealing with:
map(int, input().split())
Stating you need a list, then just store it in a single variable:
inputs = map(int, input().split())
However, dealing with Python 3, you will end up with map object. So if you actually need a list type, then just call list on the map function:
inputs = list(map(int, input().split()))
Demo:
>>> inputs = list(map(int, input().split()))
1 2 3 4 5
>>> type(inputs)
<class 'list'>
>>> inputs
[1, 2, 3, 4, 5]

Categories

Resources