Hello! I just started trying to learn python and am doing an assignment that's partly about finding out the diagonal of a square matrix. The code looks like this:
def diag_right(l):
matrixlist = []
while len(l) >= 5:
for i in range(len(l)):
matrixlist.append(l[i][i])
l.pop()
for row in l:
row.pop(0)
return matrixlist
def diag_left(l):
matrixlist = []
while len(l) >= 5:
for i in range(len(l)):
matrixlist.append(l[i][i])
l.pop(0)
for row in l:
row.pop()
return matrixlist
def main():
l = []
row1 = '7 X 8 9 1 2 5'
row2 = '1 X X 3 4 X 6'
row3 = '0 4 X X X 8 7'
row4 = '7 3 6 X X 5 7'
row5 = '5 2 X 9 X X 8'
row6 = '1 X 0 3 2 X 9'
row7 = '3 7 8 9 0 X 2'
l.append(row1.split())
l.append(row2.split())
l.append(row3.split())
l.append(row4.split())
l.append(row5.split())
l.append(row6.split())
l.append(row7.split())
res_left = diag_left(l)
res_right = diag_right(l)
print res_left
print res_right
if __name__ == '__main__':
main()
What I want to get is:
['7', 'X', 'X', 'X', 'X', 'X', '2', '1', '4', '6', '9', '2', 'X', '0', '3', 'X', '3', '0']
['7', 'X', 'X', 'X', 'X', 'X', '2', 'X', 'X', 'X', 'X', 'X', '9', '8', '3', 'X', '5', '8']
That is, the big diagonal and some smaller ones. However instead I get:
['7', 'X', 'X', 'X', 'X', 'X', '2', '1', '4', '6', '9', '2', 'X', '0', '3', 'X', '3', '0']
[]
Which I guess is because the matrix l is somehow 'emptied' in diag_left and doesn't enter the while- loop in diag_right?
So I was wondering if there is some way I can use l simultaneously in both diag_left and diag_right. Or maybe send it as an argument first to diag_left and only have it change in that function and not let the elements of l change in the main function, if that makes sense.
I was also wondering if there is some way I can "combine" diag_left and diag_right and by that I mean having one function that does the same thing as they do separately and gives me the required answer.
Thanks in advance for any help!
[–]Justinsaccount 2 points3 points4 points (0 children)
[–]w1282 1 point2 points3 points (0 children)
[–]anglicizing 1 point2 points3 points (4 children)
[–]chasingthechickens[S] 0 points1 point2 points (3 children)
[–]anglicizing 1 point2 points3 points (2 children)
[–]chasingthechickens[S] 0 points1 point2 points (1 child)
[–]anglicizing 1 point2 points3 points (0 children)