looping through the rows of a matrix in sage - python

I am trying to program a Graham-Schmidt process in sage and cannot figure out how to loop through the rows of an array.
def graham_schmidt(W):
a=0
U=W
for i in W.dims()[0]:# this is the not working part
print w
a=a+1
for j in xrange(0,-2):
a=a+1
U[i]=U[i]-(transpose(U[j])*w)/(transpose(U[j])*U[j])*U[j]
return a;

You're making things far too complicated. If W is not a sparse matrix, you can just do
for row in W:
Since you also need the row index, you can use Python's built-in enumerate:
for i, row in enumerate(W):
or (uglier)
for i in xrange(len(W.shape[0])):

Related

Python: Finding all 6x6 matrices where each value occurs only once in each column and row

I want to generate all 6x6 matrices in Python where each value (integer 1-6) occurs only once in each column and row (like a sudoku puzzle, except for the subgrids). Generating all possible 6x6 matrices and filtering afterwards is not an option I believe as there are ~1.3*10^17 possibilities.
I found that when picking a permutation of the sequence 1-6 (720 in total), the 2nd row for the matrix will only have 265 possibilities, with 3rd-4th-5th row having even less. 6th row should have only 1 possibility if the previous 5 rows have been picked.
I have tried the code below for a 3x3 matrix and it works, however I feel adding more nested loops with more comparisons is not the best way (if a way at all) to tackle this issue. It sounds like it should be doable with a recursion or list comprehension but I can't lay my finger on it.
import itertools
input_list = []
for f in itertools.permutations([1,2,3],3):
input_list.append(f)
for i in input_list:
input_listcopy = input_list.copy()
result = []
result.append(i)
input_listcopy.remove(i)
for j in input_listcopy:
if (i[0] != j[0] and i[1] != j[1] and i[2] != j[2]):
result.append(j)
print(result)
Just to be clear, the output I expect is a 2D list where each element is one row of the matrix, starting from the top:
[[1,2,3],[2,3,1],[3,1,2]]
Thanks in advance!
What about this?
from itertools import permutations
# Define the permutations
length = 6
elements = range(1, length+1)
result = []
for perm in permutations(elements, length):
if not result: # The first permutation is added
result.append(perm)
continue
is_valid_list = []
for row in result:
is_valid = all(perm[idx] != row[idx] for idx in range(length))
is_valid_list.append(is_valid)
if all(is_valid_list):
result.append(perm)
print(result)

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)

I get the error, list indices must be integers, do not know why?

for i in inpt:
for j in inpt[i]:
print j,
I want to access a 2D array, for each array i in inpt, I want to print each number j in the array i. I do not have any formal background in python and also I could not already find a solution on the internet.
Python for loops are foreach loops, in that you get the actual elements from the list and not an index. You are trying to use those elements as indices to inpt again.
Loop over i, not inpt[i], to get the matrix values:
for i in inpt:
for j in i:
print j,
I'd rename i to row to make this clearer:
for row in inpt:
for j in row:
print j,

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)

Having problems with code I wrote to get inverse of a matrix for each nonzero element and 0 to 0

I am totally new to programming, and I have written this function function to take a matrix and maps each nonzero element to its inverse and zero to zero in python. Here is my code:
def question_1_c(arr):
new_arr = []
for i in range(len(arr)):
row_arr = []
for j in range(len(arr[i])):
row_arr.append(1/ arr[i][j])
new_arr.append(row_arr)
return new_arr
question_1_c([[70,0,13,67],[90,48,57,26],[43,45,67,89],[88,65,44,23]])
For some reason it gives an error. Can anyone help?
The error that I got was a divide by zero, which makes sense because you're never checking for zero values. You're also doing integer division - which will not do what you expect it to do.
Also, in Python you can iterate over collections. I've rewritten your code, and this should do what you expect it to do.
def question_1_c(arr):
new_arr = []
for row in arr:
row_arr = []
for val in row:
if val:
row_arr.append(1.0/val)
else:
row_arr.append(val)
new_arr.append(row_arr)
return new_arr
the array has a 0 value, in [0,1] position... so in
1/ arr[i][j] the program do:
1/0, and that throw an exception.
You must consider this case do somethig like this:
if arr[i][j]==0:
...
else:
row_arr.append(1/ arr[i][j])

Categories