probiner

Probiner - Week 3 Recursions Problem 8

Nov 2nd, 2012
254
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.46 KB | None | 0 0
  1. ##We can use the idea of bisection search to determine if a character is in a string, so long as the string is sorted in alphabetical order.
  2. ##
  3. ##First, test the middle character of a string against the character you're looking for (the "test character"). If they are the same, we are done - we've found the character we're looking for!
  4. ##
  5. ##If they're not the same, check if the test character is "smaller" than the middle character. If so, we need only consider the lower half of the string; otherwise, we only consider the upper half of the string. (Note that you can compare characters using Python's < function.)
  6. ##
  7. ##Implement the function isIn(char, aStr) which implements the above idea recursively to test if char is in aStr. char will be a single character and aStr will be a string that is in alphabetical order. The function should return a boolean value.
  8. ##
  9. ##As you design the function, think very carefully about what the base cases should be.
  10.  
  11. def isIn(char, aStr):
  12.     '''
  13.    char: a single character
  14.    aStr: an alphabetized string
  15.  
  16.    returns: True if char is in aStr; False otherwise
  17.    '''
  18.     # Your code here
  19.     aStr = str(aStr)
  20.     g=len(aStr)/2
  21.  
  22.     if aStr == '':  #can't use index here or it will crash on '' string
  23.         return False
  24.     elif aStr[g] == char: #this must be second to avoid '' crashes.
  25.         return True
  26.     elif char > aStr[g]:
  27.         return isIn(char,aStr[g+1:])
  28.     else:
  29.         return isIn(char,aStr[:g])
Advertisement
Add Comment
Please, Sign In to add comment