#!/usr/bin/env python # import required modules: # note that the path to the module htkmfc must be included in the # PYTHONPATH environment variable. # import os import sys from functools import reduce # function: square # # compute the square of a number # def square(x): return(x ** 2) # function: cube # # compute the cube of a number # def cube(x): return(x ** 3) # function: mymap # # a general mapping function # def mymap(aFunc, aSeq): result = [] for x in aSeq: result.append(aFunc(x)) return result # main program # def main(argv): # imperative: compute the sum of squares # items = [1, 2, 3, 4, 5] squared = [] for x in items: squared.append(x ** 2) print("imperative:") print(squared) print("") # functional: use map # print("functional (map):") print(list(map(square, items))) print("") # functional: use lambda # print("functional (lambda):") print(list(map((lambda x: x ** 2), items))) print("") # functional: list of functions # print("functional (lambda with function lists):") funcs = [square, cube] for r in range(5): value = map(lambda x: x(r), funcs) print(list(value)) print("") print("") # functional: mymap # print("functional (mymap):") print(list(map(square, [1, 2, 3]))) print(mymap(square, [1, 2, 3])) print("") # functional: multiple lists # x = [1, 2, 3] y = [4, 5, 6] from operator import add print("functional (multiple lists):") print(x, "+", y, '=', list(map(add, x, y))) print("") # filter: numbers less than zero # print("list (numbers less than zero):") print(list(range(-5,5))) print(list(filter((lambda x: x < 0), range(-5,5)))) print("") # lists: intersecting two lists # a = [1, 2, 3, 5, 7, 9] b = [2, 3, 5, 6, 7, 8] print("list (intersecting two lists using filter):") print(a) print(b) print(list(filter(lambda x: x in a, b))) print("") # lists: list comprehension # print("list (intersecting two lists using list comprehension):") print(a) print(b) print([x for x in a if x in b]) print("") # reduce: compute the sum # print("reduce (compute the sum):") print([1, 2, 3, 4]) print("sum product = ", reduce((lambda x, y: x * y), [1, 2, 3, 4])) print("sum ratio = ", reduce((lambda x, y: x / y), [1, 2, 3, 4])) print("sum new ratio = ", reduce((lambda x, y: y / x), [1, 2, 3, 4])) print("") # begin gracefully # if __name__ == "__main__": main(sys.argv[0:]) # # end of file