简体   繁体   中英

Searching a string of characters in python 3

Below is a program I have to work on for school, in which we must use the style I have outlined, but can't figure out why the program always returns string not found . Any idea as to why this is doing this? I am supposed to be using test functions and a debugger but that is beyond me. I fixed a recursion issue that was crashing the program.

def str_search(data, target, start, end):
    """
    str_search : String String NatNum NatNum -> NatNum or NoneType
    Description:
    Search for a target value in a sorted data string.
    The search happens between the start and end indices inclusively.
    This starts searching in the middle. If it finds the target, it is done.
    Otherwise it decides whether to search the first half or the second half.
    preconditions: the data string is in ascending alphanumeric order.
    Parameters:
        data - a string
        target - the target value to find is a single character string e.g. 'Q'
        start - the starting index into the data
        end - the ending index into the data
    Returns:
        index of target in data, if present; otherwise None.
    """

    if start <= end:
        return None

    mid_index = ( start + end ) // 2
    mid_value = data[mid_index]

    # debug statement prints the data.
    #print( "Searching for", target, ":", data[start:mid_index],
    #    "*" + str( mid_value ) + "*", data[mid_index+1:end+1] )

    if target == mid_value:
        return mid_index
    elif target <= mid_value:
        return str_search(data, target, start, mid_index - 1)
    else:
        return str_search(data, target, mid_index, end)


def find_target(data, target):
    """
    find_target : String String -> NatNum or NoneType
    find_target returns the index of target in data or None if not found.
    Parameters:
        data - a string
        target - the target value to find
    Returns:
        The index of the target element in data, if present, or None.
    """

    return str_search(data, target, 0, len(data) - 1)


def makeString():
    """
    makeString : () -> String
    makeString returns a String
    """
    data = ""
    # append characters to make the string
    for num in range(36, 108, 2):
        data += chr(num)
    return data


def main_search():
    """
    main_search : Void -> NoneType
    """

    data = makeString()
    print("Number of elements: ", len(data))

    while True:
        print("\nData: ", data)
        target = input("Enter a character to find: ")

        if target == "":
            break
        else:
            index = find_target(data, target)
            print()
            if index != None:
                print(target, "found at index", index)
            else:
                print(target, "not found")
                # end while


def test_str_search():
    """
    a suite of pass/fail test cases to validate that str_search works.
    """
    # Complete this test function.
    pass

#######################################################################
# 3.3. Document your debugging results trying to fix the str_search code.
# Enter answers to the questions below inside the triple-quoted string.
"""
    Were you able to completely fix str_search?
    If not, explain in detail the cases that still fail.
    What tool(s) did you use?
    What went well?
    What problems did you have?
"""
#######################################################################

if __name__ == "__main__":
    #
    # Run the test functions for problem 1, problem 2, and problem 3.
    #
    #test_create_multiplication_table()
    #test_is_palindrome()
    #test_is_reverse_of()
    test_str_search()
    #
    main_search()

in your search function you have this

if start <= end:
        return None

but your start is 0, and end is len(data) - 1, that is why you search function is returning nothing all the time.

This is fun, you need to test if your have reached the end, forwards or backwards on the binary search before you declare that nothing was found and you have to ensure that once you have reached the end of the search that the answer isn't left hiding at either end. You should get what you want with the following:

if end - start <= 1:
    if target == data[end]:
        return end
    elif target == data[start]:
        return start
    else:
        return None

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM