Created
August 5, 2011 02:20
-
-
Save marcelcaraciolo/1126801 to your computer and use it in GitHub Desktop.
Final Dojo
This file contains hidden or 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
#-*-coding:utf-8 -*- | |
""" | |
Neste primeiro dojo, vamos tentar resolver um problema bem simples com o | |
objetivo de ter um primeiro contato com as bibliotecas Numpy e Scipy. | |
Problema: Dada uma matriz de dimensão qualquer, encontrar o elemento de | |
valor máximo e o elemento de valor mínimo. | |
Exemplos: | |
1) Para a matriz | |
[1 2 3 | |
4 5 6 | |
7 8 9], | |
de dimensão 3x3, o programa deve retornar 9 como sendo o máximo e 1 como sendo o mínino. | |
a | |
2) Para a matriz | |
[1 2 3 4 5], | |
de dimensão 1x5, o programa deve retornar 5 como sendo o máximo e 1 como sendo o mínimo. | |
""" | |
import numpy | |
from numpy.testing import assert_array_equal | |
import unittest | |
def max_min_matriz(matriz): | |
if matriz.size: | |
minimo,maximo = numpy.min(matriz), numpy.max(matriz) | |
''' | |
minimo,maximo = numpy.inf, - numpy.inf | |
if matriz.ndim == 1: | |
matriz_modificada = numpy.array([matriz]) | |
else: | |
matriz_modificada = matriz | |
if matriz_modificada.size: | |
for linha in matriz_modificada: | |
ordered_matriz = numpy.sort(linha) | |
minimo_linha,maximo_linha = ordered_matriz[0], ordered_matriz[-1] | |
if minimo_linha < minimo: | |
minimo = minimo_linha | |
if maximo_linha > maximo: | |
maximo = maximo_linha | |
''' | |
else: | |
raise ValueError('matriz vazia!') | |
return minimo,maximo | |
class TestMaxMinMatrix(unittest.TestCase): | |
def test_minmax_vector(self): | |
matriz = numpy.array([1,2,3,4,5]) | |
self.assertEquals((1,5), max_min_matriz(matriz)) | |
def test_empty_vector(self): | |
matriz = numpy.array([]) | |
self.assertRaises(ValueError,max_min_matriz,matriz) | |
def test_minmax_matriz(self): | |
matriz = numpy.array([ [1,2,3], [4,5,6] , [7,8,9] ]) | |
self.assertEquals((1,9), max_min_matriz(matriz)) | |
unittest.main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment