Practice Quesitons for E03, CS5NM, Fall 2008

Topic: Boolean Expressions

  1. Consider the following segment of code. It is part of the body of a function that checks three variables, x, y and z, each representing a side of a triangle. The function should return -1 if any of the sides is less than or equal to zero:
    if x <= 0:
       return -1
    elif y <= 0:
       return -1
    elif z <= 0:
       return -1  
      

    Fred notices that this can be simplified into a single if—we don't need the complication of the if/elif/elif here. What should we fill in for the condition of this single if? Fill in the blank below:

    
    if (_______________________________________):
       return -1
    
    
    Hint: think carefully: do you need and or do you need or?

    Here are some possible answers. Which of these are correct, and which of them are incorrect, and why?

    if x > 0 and y > 0 and z > 0:
        return -1

    if ( x or y or z <= 0 ):
        return -1

    if (x <=0 or  y<= 0  or z <= 0 ):
        return -1

    if not ( x > 0 and  y > 0  and z > 0 ):
        return -1

Topic: Recursion

We've gone over recursion in this course as it applies to lists in Python. We've looked at how to use recursion to do the following things in Python:

  1. Count all the things in a list that meet some criteria.
  2. Sum the things in a list.
  3. Find the minimum or the maximum of the items in a list.
  4. Change one list into another.
  5. Remove certain items from a list.
  6. Retain only certain items from a list