from operator import add, mul from functools import reduce def count(s, value): """Count the number of occurrences of value in sequence s. >>> count( (1, 2, 1, 2, 1), 1) 3 """ total = 0 for elem in s: if elem == value: total = total + 1 return total def count_same(pairs): """Count the number of pairs that are the same value repeated. >>> pairs = ((1, 2), (2, 2), (2, 3), (4, 4)) >>> count_same(pairs) 2 """ same_count = 0 for x, y in pairs: if x == y: same_count = same_count + 1 return same_count few = range(-2, 2) many = range(-2, 5000000) def fib(k): """Compute the kth Fibonacci number. >>> fib(1) 0 >>> fib(2) 1 >>> fib(11) 55 """ prev, curr = 1, 0 # curr is the first Fibonacci number. for _ in range(1, k): prev, curr = curr, prev + curr return curr def string_demos(): 'here' in "Where's Waldo?" 'Mississippi'.count('i') 'Mississippi'.count('issi') print('\a') hex(ord('A')) print('1\n2\n3') from unicodedata import lookup, name name('a') lookup('WHITE FROWNING FACE') lookup('SNOWMAN') lookup('SKULL AND CROSSBONES') lookup('THAI CHARACTER KHOMUT') frown = lookup('WHITE FROWNING FACE') len(frown) len(frown.encode('utf8')) dir('') "a midsummer-night's dream".title() numbers = ('one', 'two', 'three', 'four') 'A ' + ', and a '.join(numbers) '{0} in hex is {1}'.format('a', hex(ord('a'))) '{0} in hex is {1:X}'.format('a', ord('a')) map_demo = map(print, (1,2,3,4)) def iseven(n): return n % 2 == 0 def sum_even_fibs(n): """Sum the first n even Fibonacci numbers. >>> sum_even_fibs(11) 44 """ return sum(filter(iseven, map(fib, range(1, n+1)))) def first(s): return s[0] def iscap(s): return len(s) > 0 and s[0].isupper() def acronym(name): """Return a tuple of the letters that form the acronym for name. >>> acronym('University of California Berkeley') ('U', 'C', 'B') """ return tuple(map(first, filter(iscap, name.split()))) def sum_even_fibs_gen(n): """Sum the first n even Fibonacci numbers. >>> sum_even_fibs_gen(11) 44 """ return sum(fib(k) for k in range(1, n+1) if fib(k) % 2 == 0) def acronym_gen(name): """Return a tuple of the letters that form the acronym for name. >>> acronym_gen('University of California Berkeley') ('U', 'C', 'B') """ return tuple(w[0] for w in name.split() if iscap(w)) bugg = 'University of California Berkeley Undergraduate Graphics Group' sum_even_fibs(11) acronym(bugg)