【发布时间】:2020-07-22 22:59:00
【问题描述】:
Python 3 代码
import time
list = [1,2,3,4,2323449,1,525]
def Search(arr):
# sorting
i = 0
print(f"Given list: {list}")
print("Sorting...")
time.sleep(1.75)
for i in range(len(list)):
if i + 1 >= len(list):
break
elif list[i + 1] < list[i]:
list.sort()
print("List has been sorted ")
print(f"Sorted list: {list}")
#---------------------------------------
# searching
inputCheck = True
while inputCheck:
n = input("Enter a number to find in the list: ")
try:
int(n)
inputCheck = False
except ValueError or TypeError:
print("Please enter a number")
time.sleep(0.6)
print("Searching...")
l = 0
h = len(list) - 1
while l <= h:
mid = (l + h) // 2
if list[mid] == n:
pos = mid
print(f"Found at index {pos}")
break
else:
print(n)
if list[mid] < n:
l = mid
else:
h = mid
Search(list)
我正在尝试制作一个二进制搜索程序,用户在其中输入需要在列表中找到的数字,但是当执行此代码时,我收到此错误:
if list[mid] < n:
TypeError: '<' not supported between instances of 'int' and 'str'
任何帮助将不胜感激!!!
【问题讨论】:
-
input("Enter...)给你一个字符串。稍后你将它与一个数字进行比较。您可以将输入行转换为 int:n = int(input("Enter a number to find in the list: ")) -
或者在您的“try”块中...您需要通过执行以下操作来捕获 n 到 int 的转换:
n = int(n)
标签: python-3.x type-conversion