Exercise 1

Readings. Lecture Notes 1.2-1.5

ex1.py

Q1. Fill in the following function definition for adding a to the absolute value of b , without calling abs :

				from operator import add, sub
				def a_plus_abs_b(a, b):
				    """Return a+abs(b), but without calling abs.

				    >>> a_plus_abs_b(2, 3)
				    5
				    >>> a_plus_abs_b(2, -3)
				    5
				    """
				    if ___:
				        op = ____
				    else:
				        op = ____
				    return op(a, b)
				
			

Q2. Write a function that takes three positive numbers and returns the sum of the squares of the two larger numbers. Use only a single expression for the body of the function:

				def two_of_three(a, b, c):
				    """Return x*x + y*y, where x and y are the two largest of a, b, c.

				    >>> two_of_three(1, 2, 3)
				    13
				    >>> two_of_three(5, 3, 1)
				    34
				    >>> two_of_three(10, 2, 8)
				    164
				    >>> two_of_three(5, 5, 5)
				    50
				    """
				    "*** YOUR CODE HERE ***"
				
			

Q3. Write a if_function that returns true_result if condition is a true value, and false_result otherwise:

				def if_function(condition, true_result, false_result):
				    """Return true_result if condition is a true value, and false_result otherwise."""
				    
								
			

Q4. Write a product function that returns the product of the values of a function for n natural number arguments. Show how to define the factorial function in terms of product:

				def product(n, term):
				    """Return the product of the first n terms in a sequence.

				    term -- a function that takes one argument

				    >>> product(4, square)
				    576
				    """
				    "*** YOUR CODE HERE ***"
				
			
				def factorial(n):
				    """Return n factorial by calling product.

				    >>> factorial(4)
				    24
				    """
				    "*** YOUR CODE HERE ***"
				
			

Q5. Show that product is an instance of a more general function, called accumulate, with the following signature:

				def accumulate(combiner, start, n, term):
				    """Return the result of combining the first n terms in a sequence."""
				    
				    "*** YOUR CODE HERE ***"
				    
				    """
				    >>> accumulate(mul, 1, 4, square)
				    576
				        
				    """
    			
			
				def summation_using_accumulate(n, term):
				    """An implementation of summation using accumulate.

				    >>> summation_using_accumulate(4, square)
				    30
				    """
				    "*** YOUR CODE HERE ***"
    			
			
				def product_using_accumulate(n, term):
				    """An implementation of product using accumulate.

				    >>> product_using_accumulate(4, square)
				    576
				    """
				    "*** YOUR CODE HERE ***"
    			
			

Q6.

				def double(f):
				    """Return a function that applies f twice.

				    f -- a function that takes one argument

				    >>> double(square)(2)
				    16
				    """
				    "*** YOUR CODE HERE ***"