# -*- coding: utf-8 -*- import timeit def min(m,n): if m < n: return m else: return n def min_of_three(n1,n2,n3): if n1 < n2: if n1 < n3: return n1 else: return n3 else: if n2 < n3: return n2 else: return n3 def min_of_three2(n1,n2,n3): return min(min(n1,n2),n3) def len1(lst): length = 0 for _ in lst: length += 1 return length def len2(lst): # 2.5 times slower... return sum(map(lambda x:1, lst)) def is_vowel(c): return c in 'aeiouAEIOU' def is_consonant(c): return c.isalpha() and not is_vowel(c) def translate(text): robber_text = '' for c in text: if is_consonant(c): robber_text += '%so%s' % (c,c) else: robber_text += c return robber_text def sum(numbers): num_sum = 0 for n in numbers: num_sum += n return num_sum def product(numbers): num_prod = 1 for n in numbers: num_prod *= n return num_prod def sum_reduce(numbers): return reduce(lambda m,n:m+n,numbers) def product_reduce(numbers): return reduce(lambda m,n:m*n,numbers) def reverse(s): rev ='' for c in s: rev = c+rev return rev def is_palindrome(lst): return lst == reverse(lst) def is_palindrome2(lst): return lst == lst[::-1] def is_member(x,lst): for y in lst: if x == y: return True return False def pad_with_n_chars(s,n,c): pad_length = n-len(s) if pad_length < 0: return s else: left = pad_length/2 if pad_length % 2 == 0: right = pad_length/2 else: right = pad_length/2+1 return c*left + s + c*right def histogram(data): for (s,n) in data: print '%s: %s' % (s,n*'*') def histogram_refined(data): max_length = max([len(s) for (s,_) in data]) for (s,n) in data: padded_s = '%s:%s' % (s,' '*(max_length-len(s))) print '%s %s' % (padded_s,n*'*') def min_in_list(lst): lst_min = lst[0] if len(lst) > 1: for n in lst[1:]: lst_min = min(lst_min,n) return lst_min else: return lst_min def find_shortest_word(words): min_len = len(words[0]) for word in words[1:]: min_len = min(min_len,len(word)) return min_len def find_shortest_word2(words): return min_in_list([len(word) for word in words]) def find_shortest_word3(words): return min(map(len,words)) def filter_long_words(words,n): long_words = [] for word in words: if len(word) > n: long_words.append(word) return long_words def filter_long_words2(words,n): return [word for word in words if len(word) > n] def translate(words,lang): eng_swe = {'merry':'god','christmas':'jul','and':'och','happy':'gott','new':'nytt','year':'år'} swe_eng = dict([(eng_swe[eng],eng) for eng in eng_swe]) if lang == 'Swedish': return [swe_eng[word] for word in words] elif lang == 'English': return [eng_swe[word] for word in words] else: raise ValueError, 'unknown language: %s' % lang def char_freq(s): d = dict() for c in s: if c in d: d[c] += 1 else: d[c] = 1 return d def char_freq_table(): print 'Enter filename: ', filename = raw_input() with open(filename) as f: s = f.read() freq = char_freq(s) freq_str = '' for (c,n) in freq.items(): freq_str += '%s: %i\n' % (repr(c),n) return freq_str