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.

Respostas dos exercícios I 331

# -*- coding: latin1 -*-

def stat(dic):

# Soma

s = sum(dic.values())

# Média

med = s / len(dic.values())

# Variação

var = max(dic.values()) - min(dic.values())

return s, med, var

5. Escreva uma função que:

▪ Receba uma frase como parâmetro.

▪ Retorne uma nova frase com cada palavra com as letras invertidas.

Solução:

def reverse1(t):

"""

Usando um loop convencional.

"""

r = t.split()

for i in xrange(len(r)):

r[i] = r[i][::-1]

return ' '.join(r)

def reverse2(t):

"""

Usando Generator Expression.

"""

return ' '.join(s[::-1] for s in t.split())

# Testes

f = 'The quick brown fox jumps over the lazy dog'

print reverse1(f)

print reverse2(f)

# mostra: "ehT kciuq nworb xof spmuj revo eht yzal god"

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

Saved successfully!

Ooh no, something went wrong!