Matrix rotation, list index out of range - python

Trying to rotate a matrix of size 3 in counterclockwise direction.
def anti(matrix,n):
while n > 0: # n is the no of rotations
l = len(matrix)
new_matrix = [[row[:] for row in matrix]]
for i in range(l-1,-1,-1):
for j in range(l):
new_matrix[l-i-1][j] = matrix[j][i]
matrix = [row[:] for row in new_matrix]
n -= 1
return matrix
The error I got was:
List index out of range in line 7

There is extra [] in your new_matrix. Which is causing dimension miss match between new_matrix and matrix.
def anti(matrix,n):
while n > 0: # n is the no of rotations
l = len(matrix)
new_matrix = [row[:] for row in matrix]
for i in range(l-1,-1,-1):
for j in range(l):
new_matrix[l-i-1][j] = matrix[j][i]
matrix = [row[:] for row in new_matrix]
n -= 1
return matrix
a = [[1,2,3],[4,5,6],[7,8,9]]
print(anti(a, 3))

Related

Stuck in writing python list reduction program

I am stuck in writing the python code for below problem, can anyone help to find the issue with the code is much appreciated.
List Reduction:
You are given a list of integers L having size N and an integer K. You can perform the following operation on the list at most k times:
Pick any two elements of the list.
Multiply any element by 2.
Divide the other element by 2, taking the ceiling if element is odd.
Note: that after such an operation, the list is changed and the changed list will be used in subsequent operations.
You need to minimize the sum of all elements present in the list after performing at most k such operations.
Input Format:
First line contains N K as described above.
The second line contains N space separated integers, representing the list initially,
Output Format:
Print the minimum possible sum of all elements in the list at the end, after performing at most k operations.
Code:
def solve (X, arr):
Sum = 0
largestDivisible, minimum = -1, arr[0]
for i in range(0,N):
Sum += arr[i]
if(arr[i]%X == 0 and largestDivisible < arr[i]):
largestDivisible = arr[i]
if arr[i] < minimum:
minimum = arr[i]
if largestDivisible == -1:
return Sum
sumAfterOperation = (Sum-minimum-largestDivisible+(X*minimum)+(largestDivisible//X))
return min(Sum,sumAfterOperation)
N=5
X =2
#map(int, input().split())
arr = [10, 7, 4, 2, 1]
#list(map(int, input().split()))
out_ = solve(X, arr)
print (out_)
output: 20
expected output: 19
Not optimal program.
Idea: Multiplying the minimal element and dividing the maximal element gives sequence with minimal total sum. Do you want process negative numbers? Does K take negative values?
K = int(input())
arr = list(map(int, input().split()))
for _ in range(K):
arr.sort()
arr[0] *= 2
arr[-1] = arr[-1] // 2 + arr[-1] % 2
print(sum(arr))
More effective solution.
K = int(input())
arr = list(map(int, input().split()))
for _ in range(K):
mn, mx = min(arr), max(arr)
mn_i = arr.index(mn)
if mn != mx:
mx_i = arr.index(mx)
else:
mx_i = arr.index(mx, mn_i+1)
arr[mn_i] *= 2
arr[mx_i] = arr[mx_i] // 2 + arr[mx_i] % 2
print(sum(arr))
And algorithmic solution.
K = int(input())
arr = list(map(int, input().split()))
for _ in range(K):
mn, mx = 0, 0
for i, x in enumerate(arr):
if x < arr[mn]:
mn = i
if x >= arr[mx]:
mx = i
arr[mn] *= 2
arr[mx] = arr[mx] // 2 + arr[mx] % 2
print(sum(arr))

Markov Transition Probability Matrix Implementation in Python

I am trying to calculate one-step, two-step transition probability matrices for a sequence as shown below :
sample = [1,1,2,2,1,3,2,1,2,3,1,2,3,1,2,3,1,2,1,2]
import numpy as np
def onestep_transition_matrix(transitions):
n = 3 #number of states
M = [[0]*n for _ in range(n)]
for (i,j) in zip(transitions,transitions[1:]):
M[i-1][j-1] += 1
#now convert to probabilities:
for row in M:
s = sum(row)
if s > 0:
row[:] = [f/s for f in row]
return M
one_step_array = np.array(onestep_transition_matrix(sample))
My question, how do we calculate two step transition matrix. because when I manually calculate the matrix it is as below :
two_step_array = array([[1/7,3/7,3/7],
[4/7,2/7,1/7],
[1/4,3/4,0]])
However. np.dot(one_step_array,one_step_arrary) gives me a result which is different and as follows :
array([[0.43080357, 0.23214286, 0.33705357],
[0.43622449, 0.44897959, 0.11479592],
[0.20089286, 0.59821429, 0.20089286]])
Please let me know which one is correct.
You just have to change the transitions index in your for loop:
def twostep_transition_matrix(transitions):
n = 3 #number of states
M = [[0]*n for _ in range(n)]
for (i,j) in zip(transitions,transitions[2:]):
M[i-1][j-1] += 1
#now convert to probabilities:
for row in M:
s = sum(row)
if s > 0:
row[:] = [f/s for f in row]
return M

Python 3.x Finding saddle points in a matrix

This is my matrix:
1 1 2 5 6 1
5 6 8 5 6 7
10 12 10 12 11 11
8 10 5 6 8 9
6 5 10 12 15 19
and I would like to find it's saddle points.
COORDINATES of Saddle points should be:
2 0
2 2
0 4
So my question is. Can someone show me, how to make this in Python? :)
Here is a Python approach that assembles lists of the indices of all row/column mins and maxs and then uses set operations to find their intersections:
def allSaddles(matrix):
rowmins = []
rowmaxs = []
colmins = []
colmaxs = []
for i,row in enumerate(matrix):
m = min(row)
M = max(row)
for j,x in enumerate(row):
if x == m: rowmins.append((i,j))
if x == M: rowmaxs.append((i,j))
t = [list(column) for column in zip(*matrix)] #transpose of matrix
for j,col in enumerate(t):
m = min(col)
M = max(col)
for i,x in enumerate(col):
if x == m: colmins.append((i,j))
if x == M: colmaxs.append((i,j))
return (set(rowmins) & set(colmaxs)) | (set(rowmaxs) & set(colmins))
M = [[1,1,2,5,6,1],
[5,6,8,5,6,7],
[10,12,10,12,11,11],
[8,10,5,6,8,9],
[6,5,10,12,15,19]]
print(allSaddles(M))
Output: {(0, 4), (2, 0), (2, 2)}
Here is a different way to make it. Note that the input matrix is a np.ndarray :
def saddles(mat : np.ndarray) -> list:
"""
returns the list of all saddle points of the input matrix
"""
(N, M) = mat.shape
jMax = np.argmax(mat, axis = 1) # index of col for max in each row
iMin = np.argmin(mat, axis = 0) # index of row for min in each col
IJMax = [(i,jMax[i]) for i in range(N)] # list of indexes of max of each row
IJMin = [(iMin[j],j) for j in range(M)] # list of indexes of min of each col
maxRowMinCol = list(set(IJMax) & set(IJMin)) # max of row, min of col
iMax = np.argmax(mat, axis = 0) # index of row for max in each col
jMin = np.argmin(mat, axis = 1) # index of col for min in each row
IJMax = [(iMax[j],j) for j in range(M)] # list of indexes of max of each col
IJMin = [(i,jMin[i]) for i in range(N)] # list of indexes of min of each row
minRowMaxCol = list(set(IJMax) & set(IJMin)) # min of row, max of col
return maxRowMinCol + minRowMaxCol
here is my saddle point finder in python
import numpy as np
def is_saddle(row, column, *args):
index = 0
size = row * column
matrix = np.arange(size).reshape(row, column)
for i in range(row):
for j in range(column):
matrix[i][j] = args[0][index]
index = index + 1
print(matrix)
for item_row in matrix:
column_number = 0
min_item = np.amin(item_row)
for i in range(len(item_row)):
if min_item == item_row[i]:
row_number = i
reversed_matrix = matrix.transpose()
max_item = np.amax(reversed_matrix[row_number])
if max_item == min_item:
print("saddle point found : {}".format(min_item))
return matrix
row = input("enter row")
column = input("enter column")
matrix = input("enter the matrix items")
is_saddle(row, column, matrix)
input sample: row = 2, column = 3, matrix = (1,2,3,4,5,6)
I have a different approach, looking for saddle points which are local, based on a few auxiliary 2d arrays:
def find_saddle(arr2d):
xdiff = np.diff(arr2d, axis=0) # Derivative along 1st dim
ydiff = np.diff(arr2d, axis=1) # Derivative along 2nd dim
# Saddle points are not in the "boundary" elements
xdiff1 = xdiff[1: , 1:-1] # Shift matrix skipping 1st row
xdiff2 = xdiff[ :-1, 1:-1] # Cut the last row
ydiff1 = ydiff[1:-1, 1: ] # Same, for columns
ydiff2 = ydiff[1:-1, :-1]
# A saddle points is a local maximum/minimum in one dimension (xdiff1*xdiff2 < 0) and in the other dimension (ydiff1*ydiff2 < 0),
# but only in the combination max1&min2 or min1&max2 (xdiff1*ydiff1 < 0)
ind = np.where((xdiff1*xdiff2 < 0) & (ydiff1*ydiff2 < 0) &
(xdiff1*ydiff1 < 0))
saddle_points = []
if len(ind) > 0:
for j, x in enumerate(ind[0]):
saddle_points.append([x + 1, ind[1][j] + 1])
return saddle_points

Matrix Generator python index assignment list out of range

Below is the code I have written. It says the list assingment index is out of range. I can't seem to figure out where I've gone wrong here. Maybe someone could elaborate as to where the error is.
def genarator(x, y):
square = x * y
matrix = [[]]
matrix2 = []
i = 0
while square > 0:
j = 0
while x > j:
matrix[i][j] = int(raw_input("Enter the matrix number"))
j = 1
i = 1
square = -square
matrix2 = matrix2 + matrix
return matrix2
def main():
matrix3 = []
x = int(raw_input("Enter the width of your matrix"))
y = int(raw_input("Enter the Length of your matrix"))
matrix3 = genarator(x, y)
print(matrix3)
return 0
main()
###EDIT###########I SOLVED THE PROBLEM
def generator(x, y):
matrix = [[0 for i in range(x)] for j in range(y)]
turns = x
i = 0
j = 0
while turns > 0:
while i < x:
while j < y:
matrix[i][j] = int(raw_input("Enter Array values"))
j += 1
j = 0
i += 1
turns -= 1
print(matrix)
def main():
x = int(raw_input("Enter array length"))
y = int(raw_input("Enter array width"))
print(generator(x, y))
return 0
main()
If you try the following snippet:
x = []
x[0] = 4
You will see that there is an error. The reason for this is that x[0] has not yet been defined, so it can not be modified. To fix your error, you will have to append something to your list before modifying it:
def genarator(x, y):
square = x * y
matrix = [[]]
matrix2 = []
i = 0
while square > 0:
matrix.append([])
j = 0
while x > j:
matrix[-1].append(int(raw_input("Enter the matrix number")))
j = 1
i = 1
square = -square
matrix2 = matrix2 + matrix
return matrix2
I also modified the indexing because -1 will give you the last item, which is what you want.

Matrix multiplication in Python

Hello (excuse my English), I have a big doubt in python with matrix multiplication, I create a list of lists and multiplied by a scaling matrix, this is what I've done and I can not alparecer perform a multiplication operation problem with indexes, I check with paper and pencil and it works, I'm doing something bad to accommodate indexes or am I wrong accommodating matrices from the beginning?
def main():
if len(sys.argv) > 1:
v = int(sys.argv[1])
else:
print "error python exe:"
print "\tpython <programa.py> <num_vertices>"
A = []
for i in range(v):
A.append([0]*2)
for i in range(v):
for j in range(2):
A[i][j] = input("v: ")
print A
Escala(A)
def Escala(A):
print "Escala"
sx = input("Sx: ")
sy = input("Sy: ")
S = [(sx,0),(0,sy)]
print S
M = mult(S,A)
print M
def mult(m1,m2):
M = zero(len(m1),len(m2[0]))
for i in range(len(m2)):
for j in range(len(m2[0])):
for k in range(len(m1)):
M[i][j] += m1[k][j]*m2[k][j]
print M
return M
def zero(m,n):
# Create zero matrix
new_matrix = [[0 for row in range(n)] for col in range(m)]
return new_matrix
This seems wrong to me:
M[i][j] += m1[k][j]*m2[k][j]
shouldn't it be:
M[i][j] += m1[i][k]*m2[k][j]

Categories