-2

Here's the problem I'm trying to wrap my head around:

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.

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!

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 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.

As you design the function, think very carefully about what the base cases should be.

Here's the code I tried to do. I'm getting errors, but I'm falling behind in understanding the basics of how to do this problem.

def isIn(char, aStr):
    '''
    char: a single character
    aStr: an alphabetized string

    returns: True if char is in aStr; False otherwise
    '''
    # Your code here
    middle_char = len(aStr)/2
    if char == middle_char:
        True
    elif char == "" or char == 1:
        False
    elif char < aStr[:middle_char]: 
        return isIn(char,aStr(middle_char)
    else: 
        return isIn(char, aStr(middle_char))
chepner
  • 497,756
  • 71
  • 530
  • 681
  • Welcome to StackOverflow. Please read and follow the posting guidelines in the help documentation. [Minimal, complete, verifiable example](http://stackoverflow.com/help/mcve) applies here. We cannot effectively help you until you post your MCVE code and accurately describe the problem. We should be able to paste your posted code into a text file and reproduce the problem you described. – Prune Jun 29 '17 at 23:51
  • We can see the assignment you've been assigned, but what question are *you* asking *us*? – user2357112 Jun 29 '17 at 23:53

2 Answers2

2

One reason you're falling behind is that you're trying to write a recursive function when you haven't yet mastered writing simple statements. You have about 10 lines of active code here, including at least four syntax errors and two semantic errors.

Back off and use incremental programming. Write a few lines of code, test them, and don't advance until you're sure they work as expected. Insert diagnostic print statements to check values as you go. For instance, start with force-fed values and no actual function call, like this:

# def isIn(char, aStr):
'''
char: a single character
aStr: an alphabetized string

returns: True if char is in aStr; False otherwise
'''

char = 'q'
aStr = "abcdefghijklmnopqrstuvwxyz"
print "parameters:", char, aStr

middle_char = len(aStr)/2
print len(aStr), middle_char

print "if", char, "==", middle_char, ":"

This gives you the output

parameters: q abcdefghijklmnopqrstuvwxyz
26 13
if q == 13 :

Obviously, a character is not going to equal the integer 13. Fix this before you go any further. Then you can try actually writing your first if statement.

See how that works?

Prune
  • 76,765
  • 14
  • 60
  • 81
0
middle_char = len(aStr)/2
 if char == middle_char:

Middle char is half the length (I.e. an integer value) It's not going to be equal to your char value.

middle_index = len(aStr)//2
middle_char = aStr[middle_index]

to actually get the middle char value. Note the integer division (//). we want to make sure that the resulting index is a whole number.

elif char == "" or char == 1:

you've already tested (well tried to) the case where there is one char left, you dont need to handle that specifically. You also need to test for empty string before you try extracting values.

elif char < aStr[:middle_char]: 

here you actually do try and index into the string. unfortunately, what you are actually doing is slicing it, and seeing if the secind hald of the string (middle character onwards) is equal to your char. this will only ever match if you are looking at a one character string. e.g. isin('d', 'd')

    return isIn(char,aStr(middle_char)
else: 
    return isIn(char, aStr(middle_char))

- Missing parenthesis on the first return ) - aStr() is not a function. you need [ and ] - you are trying to pass just a single char into the recursive call. you need to slice the string and pass the resulting sub-string into the recursive string - both of these (ignoring the missing bracket) are identical calls. you need one to call with the first half of aStr and one with the second half.

Your task says to think about the base cases. They are (I'm listing them because you almost got them spot on): - empty string (return False) - mid char = search char (return True) - mid char > search char (search left substring) - mid char < search char (search right substring)

note that there is no need to explicitly check for a non matching string with a length of 1, as that will pass an empty string into the next call

something for you to think about: why does the string need to be sorted? what happens if the string isnt sorted?

a working implementation:

def isin (char, str):
    if not str: 
        return False
    mid_index = len(str)/2
    mid_char = str[mid_index]
    return True if mid_char == char else isin(char, str[:mid_index] if mid_char > char else str[mid_index+1:])

DO NOT just use this code. This code is just for your reference so you can understand what it is doing and rewrite you code once you understand. There is no point in just copying the code if you dont understand it. It wont help you in the future.

You do seem to have the general idea of what you need to do (I'm guessing you have gone over this in class), but are lacking knowlege in the how (syntax etc).

I recommend going through the python tutorial in your own time, doing the exercises it takes you through. It will introduce you to the features of the language in turn and this will really help you.

good luck!

Baldrickk
  • 4,291
  • 1
  • 15
  • 27