Getting rid of commas in a list [duplicate] - python

This question already has answers here:
Python - Print items in list with neither commas nor apostrophes
(2 answers)
Closed 5 years ago.
Here is my program:
def Prob2( rows, columns ):
for i in range(1, rows+1):
print(list(range(i, (columns*i)+1, i)))
Prob2( rows = int(input("Enter number of rows here: ")), columns = int(input("Enter number of columns here: ")))
Essentially, it takes a user input of rows and columns and, based on those inputs, makes lists of multiples starting with 1.
For example, if the user typed in 4 rows and 5 columns, the program would output something like this:
[1, 2, 3, 4, 5]
[2, 4, 6, 8, 10]
[3, 6, 9, 12, 15]
[4, 8, 12, 16, 20]
The problem I have is that I need to get rid of the commas and only have spaces between the numbers. Is this possible?

As your title specifies :
Getting rid of commas in a list
I'll give the general version of it.
>>> l = [1,2,3,4]
>>> l
[1, 2, 3, 4]
>>> s = ' '.join(str(x) for x in l)
>>> s
'1 2 3 4'
Here since the list contains int, we use list comprehension to convert each individual into str before joining.
Suppose the list contained str, we can directly do :
>>> l = ['1','2','3','4']
>>> l
['1', '2', '3', '4']
>>> s = ' '.join(l)
>>> s
'1 2 3 4'

def Prob2( rows, columns ):
for i in range(1, rows+1):
print('['+' '.join(str(val) for val in range(i, (columns*i)+1, i))+']')
Prob2( rows = int(input("Enter number of rows here: ")), columns = int(input("Enter number of columns here: ")))
output:
[1 2 3 4 5]
[2 4 6 8 10]
[3 6 9 12 15]
[4 8 12 16 20]

Could just convert your lists to strings and remove your commas with the re.sub() method.
import re
def Prob2(rows, columns):
for i in range(1, rows + 1):
numbers = re.sub(",", "", str(range(i, (columns * i) + 1, i)))
print(numbers)
Prob2(rows=int(input("Enter number of rows here: ")),
columns=int(input("Enter number of columns here: ")))
Output:
[1 2 3 4 5]
[2 4 6 8 10]
[3 6 9 12 15]
[4 8 12 16 20]

You can do it like so:
def Prob2( rows, columns ):
for i in range(1, rows+1):
print('['+', '.join(map(str, list(range(i, (columns*i)+1, i))))+']')
Prob2( rows = int(input("Enter number of rows here: ")), columns = int(input("Enter number of columns here: ")))
Using ' '.join() is a trick that allows you to convert a list to a string where map(str, <list>) iterates over each value in that list and apply the str() function on it.

Related

How Do I Print things on the same line from two print statements which are in two for loops

I am having a problem in my code first see the code I have a list
numbers = [3, 10, 12 ,14, 15, 17, 20]
I want to print all the numbers in the list but I want to have the number of the element before the element so my output should be
1 3
2 10
3 12
and so on I have tried this
for m in range(1 , len(numbers) + 1)
print(m , end = '')
for i in numbers:
print(numbers)
How can I acomplish this
The print statement accepts multiple arguments and prints them with a space in between.
print("hi", "there")
-> "hi there"
So you want:
for i in range(len(numbers)):
print(i, numbers[i])
Note, Python indexes from 0, not 1.
You can use enumerate, which will give you the index first. (and add 1 if you want the location).
numbers = [3, 10, 12 ,14, 15, 17, 20]
for idx,m in enumerate(numbers):
print(idx+1,' ',m)
Output:
1 3
2 10
3 12
I think you are beginner so here is simple solution
numbers = [3, 10, 12 ,14, 15, 17, 20]
count =0
for i in numbers:
count+=1
print(str(count)+ " " + str(i))

How can I sum every n array values and place the result into a new array? [duplicate]

This question already has answers here:
Sum slices of consecutive values in a NumPy array
(5 answers)
Closed 3 years ago.
I have a very long list of array numbers I would like to sum and place into a new array. For example the array:
[1,2,3,4,5,6,7,8,1,2,3,4,5,6,7,8]
would become:
[6,15,16,6,15,x]
if I was to sum every 3.
I cannot figure out how to go about it. I think possibly one problem is I do not know the length of my array - I do not mind losing the bottom bit of data if necessary.
I have tried the numpy.reshape function with no success:
x_ave = numpy.mean(x.reshape(-1,5), axis=1)
ret = umr_sum(arr, axis, dtype, out, keepdims)
I get an error:
TypeError: cannot perform reduce with flexible type
Cut the array to the correct length first then do a reshape.
import numpy as np
N = 3
a = np.array([1,2,3,4,5,6,7,8,1,2,3,4,5,6,7,8])
# first cut it so that lenght of a % N is zero
rest = a.shape[0]%N
a = a[:-rest]
assert a.shape[0]%N == 0
# do the reshape
a_RS = a.reshape(-1,N)
print(a_RS)
>> [[1 2 3]
[4 5 6]
[7 8 1]
[2 3 4]
[5 6 7]]
then you can simply add it up:
print(np.sum(a_RS,axis=1))
>> [ 6 15 16 9 18]
You can use a list comprehension do this:
ls = [1,2,3,4,5,6,7,8,1,2,3,4,5,6,7,8]
res = [sum(ls[i:i+3]) for i in range(0, len(ls), 3)]
[6, 15, 16, 9, 18, 8]
This will result in all the numbers being included in the resulting sum. If you don't want this to happen, then you can just check for it and replace the last sum with whatever value you want:
if (len(ls)%3) != 0:
res[-1] = 'x'
[6, 15, 16, 9, 18, 'x']
Or remove it entirely:
if (len(ls)%3) != 0:
res[:] = res[:-1]
[6, 15, 16, 9, 18]
Why don't you just simply use a list comprehension? E.g.
my_list = [1,2,3,4,5,6,7,8,1,2,3,4,5,6,7,8]
len_list = len(my_list) - len(my_list) % 3 # ignore end of list, s.t., only tuples of three are considered
[my_list[i] + my_list[i+1] + my_list[i+2] for i in range(0, len_list, 3)]

String to n*n matrix in python

I am an undergraduate student who loves programming. I encountered a problem today and I don't know how to solve this problem.
I looked for "Python - string to matrix representation" (Python - string to matrix representation) for help, but I am still confused about this problem.
The problem is in the following:
Given a string of whitespace separated numbers, create an nxn matrix (a 2d list where with the same number of columns as rows)and return it. The string will contain a perfect square number of integers. The int() and split() functions may be useful.
Example:
Input: '1 2 3 4 5 6 7 8 9'
Output: [[1,2,3],[4,5,6],[7,8,9]]
Example 2:
Input: '1'
Output: [[1]]
My answer:
import numpy as np
def string_to_matrix(str_in):
str_in_split = str_in.split()
answer = []
for element in str_in_split:
newarray = []
for number in element.split():
newarray.append(int(number))
answer.append(newarray)
print (answer)
The test results are in the following:
Traceback (most recent call last):
File "/grade/run/test.py", line 20, in test_whitespace
self.assertEqual(string_to_matrix('1 2 3 4'), [[1,2],[3,4]])
AssertionError: None != [[1, 2], [3, 4]]
Stdout:
[[4]]
as well as
Traceback (most recent call last):
File "/grade/run/test.py", line 15, in test_small
self.assertEqual(string_to_matrix('1 2 3 4'), [[1,2],[3,4]])
AssertionError: None != [[1, 2], [3, 4]]
Stdout:
[[4]]
as well as
Traceback (most recent call last):
File "/grade/run/test.py", line 10, in test_one
self.assertEqual(string_to_matrix('1'), [[1]])
AssertionError: None != [[1]]
Stdout:
[[1]]
as well as
Traceback (most recent call last):
File "/grade/run/test.py", line 25, in test_larger
self.assertEqual(string_to_matrix('4 3 2 1 8 7 6 5 12 11 10 9 16 15 14 13'), [[4,3,2,1], [8,7,6,5], [12,11,10,9], [16,15,14,13]])
AssertionError: None != [[4, 3, 2, 1], [8, 7, 6, 5], [12, 11, 10, 9], [16, 15, 14, 13]]
Stdout:
[[13]]
I am still confused how to solve this problem. Thank you very much for your help!
Assuming you don't want numpy and want to use a list of lists:
def string_to_matrix(str_in):
nums = str_in.split()
n = int(len(nums) ** 0.5)
return list(map(list, zip(*[map(int, nums)] * n)))
nums = str_in.split() splits by any whitespace, n is the side length of the result, map(int, nums) converts the numbers to integers (from strings), zip(*[map(int, nums)] * n) groups the numbers in groups of n, list(map(list, zip(*[map(int, nums)] * n))) converts the tuples produced by zip into lists.
Assuming you want to make this dynamic.
str_in = '1 2 3 4 5 6 7 8 9'
a = str_in.split(" ")
r_shape = int(math.sqrt(len(a)))
np.array([int(x) for x in a]).reshape(r_shape, r_shape)
Use split, create the 1D numpy array, then use reshape:
>>> s = '1 2 3 4 5 6 7 8 9'
>>> np.array([s.split(), dtype=int).reshape(3,3)
array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
If you don't know the size of the array, but you know it's square (same width / height), then you can use math.sqrt to get the inputs for reshape:
>>> import math
>>> s = '1 2 3 4 5 6 7 8 9'
>>> arr = np.array(s.split(), dtype=int)
>>> size = int(math.sqrt(len(arr)))
>>> arr.reshape(size, size)
array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
Given that you will always get perfect square number of ints:
import numpy as np
input_strings = '1 2 3 4 5 6 7 8 9'
arr = np.array(input_strings.split(), dtype=int)
n = int(len(arr) ** 0.5)
arr.reshape(n, n)
array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
Note: in your case, str.split is better off without explicit sep in order to work fine with multiple whitespaces in between the digits.
import numpy as np
def string_to_matrix(str_in):
str_in_split = str_in.split()
numbers = list(map(int, str_in_split))
size = r_shape = int(np.sqrt(len(numbers)))
return np.array(numbers).reshape(r_shape, r_shape)
This is why you always got: AssertionError: None != ...
assertEqual(A, string_to_matrix("...")) verifies if A is equals to the value returned by string_to_matrix. In your code you don't return anything so it is None
The other issue is how you splitted the string, the easier options is to split everything and convert to number, and then reshape to sqrt(number of elements). This assumes that input length can be splited to form a nxn matrix
import math
string = "1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16"
stringItems = string.split(" ")
numberOfItems = len(stringItems)
if math.sqrt(numberOfItems) - int(math.sqrt(numberOfItems)) == 0:
width = int(math.sqrt(numberOfItems))
array = []
finalArray = []
for i in range (0, width):
for j in range (0, width):
array.insert(j, stringItems[0])
stringItems.pop(0)
finalArray.insert(i, array)
array = []
print finalArray
else:
print "I require a string with length equal to a square number please"

Find second maximum number in a list [duplicate]

This question already has answers here:
How to remove items from a list while iterating?
(25 answers)
Closed 12 months ago.
First line contains N. Second line contains list of N integers each separated by a space. I need to find the second largest number in list.
My code:
N = int(raw_input())
L = map(int, raw_input().split())
for i in L:
if i == max(L):
L.remove(i)
print L
print max(L)
If input is [2, 6, 9, 9, 5], this still prints maximum value: 9, as only one 9 is getting removed from the list.
So, how to remove all the 1st maximum values in the list?
The reason that it's still returning 9 is because you're mutating the list as you iterate over it. Essentially the steps are:
1. 2 6 9 9 5
^idx0
2. 2 6 9 9 5
^idx1
3. 2 6 9 9 5
^idx2
3a. 2 6 9 5
^idx2
4. 2 6 9 5
^
See how it skips evaluating the second 9 when it deletes the first 9? You'll notice if your list is [2, 6, 9, 5, 9], it works appropriately.
The minimal change to your code that will make it function is to iterate over a copy of the list, rather than the list itself.
L = [2, 6, 9, 9, 5]
maxL = max(L) # gotta move this out!!
for i in L[:]: # the slice creates a copy
if i == maxL:
L.remove(i)
print(max(L))
However it's probably easier to make a set (ensuring uniqueness), sort it, and return the second-to-last entry.
second_max = sorted(set(L))[-2]
try
N = 5
L = map(int, "2 6 9 9 5".split())
maxL = max(L)
#list comprehension for remove all occurrences of max(L)
L_filter = [e for e in L if e!=maxL]
print L
#print max of L_filter, second maximum of L
print max(L_filter)
you get:
[2, 6, 9, 9, 5]
6
Remove duplicated elements by converting to a set:
values = set(L)
Then remove the maximum:
values.discard(max(values))
you could also do this
L = [2, 6, 9, 9, 5]
L_tuples = zip(L, range(len(L))) #need tuples to make a dict
L_map = dict(L_tuples) #use the dict to dedupe
L_uniq = L_map.keys() #get back deduped values
L_sorted = sorted(L_uniq) #sort them ascending
second_largest = L_sorted[-2] #second from last is second largest
#or, rolling all that up...
second_largest = sorted(dict(zip(L, range(len(L)))).keys())[-2]
>>> import heapq
>>> values = [2, 6, 9, 9, 5]
>>> heapq.heapify(values)
>>> heapq._heapify_max(values)
>>> value = top = heapq.heappop()
>>> while value == top:
... value = heapq.heappop()
>>> print value
Here is another way to calculate the second maximum in a list. The code also considers the scenario that includes duplicate elements in the list.
number_of_elements=int(input('The number of elements in list\n'))
a=[]
for i in range(number_of_elements):
a.append(int(input('enter the list elements')))
#Use built-in function to calculate the maximum
max_list=max(a)
print("The maximum element is ",max_list)
#Calculate the number of times the number occur
count_of_max_num=a.count(max_list)
b=a
if (count_of_max_num == 1):
b.remove(max_list)
second_max=max(b)
print("The second largest number is", second_max, "The new list is" ,b)
else:
for i in range(count_of_max_num):
b.remove(max_list)
print ("The second largest is" , max(b))

How to input matrix (2D list) in Python?

I tried to create this code to input an m by n matrix. I intended to input [[1,2,3],[4,5,6]] but the code yields [[4,5,6],[4,5,6]. Same things happen when I input other m by n matrix, the code yields an m by n matrix whose rows are identical.
Perhaps you can help me to find what is wrong with my code.
m = int(input('number of rows, m = '))
n = int(input('number of columns, n = '))
matrix = []; columns = []
# initialize the number of rows
for i in range(0,m):
matrix += [0]
# initialize the number of columns
for j in range (0,n):
columns += [0]
# initialize the matrix
for i in range (0,m):
matrix[i] = columns
for i in range (0,m):
for j in range (0,n):
print ('entry in row: ',i+1,' column: ',j+1)
matrix[i][j] = int(input())
print (matrix)
The problem is on the initialization step.
for i in range (0,m):
matrix[i] = columns
This code actually makes every row of your matrix refer to the same columns object. If any item in any column changes - every other column will change:
>>> for i in range (0,m):
... matrix[i] = columns
...
>>> matrix
[[0, 0, 0], [0, 0, 0]]
>>> matrix[1][1] = 2
>>> matrix
[[0, 2, 0], [0, 2, 0]]
You can initialize your matrix in a nested loop, like this:
matrix = []
for i in range(0,m):
matrix.append([])
for j in range(0,n):
matrix[i].append(0)
or, in a one-liner by using list comprehension:
matrix = [[0 for j in range(n)] for i in range(m)]
or:
matrix = [x[:] for x in [[0]*n]*m]
See also:
How to initialize a two-dimensional array in Python?
Hope that helps.
you can accept a 2D list in python this way ...
simply
arr2d = [[j for j in input().strip()] for i in range(n)]
# n is no of rows
for characters
n = int(input().strip())
m = int(input().strip())
a = [[0]*n for _ in range(m)]
for i in range(n):
a[i] = list(input().strip())
print(a)
or
n = int(input().strip())
n = int(input().strip())
a = []
for i in range(n):
a[i].append(list(input().strip()))
print(a)
for numbers
n = int(input().strip())
m = int(input().strip())
a = [[0]*n for _ in range(m)]
for i in range(n):
a[i] = [int(j) for j in input().strip().split(" ")]
print(a)
where n is no of elements in columns while m is no of elements in a row.
In pythonic way, this will create a list of list
If the input is formatted like this,
1 2 3
4 5 6
7 8 9
a one liner can be used
mat = [list(map(int,input().split())) for i in range(row)]
explanation with example:
input() takes a string as input. "1 2 3"
split() splits the string by whitespaces and returns a
list of strings. ["1", "2", "3"]
list(map(int, ...)) transforms/maps the list of strings into a list of ints. [1, 2, 3]
All these steps are done row times and these lists are stored in another list.[[1, 2, 3], [4, 5, 6], [7, 8, 9]], row = 3
If you want to take n lines of input where each line contains m space separated integers like:
1 2 3
4 5 6
7 8 9
Then you can use:
a=[] // declaration
for i in range(0,n): //where n is the no. of lines you want
a.append([int(j) for j in input().split()]) // for taking m space separated integers as input
Then print whatever you want like for the above input:
print(a[1][1])
O/P would be 5 for 0 based indexing
Apart from the accepted answer, you can also initialise your rows in the following manner -
matrix[i] = [0]*n
Therefore, the following piece of code will work -
m = int(input('number of rows, m = '))
n = int(input('number of columns, n = '))
matrix = []
# initialize the number of rows
for i in range(0,m):
matrix += [0]
# initialize the matrix
for i in range (0,m):
matrix[i] = [0]*n
for i in range (0,m):
for j in range (0,n):
print ('entry in row: ',i+1,' column: ',j+1)
matrix[i][j] = int(input())
print (matrix)
This code takes number of row and column from user then takes elements and displays as a matrix.
m = int(input('number of rows, m : '))
n = int(input('number of columns, n : '))
a=[]
for i in range(1,m+1):
b = []
print("{0} Row".format(i))
for j in range(1,n+1):
b.append(int(input("{0} Column: " .format(j))))
a.append(b)
print(a)
If your matrix is given in row manner like below, where size is s*s here s=5
5
31 100 65 12 18 10 13 47 157 6 100 113 174 11 33 88 124 41 20 140 99 32 111 41 20
then you can use this
s=int(input())
b=list(map(int,input().split()))
arr=[[b[j+s*i] for j in range(s)]for i in range(s)]
your matrix will be 'arr'
m,n=map(int,input().split()) # m - number of rows; n - number of columns;
matrix = [[int(j) for j in input().split()[:n]] for i in range(m)]
for i in matrix:print(i)
no_of_rows = 3 # For n by n, and even works for n by m but just give no of rows
matrix = [[int(j) for j in input().split()] for i in range(n)]
print(matrix)
You can make any dimension of list
list=[]
n= int(input())
for i in range(0,n) :
#num = input()
list.append(input().split())
print(list)
output:
Creating matrix with prepopulated numbers can be done with list comprehension. It may be hard to read but it gets job done:
rows = int(input('Number of rows: '))
cols = int(input('Number of columns: '))
matrix = [[i + cols * j for i in range(1, cols + 1)] for j in range(rows)]
with 2 rows and 3 columns matrix will be [[1, 2, 3], [4, 5, 6]], with 3 rows and 2 columns matrix will be [[1, 2], [3, 4], [5, 6]] etc.
a = []
b = []
m=input("enter no of rows: ")
n=input("enter no of coloumns: ")
for i in range(n):
a = []
for j in range(m):
a.append(input())
b.append(a)
Input : 1 2 3 4 5 6 7 8 9
Output : [ ['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9'] ]
row=list(map(int,input().split())) #input no. of row and column
b=[]
for i in range(0,row[0]):
print('value of i: ',i)
a=list(map(int,input().split()))
print(a)
b.append(a)
print(b)
print(row)
Output:
2 3
value of i:0
1 2 4 5
[1, 2, 4, 5]
value of i: 1
2 4 5 6
[2, 4, 5, 6]
[[1, 2, 4, 5], [2, 4, 5, 6]]
[2, 3]
Note: this code in case of control.it only control no. Of rows but we can enter any number of column we want i.e row[0]=2 so be careful. This is not the code where you can control no of columns.
a,b=[],[]
n=int(input("Provide me size of squre matrix row==column : "))
for i in range(n):
for j in range(n):
b.append(int(input()))
a.append(b)
print("Here your {} column {}".format(i+1,a))
b=[]
for m in range(n):
print(a[m])
works perfectly
rows, columns = list(map(int,input().split())) #input no. of row and column
b=[]
for i in range(rows):
a=list(map(int,input().split()))
b.append(a)
print(b)
input
2 3
1 2 3
4 5 6
output
[[1, 2, 3], [4, 5, 6]]
I used numpy library and it works fine for me. Its just a single line and easy to understand.
The input needs to be in a single size separated by space and the reshape converts the list into shape you want. Here (2,2) resizes the list of 4 elements into 2*2 matrix.
Be careful in giving equal number of elements in the input corresponding to the dimension of the matrix.
import numpy as np
a=np.array(list(map(int,input().strip().split(' ')))).reshape(2,2)
print(a)
Input
array([[1, 2],
[3, 4]])
Output

Categories

Resources