Getting values for matrix in python - python

I'm new to python and I tried to store integer values in a 2 dimensional list using loops(I use this logic in C for getting input for matrix). When I run this code, it shows IndexError: list assignment index out of range. What caused this error?
Code to print numbers from 1-9 in matrix form:
num=1
a=[[]]
for i in range(0,3):
for j in range(0,3):
a[i][j]=num
++num
for i in range(0,3):
for j in range(0,3):
print(a[i][j]+" ")
print("\n")

You need to allocate the memory dynamically using append. Also, ++num will not do what you think here and you need num += 1.
num=1
a = []
for i in range(0,3):
a.append([])
for j in range(0,3):
a[i].append(num)
num += 1
for i in range(0,3):
for j in range(0,3):
print(str(a[i][j]) + " ", end="")
print("\n")
Also, you should look at the numpy library which makes the matrix operations and linear algebra easy, efficient and optimized. The equivalent code in numpy would be:
import numpy as np
mat = np.arange(1,10).reshape(3,3)
print(mat)

Related

Troubles taking a matrix from user's input, defining it as a list of lists

I want to make a program that takes inputs from the user to build an n x n matrix.
This is what I tried to do:
dim=int(input("Dimension of your matrix? "))
row=[]
matrix=[]
for i in range(dim):
for j in range(dim):
inp=float(input("Insert element with indeces: "+str(i+1)+" "+str(j+1)+" :"))
row.append(inp)
print(row)
matrix.append(row)
row.clear()
print("Your matrix is:")
print(matrix)
And although the printed rows are fine, the final matrix I print consists only of empty lists. It looks something like the following:
[[],[],[]]
Why is this happening?
.clear() modifies the row list in-place, and you're using the same list across different iterations of the outer loop. Under the hood, matrix list consists of references that point to the same memory as row. So, the removal of all the elements in row is reflected in the matrix as well.
To resolve, reassign the row variable to an empty list at the start of each iteration of the outer loop. This separates the memory used to store each row.
dim=int(input("Dimension of your matrix? "))
matrix=[]
for i in range(dim):
row = []
for j in range(dim):
inp=float(input("Insert element with indeces: "+str(i+1)+" "+str(j+1)+" :"))
row.append(inp)
print(row)
matrix.append(row)
print("Your matrix is:")
print(matrix)
You are using a shallow copy when you append a row in your matrix. So it just keep the address of your row, and when you clean the row at the end of your loop the amounts in your matrix is also cleaned. You need to use a deep copy. So, use this code, the when you are appending a new row:
matrix.append(row.copy())
The complete program will be:
dim=int(input("Dimension of your matrix? "))
row=[]
matrix=[]
for i in range(dim):
for j in range(dim):
inp=float(input("Insert element with indeces: "+str(i+1)+" "+str(j+1)+" :"))
row.append(inp)
print(row)
matrix.append(row.copy())
row.clear()
print("Your matrix is:")
print(matrix)

How can I get this nested for loop skip the first and the last list in the 2D array in order to print out a board surrounded with +'s?

The goal of my Python program is printing out a user-specified N^N board surrounded with +'s using a 2D array. To do that I first created a 2D list with N+2 lines and rows of +'s. Then using a nested for loop, I tried to replace the +'s with " " on indices 1 to N+1(not including) on each row except the first and the last rows, so that my code would print out a N^N board on the inside, surrounded with +'s. However I could not get my program to skip the first and last lines when erasing the +'s, despite excluding their indices in the 2D List in the nested for loop.
Thank you for your help in beforehand!
Here is my code.
This is the desired output (for N=5)
And this is the output of my code.
In your code, you do:
board =[['+'] * (N+2)] * (N+2)
This makes a list with N+2 references to the same list.
So everytime you change a 'middle square' to a white space inside your code(board[x][y] = " ") for a particular row x, you're infact actually changing all the tiles in the column y in your board to the white space simultaneously, since all the rows refer to but one list.
Instead, you should use something like this which actually creates (N+2) separate lists:
board =[['+'] * (N+2) for _ in range(N+2)]
This has also been explained in greater detail in this stackoverflow answer
Making the above change in the code results in the output you desire.
Although, it is a good practice to think of your own approaches & code it out when you're learning, but reading other people's code along with that will give you some hints towards multiple better approaches that you should eventually try to come up with. Here, are my two cents. Keeping it simple!
# board dimension
N = 5
# print board
def print_board(board):
for i in range(N):
for j in range(N):
print(board[i][j], end='')
print()
# declare & populate the board
board = []
for i in range(N):
row = []
for j in range(N):
row.append('+')
board.append(row)
# state of board initially
print_board(board)
print()
# Your logic of removing the plus sign, simply don't include the first & last
# row and column for converting into space
for i in range(1,N-1):
for j in range(1,N-1):
board[i][j] = ' '
print_board(board)
to make this pattern you can simply use for loops.
N = int(input())
for i in range(N+2):
for j in range(N+2):
if(i == 0 or i == N+1 or j == 0 or j == N+1):
print('+', end = '')
else:
print(' ', end = '')
print()

Check array to find if they are the same

I am new to programming in Python. I had used Matlab extensively. I want to check if in a 2D array,any two arrays are same. I have points lets say (x,y,z) coordinates in the format
data=[[x1,y1,z1],[x2,y2,z2]...[xn,yn,zn]].
I want to check if any point is equal to another point. And if there are any similar instance, i want to know how many are same and which two are same. The code i have in Python is something like
data = [[1,2,3],[3,1,8],[4,2,5],[1,2,3]]
s=0
for i in range(len(data)):
a=data[i]
for j in range(len(data)):
while i != j:
if data[j]==a:
s=s+1
c=i
d=j
print(s)
print(c,d)
and i also dont want the answer that point N is equal to point N etc
I also have used
for j in range(i,len(R)):
but it also dont give the correct answer.
This working well:
data =[[1,2,3],[4,5,6],[2,5,6],[0,9,1],[1,5,7],[2,5,4]]
st=[]
dic={}
while len(data)>1:
d = data[0]
data.remove(d)
st=[]
for dat in data:
k=0
for i in d:
if i in dat:
k=k+1
if k>1:
st.append(dat)
if len(st)>0:
dic[str(d)]=st
for key in dic.keys():
print(key," : ", dic[key])
Apparently, found a workthrough myself
d=[[1,2,3],[3,5,4],[5,6,9],[0,2,1],[1,2,3]]
s=0
for i in range(len(d)):
for j in range(i+1,len(d)):
if d[i]==d[j]:
s=s+1
x=i
y=j
print(s)
print(x,y)

Assign numpy ndarray to list

Can someone help me with my question. I have created a loop which in every execution produce a numpy.ndarray of size (5,) but when the loop terminates and I want to print the results of my code it only print the last ndarry of size 5, I tried to assigned the results in a list but I get "too many indices for array"
k=0;
for i in range(M):
for j in range(N):
if table[i, j] != 0:
k=k+1;
inv=np.linalg.inv(np.dot(X.T,X));
theta[k,:] = np.dot(inv,X.T).dot(HSI[i,j,:])
I want to assign the results on theta[] so if I want to print the result from the second execution I will write theta[1] and so on.
Most likely my false is on the last line
A quick sketch, you can amend as necessary
import random
a=[] #start with an empty set
k=0
while k< 5:
b=random.sample(range(1,100), 5) #get a random sample of length 5 within range of 1-100
a.append(b) # add/'append' b to your currently empty set of 'a'
print a #print current contents of 'a'
k=k+1
I've not run this but it seems intuitive.
Good luck!

2d Array Python :list index out of range

I am new to Python programming and I am trying to write code to check if a DFA( Deterministic Finite Automata) has empty language or not.
I am using 2-d array to store state of the DFA.
On executing the code I keep getting list index out of range. How can I fix this?
Below is the code
top=-1
count=0
n=int(input("\nEnter the no of states"))
mat=[[]]
b=[]
print("\nEnter the transition table")
for i in range(0,n):
for j in range(0,n):
mat.append(input())
finalState=input("\nEnter the final state:")
startState=input("\nEnter the start state:")
for i in range(0,n):
for j in range(0,n):
if mat[i][j]:
b[++top]=j
for k in range(top):
if b[k]==finalState:
count+=1
if count>0:
print("\nLanguage is not empty")
else:
print("\nLanguage is empty")
when you make a 2x2 table, you want mat to be [[1,2],[3,4]], but you're getting [[],1,2,3,4] right now.
Instead, try:
mat = []
for i in range(n):
row = []
for j in range(n):
row.append(input())
mat.append(row)
Also, Python does not have a "++" operator, so b[++top]=j is the same as b[top] = j. If you want to increment top, you have to do that on its own line before you use it to index the list.
On top of that, b has zero elements, so indexing it in any way will cause a crash. If you're trying to increase the size of b by adding new items to it, use append. Then you don't need a top variable at all.
b.append(j)

Categories