Data Science Academy - Python Fundamentos - Capítulo 4

Download: http://github.com/dsacademybr


In [1]:
# Versão da Linguagem Python
from platform import python_version
print('Versão da Linguagem Python Usada Neste Jupyter Notebook:', python_version())


Versão da Linguagem Python Usada Neste Jupyter Notebook: 3.7.6

Reduce


In [2]:
# Importando a função reduce do módulo functools
from functools import reduce

In [3]:
# Criando uma lista
lista = [47,11,42,13]

In [4]:
lista


Out[4]:
[47, 11, 42, 13]

In [5]:
# Função 
def soma(a,b):
    x = a + b
    return x

In [6]:
# Usando reduce com uma função e uma lista. A função vai retornar o valor máximo
reduce(soma, lista)


Out[6]:
113

In [7]:
from IPython.display import Image
Image('arquivos/reduce.png')


Out[7]:

In [8]:
# Criando uma lista
lst = [47, 11, 42, 13]

In [9]:
# Usando a função reduce() com lambda
reduce(lambda x,y: x+y, lst)


Out[9]:
113

In [10]:
# Podemos atribuir a expressão lambda a uma variável
max_find2 = lambda a,b: a if (a > b) else b

In [11]:
type (max_find2)


Out[11]:
function

In [12]:
# Reduzindo a lista até o valor máximo, através da função criada com a expressão lambda
reduce(max_find2, lst)


Out[12]:
47

Fim

Obrigado - Data Science Academy - facebook.com/dsacademybr