# CSE 481E # Python Warmup Excercise Questions 2-5 from numpy import * # 2. Higher-Order Functions in Python # scale takes a number n, and a list of numbers s, and returns # a new list with each element in s multiplied by n. def scale(n, s): return map(lambda x: n*x, s) # evens takes a list of numbers as an argument, and returns a list of just # the even numbers def evens(s): return filter(lambda n: n%2==0, s) # make_table function def make_table(n): ns = arange(n) return vstack( ( ns, sqrt(ns), ns*ns, log(ns), exp(ns) ) ) # Random tester def rand_tester(n): # Take the sum of an array consisting of 1s for every random element # greater than 0.5, and 0 for every other random element: return sum (where (random.rand(n) > 0.5, 1, 0)) # Desirability computations def desirable_apartment_count(incomes, rents): # Desirability is the outer product of the rents and 1/incomes cost_to_income = outer(rents, 1.0 / incomes) # Desirable counts are the number of elements less than 1/3 in each column: return sum( where (cost_to_income < 1/3., 1, 0), axis = 0)