【问题标题】:Searching a string of characters in python 3在python 3中搜索字符串
【发布时间】:2015-12-25 04:08:42
【问题描述】:

下面是我必须为学校工作的一个程序,我们必须使用我概述的样式,但无法弄清楚为什么该程序总是返回string not found。关于为什么这样做的任何想法?我应该使用测试功能和调试器,但这超出了我的范围。我修复了导致程序崩溃的递归问题。

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()

【问题讨论】:

  • 您的搜索功能假定列表已排序。

标签: python string python-3.x search


【解决方案1】:

这很有趣,在声明没有找到任何内容之前,您需要在二进制搜索中测试您是否已经到达终点,向前或向后,并且您必须确保一旦到达搜索终点,答案没有留下隐藏在任何一端。你应该得到你想要的东西:

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

【讨论】:

    【解决方案2】:

    在你的搜索功能中你有这个

    if start <= end:
            return None
    

    但你的开始是 0,结束是 len(data) - 1,这就是为什么你的搜索功能一直没有返回任何东西。

    【讨论】:

      猜你喜欢
      • 2013-11-22
      • 2016-07-04
      • 1970-01-01
      • 1970-01-01
      • 2015-05-28
      • 2020-04-12
      • 2017-02-11
      • 1970-01-01
      • 2023-03-29
      相关资源
      最近更新 更多