def celsius_fahrenheit(c=0): # round(n, d) => arredonda n em d casas decimais return round(9. * c / 5. + 32., 2) def fahrenheit_celsius(f=0): return round(5. * (f - 32.) / 9., 2) # Testes print celsius_fahrenheit(123.0) print fahrenheit_celsius(253.4) # Testa se o número é primo def is_prime(n): if n < 2: return False for i in range(2, n): 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 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] 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 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" def ord_tab(dados, chave=0, reverso=False): # Rotina para comparar as tuplas em sort() def _ord(x, y): return x[chave] - y[chave] dados.sort(_ord, reverse=reverso) return dados # Testes t = [(1, 2, 0), (3, 1, 5), (0, 3, 3)] print ord_tab(t) print ord_tab(t, 1) print ord_tab(t, 2) # Mostra: # [(0, 3, 3), (1, 2, 0), (3, 1, 5)] # [(3, 1, 5), (1, 2, 0), (0, 3, 3)] # [(1, 2, 0), (0, 3, 3), (3, 1, 5)]