Python 3.x中的二进制字符串搜索 [英] Binary string search in Python 3.x

查看:340
本文介绍了Python 3.x中的二进制字符串搜索的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法使这种二进制排序正常工作.我在lower_bound和其他地方收到语法错误.我知道这很明显,但是我已经到了工作要点.有人可以帮我使它清楚地运行吗,我知道这是基本知识,但是我对此还很陌生.

I am having trouble getting this binary sort to work. I get syntax errors at lower_bound and in other places. I know it is something obvious but I am getting to the desk flipping point. Can someone help me to get this to run clearly, I know this is basic stuff but I am fairly new to this.

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

推荐答案

您忘了在之前行上添加最后一个右括号:

You forgot to add the last closing parenthesis on the preceding line:

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

此外,您没有定义功能string().并不是必须的,input()返回一个字符串已经.

Also, you didn't define the function string(). Not that it is needed, input() returns a string already.

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

After that, I see an error for name_list, but presumably you have that list defined outside of the code posted here.

这篇关于Python 3.x中的二进制字符串搜索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆