Dah*_*aka 21 list binary-search typeerror python-3.x
我有一个python 3.x程序产生错误:
def main():
names = ['Ava Fischer', 'Bob White', 'Chris Rich', 'Danielle Porter',
'Gordon Pike', 'Hannah Beauregard', 'Matt Hoyle',
'Ross Harrison', 'Sasha Ricci', 'Xavier Adams']
entered = input('Enter the name of whom you would you like to search for:')
binary_search(names, entered)
if position == -1:
print("Sorry the name entered is not part of the list.")
else:
print(entered, " is part of the list and is number ", position, " on the list.")
input('Press<enter>')
def binary_search(names, entered):
first = 0
last = len(names) - 1
position = -1
found = False
while not found and first <= last:
middle = (first + last) / 2
if names[middle] == entered:
found = True
position = middle
elif names[middle] > entered:
last = middle - 1
else:
first = middle + 1
return position
main()
Run Code Online (Sandbox Code Playgroud)
错误是:
TypeError: list indices must be integers, not float
Run Code Online (Sandbox Code Playgroud)
我无法理解此错误消息的含义.
Roc*_*key 45
看起来你正在使用Python 3.x. Python 3.x的一个重要区别是处理除法的方式.执行此操作时x / y,Python 2.x中将返回一个整数,因为十进制被截断(楼层划分).但是在3.x中,/运算符执行'true'除法,从而得到a float而不是整数(例如1 / 2 = 0.5).这意味着您现在正在尝试使用浮点引用列表中的位置(例如my_list[0.5],甚至my_list[1.0]),这在Python期望整数时将无法工作.因此,您可能首先要尝试使用middle = (first + last) // 2,调整以使结果返回您期望的结果.该//指示在Python 3.x的地板师
| 归档时间: |
|
| 查看次数: |
49002 次 |
| 最近记录: |