Print row in python - python

What can I change so that I will get a list of only the first row?
i.e
0 1
1 2
2 3
3 4
I have tried the below:
matrix = [[1, 2, 3, 4],
[3, 5, 7, 9],
[4, 6, 8, 10],
[5, 7, 9, 11]]
for index in range(len(matrix)):
print(index,matrix[index][0])
0 1
1 3
2 4
3 5

You need:
print(index,matrix[0][index])
instead of:
print(index,matrix[index][0])
This is because the first index is associated with the outer list (the rows). matrix[index] returns an entire row, and then slicing it further returns elements from that row.
You should also change:
for index in range(len(matrix)):
to:
for index in range(len(matrix[0])):
for the same reason. Since it's a square matrix, it'll work out either way, but that's just luck. Actually, it'd be best to just do this instead for simplicity:
for i, e in enumerate(matrix[0]):
print(i, e)
On each iteration of the loop, enumerate() yields a tuple consisting of the index and the element together. If you don't need the index, you could further simplify to:
for e in matrix[0]:
print(e)
You typically only need to use range() if you aren't already starting with a list (or something else that's iterable).

This should work:
matrix = [[1, 2, 3, 4],
[3, 5, 7, 9],
[4, 6, 8, 10],
[5, 7, 9, 11]]
for index in range(len(matrix)):
print(index,matrix[0][index])
You were trying to get the first element from each individual list, the code above will get all elements from the first list.

Assuming your matrix is a list of rows:
print(matrix[0])
Or if you want one item per line:
for value in matrix[0]:
print(value)
And if you want the index:
for index, value in enumerate(matrix[0]):
print(index, value)

matrix = [
[1, 2, 3, 4],
[3, 5, 7, 9],
[4, 6, 8, 10],
[5, 7, 9, 11]
]
matrix[0] gives you the first row, just iterate over it like this:
# ONLY ITERATING OVER THE FIRST ROW
for item in matrix[0]:
print(item)

Related

Remove rows that contains at least one duplicate value

I have a list of indexes A :
A = np.array([[1, 4, 3],
[1, 2, 5],
[6, 7, 8],
[9, 10, 2],
[11, 3, 12]])
I would like to delete each lines that contains at least one duplicated value (no matter in which column it's located) to obtain an array with no duplicates indexes :
[[1, 4, 3],
[6, 7, 8],
[9, 10, 2],
Is there a quick and convenient way to perform this ?
Given that no sub-list should be in the output if a value in it has already been in any previous sub-list then one possible solution can look like this,
# Assuming that A is a 2-D list
output = []
# Add all values to a set
st = set()
for i in range(len(A)):
for j in range(len(A[i])):
if A[i][j] not in st:
st.add(A[i][j])
for i in range(len(A)):
flag = True
j = 0
while j < len(A[i]):
if A[i][j] not in st:
# set flag to false if value not in set meaning a duplicate is encountered
flag = False
break
else:
# if a value is in the set then remove it from set
st.remove(A[i][j])
j += 1
# append A[i] to output only if the sub-list did not encounter any duplicates
if flag:
output.append(A[i])
The time complexity will be O(n2).
When the input is,
A = [[1, 4, 3],
[1, 2, 5],
[6, 7, 8],
[9, 10, 2],
[11, 3, 12]]
It provides the output,
[[1, 4, 3], [6, 7, 8], [9, 10, 2]]
mask means dont show the element.
mask = 0 means show element
In beginning assume all are unmasked
one by one check if there is intersection with next and if so, mask that
If something is masked, dont use it for masking next elements
Show all unamsked element
mask = np.zeros((A.shape[0],), dtype=bool)
for i in range(A.shape[0]):
if mask[i]: continue
a = set(A[i])
for j in range(i+1, A.shape[0]):
if not a.intersection(A[j]): continue
mask[j] = True
A[~mask]

add value to each element of a multidimensional array

I want to know how I can add a value to each element of a NXN multidimensional array. I tried [x+1 for x in multiArray], but this one yields only for a 1D array.
Maybe something like this:
multiArray = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
addingArray=[]
for i in range(3):
for j in range(3):
addingArray.append(multiArray[j]+1) #(adding 1 to each element here)
But this seems to be wrong?
You're getting 1D array as result because you have addingArray as a simple list. So, you iterate over all the elements in your multiArray and add 1 to it and you're appending the result to a list.
For efficiency reasons, it is advisable to use NumPy for arrays. Then, you can simply use broadcasting to add value to each element of the array. Below is an illustration:
# input array
In [180]: multiArray = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
# add 1 to each value of the array
In [181]: multiArray + 1
Out[181]:
array([[ 2, 3, 4],
[ 5, 6, 7],
[ 8, 9, 10]])
If you indeed want a plain python list as the result for some reasons, you can simply cast it to one:
In [182]: (multiArray + 1).tolist()
Out[182]: [[2, 3, 4], [5, 6, 7], [8, 9, 10]]
Indice-iteration
You need to have a inner list to get the inner results, and access the good value with multiArray[i][j], also don't use constant 3 take the habit to use object length
addingArray=[]
for i in range(len(multiArray)):
innerArray = []
for j in range(len(multiArray[i])):
innerArray.append(multiArray[i][j]+1)
addingArray.append(innerArray)
print(addingArray) # [[2, 3, 4], [5, 6, 7], [8, 9, 10]]
Value iteration
You can also iterate over the arra directly to simplify and don't both with indices
addingArray=[]
for inner in multiArray:
innerArray = []
for value in inner:
innerArray.append(value+1)
addingArray.append(innerArray)
List comprehension
And shorten it with list comprehension syntax
multiArray = [[v+1 for v in inner] for inner in multiArray]
print(multiArray) # [[2, 3, 4], [5, 6, 7], [8, 9, 10]]

How to split a nested list into a smaller nested list

So I have a nested list as my input (and the nested list is always square. ie. same number of rows as columns). I want to break this list up into another nested list of which the elements are just 2x2 "parts" of the original list.
For example, if my input was
[[1,2,3,4],
[5,6,7,8],
[9,10,11,12],
[13,14,15,16]]
my output should be
[[1,2,5,6], [3,4,7,8], [9,10,13,14], [11,12,15,16]]
Another example:
input:
[[1,2,3],
[5,6,7],
[9,10,11],
output:
[[1,2,5,6],[3,7],[9,10],[11]]
I've tried making a nested for loop that goes through the first two columns and rows and makes that into a list and then appends that to another list and then repeats the process, but I get an index out of bounds exception error
This is what I've done so far
def get_2_by_2(map: List[List[int]]) -> int:
i = 0
j = 0
lst_2d = []
lst = []
for row in range(i, min(i+2, len(map))):
for column in range(j, min(j+2, len(map))):
print(row,column)
lst.append(map[row][column])
lst_2d.append(lst)
return lst_2d
basically this one only returns the first 2x2. I attempted using a while loop on the outside and incrementing the values of i and j and making my while loop dependent on one of them. that resulted in an index out of bounds.
You can iterate through the rows and columns in a step of 2, and slice the list of lists accordingly:
def get_2_by_2(matrix):
output = []
for row in range(0, len(matrix), 2):
for col in range(0, len(matrix[0]), 2):
output.append([i for r in matrix[row: row + 2] for i in r[col: col + 2]])
return output
or with a nested list comprehension:
def get_2_by_2(matrix):
return [
[i for r in matrix[row: row + 2]
for i in r[col: col + 2]] for col in range(0, len(matrix[0]), 2)
]
so that given:
m = [[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16]]
get_2_by_2(m) returns:
[[1, 2, 5, 6], [3, 4, 7, 8], [9, 10, 13, 14], [11, 12, 15, 16]]
and that given:
m = [[1, 2, 3],
[5, 6, 7],
[9, 10, 11]]
get_2_by_2(m) returns:
[[1, 2, 5, 6], [3, 7], [9, 10], [11]]

Finding unique solution puzzle python

x = np.array([[0,1,11],[0,2,11],[0,3,10],[0,4,10],[0,5,9],[0,6,9],[1,7,9],
[1,5,11],[1,6,11],[2,7,11],[2,8,10]])
I'm pretty new to this so i'm gonna call things like this [element1,element2,element3]
i have an array as shown above, and i want to find a solution to this array.
It should satisfy the following conditions:
The first element 0:
it should have atleast one solution from [0,1,11],[0,2,11],[0,3,10],[0,4,10],[0,5,9],[0,6,9]
The first element 1:
this : [1,7,9],[1,5,11],[1,6,11]
The first element 2:
and this : [2,7,11],[2,8,10]
Such that the second element and 3rd element is unique for each solution(where 1st element=0,second element=1 and 3rd element=2)
o/p can be :
[0,1,11] and [1,7,9] and [2,8,10]
wrong output :
[0,1,11], [1,6,11] ,[2,8,10]
here parameter 3 of the first and the second are same.
If I understand correctly, you want to produce triplets from the given x array so that the first, second and third element are all unique in one triplet. Code to do that:
import itertools
x = [[0,1,11],[0,2,11],[0,3,10],[0,4,10],[0,5,9],[0,6,9],[1,7,9],
[1,5,11],[1,6,11],[2,7,11],[2,8,10]]
triplets = itertools.combinations(x,3)
for t in triplets:
isGood = True
for pos in range(3):
if (t[0][pos] == t[1][pos] or t[0][pos] == t[2][pos] or t[1][pos] == t[2][pos]):
isGood = False
if (isGood):
print(repr(t))
This procudes the following output:
([0, 1, 11], [1, 7, 9], [2, 8, 10])
([0, 2, 11], [1, 7, 9], [2, 8, 10])
([0, 5, 9], [1, 6, 11], [2, 8, 10])
([0, 6, 9], [1, 5, 11], [2, 8, 10])
A more pythonic solution which does the same in only 3 lines
for t in itertools.combinations(x,3):
if all(len(col) == len(set(col)) for col in zip(*t)):
print(repr(t))
Insane one-liner:
print(''.join(repr(t) + '\n' for t in itertools.combinations(x,3) if all(len(col) == len(set(col)) for col in zip(*t))))

Looping through a mutidimentional array in python

How do i achieve line 9 and 10 i.e the two for loops in python
matrix = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]
]
newMatrix = []
for (i=0; i < len(matrix); i++):
for (j=0; j < len(matrix[i]); j++):
newMatrix[j][i] = matrix[i][j]
print newMatrix
PS: i know i can do [[row[i] for row in matrix] for i in range(4)] but how i do only using for loops
Use range (or xrange).
for i in range(len(matrix)):
for j in range(len(matrix[i])):
FYI, assigning to newMatrix[i][j] will fail, because newMatrix is an empty list. You need to add a new empty list to newMatrix for every row and then append the new value to that list in every iteration.
You can use the enumerate() function to loop over both the matrix values and give you indices:
newMatrix = [[0] * len(matrix) for _ in xrange(len(matrix[0]))]
for i, row in enumerate(matrix):
for j, value in enumerate(row):
newMatrix[j][i] = value
This outputs:
[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
Because you are addressing rows and columns in the new matrix directly, you need to have initialized that new matrix with empty values first. The list comprehension on the first line of my example does this for you. It creates a new matrix that is (y, x) in size, given an input matrix of size (x, y).
Alternatively, you can avoid explicit looping altogether by (ab)using the zip function:
newMatrix = zip(*matrix)
which takes each row of matrix and groups each column in those rows into new rows.
In the generic case, python for constructs loop over sequences. The range() and xrange() functions can produce numerical sequences for you, these generate a number sequence in much the same way that a for loop in C or JavaScript would produce:
>>> for i in range(5):
>>> print i,
0 1 2 3 4
but the construct is far more powerful than the C-style for construct. In most such loops your goal is to provide indices into some sequence, the python construct bypasses the indices and goes straight to the values in the sequence instead.
Just to throw something else into the mix of answers, if you are doing any kind of matrix operations with Python, consider using numpy:
>>> import numpy
>>> matrix = numpy.matrix([
... [1, 2, 3, 4],
... [5, 6, 7, 8],
... [9, 10, 11, 12]
... ])
The transpose is pretty simple to do:
>>> matrix.transpose()
matrix([[ 1, 5, 9],
[ 2, 6, 10],
[ 3, 7, 11],
[ 4, 8, 12]])
If I understand you correctly, what you want to do is a matrix transposition, which can be done this way:
zip(*matrix)

Categories

Resources