21.12.2022 Views

python_para_desenvolvedores_2ed

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

330 Respostas dos exercícios I

if not n % i:

return False

else:

return True

# Para x de 1 a 100

for x in range(1, 101):

if is_prime(x):

print x

3. Implementar uma função que receba uma lista de listas de comprimentos

quaisquer e retorne uma lista de uma dimensão.

Solução:

def flatten(it):

"""

"Achata" listas...

"""

# Se for uma lista

if isinstance(it, list):

ls = []

# Para cada item da lista

for item in it:

# Evoca flatten() recursivamente

ls = ls + flatten(item)

return ls

else:

return [it]

# Teste

l = [[1, [2]], [3, 4], [[5, 6], 7]]

print flatten(l)

# imprime: [1, 2, 3, 4, 5, 6, 7]

4. Implementar uma função que receba um dicionário e retorne a soma, a

média e a variação dos valores.

Solução:

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!