""" BJC : Beauty and Joy of Computing """ """ Besides Blocks II code examples """ """ Author: Dan Garcia, UC Berkeley """ """ License: (CC BY-NC-SA 3.0) """ import functools import math """Let's start with our classic Acronym""" def acronym(sentence): """Return the acronym of the input sentence.""" return(functools.reduce(lambda L,R:L+R, (map(lambda word:word[0], filter(lambda word: len(word)>3, sentence.split(" ")))))) print("acronym('The United States of America') = " + acronym("The United States of America")) """Let's take a look at the wordvalue question from the midterm""" testdictionary = ('and', 'bob', 'ralph') dictfileptr = open('/usr/share/dict/words') dictionary = list(map(lambda word: word[:-1].lower(),dictfileptr.readlines())) dictfileptr.close() def lettervalue(letter): """Return the value of a lowercase letter (a=1, b=2, ..., z=26)""" return ord(letter)-ord('a')+1 def wordvalue(word): """Return the value of a word (the sum of all its letters, a=1, b=2, etc)""" return functools.reduce(lambda x,y:x+y, map(lettervalue,word)) def wordswithmyvalue(word): """Return all words in 'dictionary' (global) that have the same word value as the input""" return list(filter(lambda cword: wordvalue(cword) == wordvalue(word), dictionary)) print("The words that have the same value as 'cal' are:") print(wordswithmyvalue("cal")) """Now, how about the list-of-functions --> equivalent-function""" def compose(f,g): """Given two monadic functions f and g, return lambda(x),f(g(x))""" return lambda x: f(g(x)) def oneplus(x): """Return 1+input""" return 1+x def double(x): """Return double the input""" return x+x oneplusdouble = compose(oneplus,double) print("1+(double(10)) = ", end="") print(oneplusdouble(10)) ### 21 print("1+(double(sqrt(100))) = ", end="") print(functools.reduce(compose,[oneplus,double,math.sqrt])(100)) ### 21