Last active
July 3, 2017 00:32
-
-
Save fcschmidt/71b78a6accd3f42f728e0a61e6a62639 to your computer and use it in GitHub Desktop.
Exemplo simples de como fazer operações com as diagonais (principal e secundária) de uma matrix.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
0 0 0 0 0 | |
0 0 0 0 0 | |
0 0 0 0 0 | |
0 0 0 0 0 | |
0 0 0 0 0 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
""" | |
Exemplo simples de como fazer operações com as diagonais (principal e secundária) | |
de uma Matriz, sem utilizar Numpy ou qualquer outra lib que facilitaria esse processo. | |
Recebe como input uma sequência de números de um arquivo .txt | |
e gera uma matrix à partir deles. | |
Neste caso corresponde à uma matriz de 5x5 | |
Input: | |
0 0 0 0 0 | |
0 0 0 0 0 | |
0 0 0 0 0 | |
0 0 0 0 0 | |
0 0 0 0 0 | |
Output: | |
As duas diagonais da matrix. | |
[1, 0, 0, 0, 1] | |
[0, 1, 0, 1, 0] | |
[0, 0, 2, 0, 0] | |
[0, 1, 0, 1, 0] | |
[1, 0, 0, 0, 1] | |
""" | |
def diagonalPrincipal(m): | |
""" | |
Soma os elementos da Diagonal Principal com um valor qualquer | |
neste caso esta sendo somado +1 aos valores da diagonal principal | |
podendo ser qualquer tipo de operação matemática. | |
Resultado: | |
1 0 0 0 0 | |
0 1 0 0 0 | |
0 0 1 0 0 | |
0 0 0 1 0 | |
0 0 0 0 1 | |
""" | |
ac = 0 | |
m1 = [] | |
while ac <= len(m) - 1: | |
vet = m[ac] | |
vet[ac] += 1 | |
ac += 1 | |
m1.append(vet) | |
return m1 | |
def diagonalSecundaria(m): | |
""" | |
Soma os elementos da Diagonal Secundário com um valor qualquer | |
neste caso esta sendo somado +1 aos valores da diagonal secundária | |
também podendo ser qualquer tipo de operação matemática | |
Resultado: | |
0 0 0 0 1 | |
0 0 0 1 0 | |
0 0 1 0 0 | |
0 1 0 0 0 | |
1 0 0 0 0 | |
""" | |
dec = len(m) - 1 | |
aux = 0 | |
m2 = [] | |
while dec >= 0: | |
vet = m[aux] | |
vet[dec] += 1 | |
m2.append(vet) | |
dec -= 1 | |
aux += 1 | |
return m2 | |
def main(): | |
input_file = 'input.txt' | |
output_file = 'output.txt' | |
matrix = [] | |
for row in open(input_file, 'rb'): | |
int_ = [int(z) for z in row.split()] | |
matrix.append(int_) | |
diagonalPrincipal(matrix) | |
res = diagonalSecundaria(matrix) | |
with open(output_file, 'w') as o: | |
for r in res: | |
print(r) | |
o.write('{}\n' .format(''.join(str(r)))) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment