Estimated time to complete:18 minutes
We can use the idea of bisection search to determine if a character are in a string, so long as the string is sort Ed in alphabetical order.
First, test the middle character of a string against the character you ' re looking for (the "test character"). If They is the same, we are done-we ' ve found the character we ' re looking for!
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.)
Implement the function isIn(char, aStr)
which implements the above idea recursively to test if are in. 'll be char
aStr
char
a Sin GLE character and'll be a string, that's in aStr
alphabetical order. The function should return a Boolean value.
As you design the function, think very carefully on what is the base cases should be.
def isIn (char, ASTR):
‘‘‘
CHAR:A single character
Astr:an alphabetized string
Returns:true if Char is in ASTR; False otherwise
"This is the answer I wrote:
# Your code here
If Len (aStr) = = 0:
Return False
Elif len (aStr) = = 1:
if aStr = = Char:
Return True
Else
Return False
Else
if char = = Astr[len (aStr)//2]:
Return True
Elif Char < Astr[len (ASTR)//2]:
Return IsIn (char, Astr[:len (ASTR)//2])
else:
Return IsIn (char, Astr[len (ASTR)//2+1:])
def isIn (char, ASTR): "This is the standard answer: char:a single character Astr:an alphabetized string returns:true if char I s in AStr; False otherwise ' # Base case:if aStr is empty, we do not find the char. if aStr = = ": Return False # Base case:if aStr is of length 1, just see if the chars is equalIf Len (aStr) = = 1:return AStr = = Char# Base Case:see If the character in the middle of aStr equals the # test character midindex = Len (aStr)//2 MidC Har = Astr[midindex] if char = = Midchar: # We found the character! Return True # Recursive case:if The test character is smaller than the middle # character, recursively search on The first half of AStr elif Char < Midchar:return isIn (char, Astr[:midindex]) # Otherwise the test character is larger than the middle character, # so recursively search on the last half of AStr Else:return IsIn (Char, a Str[midindex+1:])
Although the first time to see this problem, I was crazy, do not understand the meaning of the topic. But when I look at it again, I suddenly understand. Test instructions: Use dichotomy and recursion to find the required character in a string that is arranged from small to large. Finally my answer is correct, can see: I and the answer of the thought is the same, but it is written more concise, this need to learn.
MITX:6.00.1X Introduction to Computer science and programming Using Python Week 2:simple Programs 4. Functions