How to take input in this form in python? - python

So, I want to take input of the following -
3
1 2
2 4
3 4
The first line contains an integer n. Each of the following n lines contains a pair of distinct space-separated integers.
I want to store the inputs of first column in one array and the second column in another array.
I came up with this code, can you tell me where I went wrong and how to do it?
n = int(input())
h = []
g = []
num = 0
for i in range(n):
m = map(int,input().split("\n"))
h.append(m)
for j in range(n):
ni = map(int,input().split("\n"))
h.append(ni)

When you read using input you get the entire current line of input as a string, so each of your calls to input after the first will return '1 2', '2 4' and finally '3 4'.
You need to split those strings on (space) and then convert the values to integers and append them to the h and g lists. For example:
for i in range(n):
this_h, this_g = map(int, input().split(' '))
h.append(this_h)
g.append(this_g)
print(h)
print(g)
Output:
[1, 2, 3]
[2, 4, 4]

Related

Create list object from multiline input with only the standard python library

I'm trying to store this single input:
5 2 100
2
8
1
3
into three variables (N, x, n) and a list object
the variables are correctly written, being N = 5, x = 2, n = 100
N, x, n = input().split(' ')
list = [input()]
I've tried using this, but the list only intakes the ['2'], while I need it to be ['2', '8', '1', '3']
I've also tried using while and if loops to try to iterate through the input,
but that didn't seem to work for me.
To enter the list you use this approach:
N, x, n = input().split(' ')
lst = []
while True:
el = input()
if len(el) > 0:
lst.append(el)
else:
break
Note that you'll have a list of strings, and also N, x and n are strings - so will need to take care of it...

Taking user input of 2-D array in a given format

I have a 2-D 6x6 array, A.
I want its values to be input by the user in the following format or example:
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
where the 0's indicate the places where the user would write their values.
This is my code. It returns an error in split().
def arr_input(x):
for i in range(6):
for j in range(6):
n = int(input().split(' '))
if n>=-9 and n<=9:
x[i][j] = n
print "\n"
I don't want input in a single line. Please help!
EDIT 1
The code I needed was already provided :D. Nevertheless, I learned something new and helpful. Here is the existing code to do the task I wanted:
arr = []
for arr_i in xrange(6):
arr_temp = map(int,raw_input().strip().split(' '))
arr.append(arr_temp)
First of all, you are using input() which returns int when you enter numbers in terminal. You should use raw_input() and get it line by line.
Second, you are trying to convert a list to integer, you should loop through the list values, convert and insert on the resulting list.
Fixed code:
def arr_input(x):
for i in range(6):
num_list = raw_input().split(' ')
for j, str_num in enumerate(num_list):
n = int(str_num)
if n >= -9 and n <= 9:
x[i][j] = n
print "\n"
Here, I used enumerate() to loop though the number list by getting its index each iteration.
There's an inconsistency in how you're treating the input. In python 2.7, the input() function is designed to read one, and only one, argument from stdin.
I'm not exactly sure which way you're trying to read the input in. The nested for loop suggests that you're trying to read the values in one by one, but the split suggests that you're doing it line by line. To cover all bases, I'll explain both cases. At least one of them will be relevant.
Case 1:
Let's say you've been inputting the values one by one, i.e.
1
4
9
4
...
In this case, what's happening is that the input() function is automatically parsing the inputs as integers, and when you try running split() on an integer there's a type error. Python is expecting a string and you're providing an int. That's going to break. There's an easy solution--this can be fixed by simply replacing that line with
n = input()
Case 2: Let's say you're inputing the numbers line by line, as strings. By this, I mean something like:
"1 3 4 5 7 9"
"4 1 8 2 5 1"
...
What's occurring here is that int(...) is trying to cast a list of strings into an integer. That will clearly break the code. A possible solution would be to restructure the code by gett rid of the inner for loop. Something like this should work:
def arr_input(arr):
for i in range(6):
s = input()
nums_s = s.split(' ')
nums = [int(x) for x in nums_s]
arr.append(nums)
print "\n"
return arr
# Usage
a = []
print(a)
a = arr_input(a)
print(a)
Give this one-liner a try:
def arr_input(N=6):
print 'Enter %d by %d array, one row per line (elements separated by blanks)' % (N, N)
return [[n if abs(n)<=9 else 0 for n in map(int, raw_input().split())] for i in range(N)]
The following interactive session demonstrates its usage:
>>> A = arr_input(3)
Enter 3 by 3 array, one row per line (elements separated by blanks)
1 2 -3
4 5 -6
8 9 10
>>> A
[[1, 2, -3], [4, 5, -6], [8, 9, 0]]

Can we add the same element twice in a python list?

Here is the question:
Here is an array of length M with numbers in the range 1 ... N, where
N is less than or equal to 20. We are to go through it and count how
many times each number is encountered. I.e. it is like Vowel Count
task, but we need to maintain more than one counter. Be sure to use
separate array for them, do not create a lot of separate variables,
one for each counter.
Input data contain M and N in the first line. The second (rather long)
line will contain M numbers separated by spaces. Answer should contain
exactly N values, separated by spaces. First should give amount of
1-s, second - amount of 2-s and so on.
Example:
data input: 10 3 3 2 1 2 3 1 1 1 1 3
answer: 5 2 3
Here is my code for this problem:
# 10 3
# 3 2 1 2 3 1 1 1 1 3
# [1, 0, 0]
# expected: [5, 2, 3]
# Transfer the first line input into number lista:
rawone = input()
stringa = rawone.split()
lista = []
for el in stringa:
lista.append(int(el))
# check the function:
# print (lista)
# Transfer the second line input into number listb:
rawtwo = input()
stringb = rawtwo.split()
listb = []
for ele in stringb:
listb.append(int(ele))
# check the function:
# print (listb)
# initiate a few variables:
t = 0 # the current time
times = lista[1] # the total time
print (times)
d = 1 # detect key
n = 0 # the number of qualified candidate
out = [] # the list of output
elist = []
# method: while (t<times) --> for element in listo: if (el==d) --> n=n+1:
# THIS PART HAS SOME PROBLEMS!!!
while t < times:
n = 0 # reinitiate the n
for elem in listb: # ***WHY THIS FOR LOOP CAN ONLY BE EXCUTE ONCE AND NOT WORK ANY MORE???
if elem == d:
elist += [(elem)]
d = d + 1
out.append(len(elist))
print (elist)
t = t + 1
print (out)
So I have some problem with the formula part and it's not what I expect it would do. And I checked my answer. I am confused why it only add one qualified element in each turn. How can I fix this? Thank you for your generous help!
So the problem has been solved, my final code is like below:
# Transfer the first line input into number lista:
rawone = input()
stringa = rawone.split()
lista = []
for el in stringa:
lista.append(int(el))
# check the function:
# print (lista)
# Transfer the second line input into number listb:
rawtwo = input()
stringb = rawtwo.split()
listb = []
for ele in stringb:
listb.append(int(ele))
# check the function:
# print (listb)
# initiate a few variables:
t = 0 # the current time
times = lista[1] # the total time
# print (times)
d = 1 # detect key
n = 0 # the number of qualified candidate
out = [] # the list of output
elist = []
# method: while (t<times) --> for element in listo: if (el==d) --> n=n+1:
# THIS PART HAS SOME PROBLEMS!!!
while t < times:
n = 0 # reinitiate the n
for elem in listb: # ***WHY THIS FOR LOOP CAN ONLY BE EXCUTE ONCE AND NOT WORK ANY MORE???
if elem == d:
elist.append(elem)
d = d + 1
out.append(len(elist))
elist = [] # reinitiate elist
# print (elist)
t = t + 1
print(" ".join(str(x) for x in out))
I realize this might not count for your assignment, but anyways:
from collections import Counter
N = 3
my_list = [3, 3, 2, 1, 2, 3, 1, 1, 1, 1, 3]
c = Counter(my_list)
print(" ".join(c[i+1] for i in range(N)))
Your code is difficult to follow due to the poor variable names and extra variables. As you continue in programming, please look for examples of better coding.
The main problem you have is that you increment d inside the inner loop. Take the statement d = d + 1 and un-indent it one level. This means that you increment d only once each time you go through the outer while loop.
Even better, just use the outer loop for this. Since you already know how many times you have to execute that, use a for loop on the outside, as well:
for d in range(1, times+1):
n = 0 # reinitiate the n
for elem in listb: # ***WHY THIS FOR LOOP CAN ONLY BE EXCUTE ONCE AND NOT WORK ANY MORE???
if elem == d:
elist += [elem]
out.append(len(elist))
print (elist)
print (out)
This at least gets you to output closer to what you want:
[1, 1, 1, 1, 1]
[1, 1, 1, 1, 1, 2, 2]
[1, 1, 1, 1, 1, 2, 2, 3, 3, 3]
[5, 7, 10]
You can now attack the next problem: counting only the entries for that particular number, rather than all the numbers found so far. To do this, be sure to clean out the elist every time, instead of only once:
for d in range(1, times+1):
elist = []
for elem in listb:
...
... which finally gets the output:
[1, 1, 1, 1, 1]
[2, 2]
[3, 3, 3]
[5, 2, 3]
I expect that you can finish from here.
Also note that you can simply set up out as a direct count of the elements you find. If you find a 1, increment the first element of out; if you find a 2, increment the second, and so on. The code for that segment has no outer loop; it just looks like this:
out = [0] * times
for elem in listb:
out[elem-1] += 1
print (out)
That replaces all your code below print (times).
#Prune shows you how to fix your code. I also want to show you how it's possible to solve this problem with much less code (using a list rather than resorting to collections.Counter)
Since you are given M and N, it's a good idea to store them in variables od those names
first_line = [int(x) for x in input().split()]
M, N = first_line
second_line = [int(x) for x in input().split()]
Now create a list (array) with N zeros. These are the counters
result = [0] * N
Remember that list (array) indices start at 0, so we need to subtract 1 from each elem
for elem in second_line:
result[elem - 1] += 1
Show the result
print(result)

multiply the every second digit in list in python

I've tried to get numbers' list between 0 and100,000. and then i want to multiply every second digits of the list. I have no idea how to get the ervery second digit of the numbers.
def breakandSum():
if 0<=x<100000:
digits=(map(int,str(x)))
return digits
To get the second digit from the right in base 10, you would first mod the number by 100 to truncate the leading digits, then take the integer result and divide by the integer 10 to truncate the trailing digits.
Here's a quick example where x = 4567 which extracts the second base 10 digit from the right, or the "tens" digit, which is "6" in this example:
>>> x = 4567
>>> x = x % 100
>>> x = x / 10
>>> print x
6
If you wanted to put all the digits in a list, you could just extract the right-most digit, append it to the list, then truncate and continue the loop as shown here:
>>> x = 4567
>>> xdigit = []
>>> while x > 0:
... xdigit.append(x % 10)
... x = x / 10
...
>>> print xdigit
[7, 6, 5, 4]
>>>
From here you can then get every second digit using a list comprehension and filter:
>>> every_other_digit = [xdigit[i] for i in filter(lambda j: j % 2 == 0, range(len(xdigit)))]
>>> print every_other_digit
[7, 5]
Which if you need to multiply these digits you can now just iterate over this list to get the final product:
>>> answer = 1
>>> for k in every_other_digit: answer *= k
...
>>> print answer
35
There is a more concise way of doing it:
digitSum = sum(x * 2 for x in list(map(int, str(num)))[::2])
Where:
str(num) turns num into a string
list(map(int, str(num))) for every element in string turn it back to an int and put it in a list
list(...)[::2] for every other element in the list starting from the leftmost element
x * 2 for x in list(...)[::2] for each element in the list multiply it by 2
sum(...) add every element from the iteration
Edit: sorry I thought you wanted to multiply each by a specific number if you want to multiply every other you just go:
import math
digitSum = math.prod(x for x in list(map(int, str(num)))[::2])

taking n*n matrix input by user in python

I am starting to code in python. When I was to take two inputs from user with a space between the two inputs my code was like
min, p = input().split(" ")
min=int(min)
p=float(p)
which worked fine. In another such problem I am to take a n*n matrix as user input which I declared as arr=[[0 for i in range(n)] for j in range(n)]
printing the arr gives a fine matrix(in a single row though) but I am to replace each element '0'with a user input so I use nested loops as
for i in range(0,n)
for j in range(0,n)
arr[i][j]=input()
this also worked fine but with a press of 'enter' button after each element. In this particular problem the user will input elements in one row at space instead of pressing 'enter' button. I wanted to know how to use split in this case like in first case above, keeping in mind the matrix is n*n where we don't know what is n. I prefer to avoid using numpy being a beginner with python.
You can do this:
rows = int(input("Enter number of rows in the matrix: "))
columns = int(input("Enter number of columns in the matrix: "))
matrix = []
print("Enter the %s x %s matrix: "% (rows, columns))
for i in range(rows):
matrix.append(list(map(int, input().rstrip().split())))
Now you input in the console values like this:
Enter number of rows in the matrix: 2
Enter number of columns in the matrix: 2
Enter the 2 x 2 matrix:
1 2
3 4
#Take matrix size as input
n=int(input("Enter the matrix size"))
import numpy as np
#initialise nxn matrix with zeroes
mat=np.zeros((n,n))
#input each row at a time,with each element separated by a space
for i in range(n):
mat[i]=input().split(" ")
print(mat)
You can try this simple approach (press enter after each digit...works fine)::
m1=[[0,0,0],[0,0,0],[0,0,0]]
for x in range (0,3):
for y in range (0,3):
m1[x][y]=input()
print (m1)
Try something like this instead of setting the matrix one by one using existing list(s):
# take input from user in one row
nn_matrix = raw_input().split()
total_cells = len(nn_matrix)
# calculate 'n'
row_cells = int(total_cells**0.5)
# calculate rows
matrix = [nn_matrix[i:i+row_cells] for i in xrange(0, total_cells, row_cells)]
Example:
>>> nn_matrix = raw_input().split()
1 2 3 4 5 6 7 8 9
>>> total_cells = len(nn_matrix)
>>> row_cells = int(total_cells**0.5)
>>> matrix = [nn_matrix[i:i+row_cells] for i in xrange(0, total_cells, row_cells)]
>>> matrix
[['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9']]
>>>
>>> import math
>>> line = ' '.join(map(str, range(4*4))) # Take input from user
'0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15'
>>> items = map(int, line.split()) # convert str to int
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
>>> n = int(math.sqrt(len(items))) # len(items) should be n**2
4
>>> matrix = [ items[i*n:(i+1)*n] for i in range(n) ]
[[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11], [12, 13, 14, 15]]
Well if matrix is n*n that means with first input line you know number of input lines (and no, it's impossible for input() to not end with key enter is pressed). So you need something like this:
arr = []
arr.append(input().split())
for x in range(len(arr[0]) - 1):
arr.append(input().split())
I used range(len(arr[0]) - 1) so it inputs rest of lines (because matrix width and height is same and one first line is already read from input).
Also I used .split() without " " as parameter because it's default parameter.
Try with below,
r=int(input("enter number of rows"));
c=int(input("enter number of columns"));
mat=[];
for row in range(r):
a=[]
for col in range(c):
a.append(row*col);
mat.append(a)
print mat;
print("Enter The row and column :")
row,col=map(int,input().split())
matrix = []
print("Enter the entries rowwise:")
# For user input
for i in range(row): # for loop for row entries
a =[]
for j in range(col): # for loop for column entries
a.append(int(input()))
matrix.append(a)
for i in range(row):
for j in range(col):
print(matrix[i][j], end = " ")
print()
n= 10 # n is the order of the matrix
matrix = [[int(j) for j in input().split()] for i in range(n)]
print(matrix)
r = int(input("Enret Number of Raws : "))
c = int(input("Enter Number of Cols : "))
a=[]
for i in range(r):
b=[]
for j in range(c):
j=int(input("Enter Number in pocket ["+str(i)+"]["+str(j)+"]"))
b.append(j)
a.append(b)
for i in range(r):
for j in range(c):
print(a[i][j],end=" ")
print()

Categories

Resources