【问题标题】:Receiving type error when comparing two variables python 3比较两个变量python 3时收到类型错误
【发布时间】: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


【解决方案1】:

您的实现中存在一些错误

  1. 如果输入是有效数字,则搜索块将执行,因此,在 try 块中,您必须存储 n 的值,即 n=int(n)
  2. 如果列表中不存在n,则l=midh=mid 将无限运行while 循环,因为您已经检查了索引mid,因此在while 循环中设置l=mid+1h=mid-1的二分查找。

    请在需要更改的地方查看下面的 cmets 代码

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:
            n=int(n)                        # if input is valid value then seaching will be done so store that number 
            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+1           # as index mid has already checked so set l=mid+1
            else:
                h = mid-1           # mid has already checked so set h=mid-1
            
Search(list)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-20
    • 2020-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多