Homework Solution

Recursion

Problems to be Submitted (20 points)

  1. (5 points)

    def __le__(self,other):
        if self._isEmpty():
            return True          # empty list is less than or equal to anything
        elif other._isEmpty():
            return False         # cannot otherwise less than or equal to empty list
        else:
    	# both lists are non empty; compare the heads
    	if self._head < other._head:
    	    return True
    	elif self._head > other._head
    	    return False
    	else:
    	    # heads are the same; revert to rest
    	    return self._rest < other._rest
    

  2. (5 points)

    def index(self, value, start=0):
      if self._isEmpty():
        raise ValueError('OurList.index(x): x not in list')
      elif start == 0 and self._head == value:
        return 0
      else:
        return 1 + self._rest.index(value, max(start-1,0))
    

  3. (5 points)

    def binary(n):
      answer = str(n % 2)   # rightmost bit, for now
      if n >= 2:
        answer = binary(n // 2) + answer
      return answer
    

  4. (5 points)

    As a simple example, consider a call to search(['A', 'B'], 'C', 0, 1). In this case midIndex is set to 0, and since the target is greater than 'A', line 20 of the proposed code results in (indentical) call search(['A', 'B'], 'C', 0, 1). Therefore, we have an infinite process.


Extra Credit

  1. (2 points)

    def __getslice__(self,i,j):
        """
        Returns new list representing self[i:j]
    
        Assumes that i and j are non-negative.
        """
        if self._isEmpty() or i>=j:
            return OurList()    # a new empty list
        elif i>0:
            return self.rest.__getslice__(i-1,j-1)
        else:
            result = OurList()
            result.head = self.head
            result.rest = self.rest.__getslice__(0,j-1)
            return result
    


Last modified: Sunday, 25 April 2010