gpt4 book ai didi

python - 允许某人输入一个名称,该名称将传递给一个函数,该函数将使用二进制搜索来查看该名称是否包含在列表中

转载 作者:行者123 更新时间:2023-11-28 17:36:55 25 4
gpt4 key购买 nike

基本上,我需要创建一个程序,允许某人输入一个名称,然后将该名称传递给一个函数,该函数将使用二进制搜索来查看该名称是否包含在列表中。这是我到目前为止的代码:

def main():
SIZE = 10
names = ['Ava Fischer', 'Bob White', 'Chris Rich', 'Danielle Porter', 'Gordon Pike', 'Hannah Beauregard', 'Matt Hoyle', 'Ross Harrison', 'Sasha Ricci', 'Xavier Adams']

searchName=input("Enter name to search for: ")
index = binarySearch(names, searchName, SIZE)

if index != -1:
print ("The name is ", names(index))
else:
print (searchName,"was not found.")

def binarySearch(names, name, SIZE):
first = 0
last = SIZE - 1
position = -1
found = False


while (not found) and (first <= last):
middle = (first + last)/2

if middle == name:
found = True
position = middle
elif middle > name:
last = middle - 1
else:
first = middle + 1

main()`

运行错误的示例:

Enter name to search for: Ava Fischer
Traceback (most recent call last):
File "C:\Python30\NameSrch.py", line 31, in <module>
main()
File "C:\Python30\NameSrch.py", line 6, in main
index = binarySearch(names, searchName, SIZE)
File "C:\Python30\NameSrch.py", line 26, in binarySearch
elif middle > name:
TypeError: unorderable types: float() > str()

我知道为什么它会给我错误,但我似乎无法找到一种方法来更改我的代码以阻止此错误的发生。请在不过多更改我的代码的情况下实现解决方案。请记住,当您回答说我是编程方面的新手时,请保持友善 :) 现在是晚上 10 点,该程序将在午夜前到期,所以我真的需要一些帮助。谢谢!

最佳答案

我想我理解了这个问题。

二分搜索算法应该将排序列表的中间点(即“枢轴”)与搜索词进行比较。相反,您正在比较列表中间点的 INDEX。

middle = names[(first+last)/2] # values of names at pivot idx

更好的实现方式是:

def binary_search(needle, haystack):
start, end = 0, len(haystack)-1
while start < end:
pivot_idx = (start + end) // 2
pivot = haystack[pivot_idx]
if needle == pivot:
return True
if pivot_idx == start:
# edge case -- I'm sure a better algorithm
# would write this into the while condition
break
if needle < pivot:
end = pivot_idx
else:
start = pivot_idx
return False

现在是讨论测试的好时机吗?总是写测试!测试驱动开发非常有效!您应该能够在编写函数之前编写测试!

def test_bin_search():
tests = [(2, [1, 3, 4, 5, 6, 7], False),
(3, [1, 3, 4, 5, 6, 7], True),
("s", ['a','b','s','q'], True),
('anything', ['unsorted', 'lists', 'should', 'fail!'], False)]
for test in tests:
needle, haystack, result = test
assert binary_search(needle, haystack) == result
# there are modules such as unittest and nose that do a much
# better job of this than just running a series of asserts,
# but they're generally beyond the scope of a beginning student
# who's not specifically looking to learn TDD! If you're interested,
# I've written up a gist that has a basic implementation:
# https://gist.github.com/NotTheEconomist/cf2b57b218a4c978e82b

事实上,如果您运行这些测试,您会看到我在算法中遗漏的另一个案例!我将把它作为练习留给您来实现该案例:)

关于python - 允许某人输入一个名称,该名称将传递给一个函数,该函数将使用二进制搜索来查看该名称是否包含在列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29641058/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com