0

我无法让这种二进制排序正常工作。lower_bound我在其他地方遇到语法错误。我知道这很明显,但我正处于办公桌的转折点。有人可以帮我让它清晰运行吗,我知道这是基本的东西,但我对此很陌生。

def main():
    sortNames()
    binarySearch()


def sortNames():
    global names
    names = ["Chris Rich", "Ava Fischer",  "Bob White", "Danielle Porter", "Gordon Pike", "Hannah Beauregard", "Matt Hoyle", "Ross Harrison", "Sasha Ricci", "Xavier Adams"]
    names.sort()


def binarySearch():
    global names, found, nameSearch, lower_bound, middle_pos, upper_bound
    nameSearch = string(input("What name are you looking for?")
    lower_bound = 0
    upper_bound = len(names)-1
    found = False
    while lower_bound <= upper_bound and not found:
        middle_pos = (lower_bound+upper_bound) // 2
        if name_list[middle_pos] < nameSearch:
            lower_bound = middle_pos + 1
        elif name_list[middle_pos] > nameSearch:
            upper_bound = middle_pos - 1
        else:
            found = True

    if found:
        print("The name is at position", middle_pos)
    else:
        print("The name was not in the list.")                               


main()
4

2 回答 2

4

您忘记在前一行添加最后一个右括号:

nameSearch = string(input("What name are you looking for?")
#               1--^  2--^                             2--^ 

另外,您没有定义 function string()。不需要它,已经input()返回一个字符串。

之后,我看到 的错误name_list,但大概您在此处发布的代码之外定义了该列表。

于 2013-11-10T22:49:58.537 回答
0
names = ["Chris Rich", "Ava Fischer",  "Bob White",\
         "Danielle Porter", "Gordon Pike", "Hannah Beauregard",\
         "Matt Hoyle", "Ross Harrison", "Sasha Ricci", "Xavier Adams"]

def sortNames():
    global names
    names.sort()

def binarySearch():
    global names, found, nameSearch, lower_bound, middle_pos, upper_bound

    nameSearch = raw_input("What name are you looking for?")
    lower_bound = 0
    upper_bound = len(names)-1
    found = False
    while lower_bound <= upper_bound and not found:
        middle_pos = (lower_bound+upper_bound) // 2
        if names[middle_pos] < nameSearch:
            lower_bound = middle_pos + 1
        elif names[middle_pos] > nameSearch:
            upper_bound = middle_pos - 1
        else:
            found = True
    if found:
        print("The name is at position", middle_pos)
    else:
        print("The name was not in the list.")                           

def main():
        sortNames()
        binarySearch()


if __name__ == "__main__":
    main()

输出

anukalp@anukalp-Latitude-E6400:~$ python del1.py
What name are you looking for?Ross Harrison
('The name is at position', 7)
于 2014-04-18T05:17:18.847 回答