首页 > 解决方案 > 我的 python 代码的“int”和“NoneType”实例之间不支持“>=”

问题描述

我有以下代码,当我尝试运行它时,出现以下错误:'int' 和'NoneType' 的实例之间不支持'>='。这是python代码:

def quickSort (arr, left, right):

    #Checking the edge case 0 or 1 element subarray
    if left >= right:
        return arr
    
    #Setting our initial pivot to be the left, not random
    i = left

    #Swaping A[l] and A[i]
    to_swap = arr[left]
    arr[left] = arr[i]
    arr[i] = to_swap

    #We now define j to be our new pivot postion
    j = partition(arr, left, right)

    #Recurse on the first partition
    quickSort(arr, left, j)

    #Recurse on the second partition
    quickSort(arr, j + 1, right)

def partition(arr, left, right):
    p = arr[left]
    i = left + 1

    for j in range(left + 1, right):
        if arr[j] < p:

            #Swap A[j] and A[i]
            temp = arr[i]
            arr[i] = arr[j]
            arr[j] = temp

            #Restoring the invariant
            i = i + 1
        
        #Swap A[l] and A[i-1] which will allow us to place the pivot correctly
        temp = arr[left]
        arr[left] = arr[i-1]
        arr[i-1] = temp

        #Returning the final pivot postion 
        return i - 1 

我正在使用以下代码来运行我的程序:

arrayTest1 = []
x1 = time.time_ns()
textFile1 = open('test1.txt')
data_set1 = textFile1.readlines()

for i in data_set1:
    sortArray1 = i.strip()
    inputText1 = int(sortArray1)
    arrayTest1.append(inputText1)

n1 = len(arrayTest1)
quickSort(arrayTest1, 0, n1)
print("\n\nArray for test1.txt: " + str(arrayTest1))

y1 = time.time_ns()
totalTime1 = y1 - x1
print('Total Time for first Array: ' + str(totalTime1))

我 test1.txt 由简单的数组值 1-10 组成。这是显示我遇到的问题的回溯:

Traceback (most recent call last):
  File "main.py", line 64, in <module>
    quickSort(arrayTest1, 0, n1)
  File "main.py", line 25, in quickSort
    quickSort(arr, j + 1, right)
  File "main.py", line 22, in quickSort
    quickSort(arr, left, j)
  File "main.py", line 22, in quickSort
    quickSort(arr, left, j)
  File "main.py", line 7, in quickSort
    if left >= right:
TypeError: '>=' not supported between instances of 'int' and 'NoneType'

标签: python

解决方案


唯一包含 a 的行>=是这一行:

if left >= right:

该错误表明您无法将 anint与 a进行比较NoneType- 这意味着要么 要么leftrightan int,而另一个是None

我认为@tdelaney 找到了根本原因:

如果没有什么可以消耗的?然后分区返回 None (这可以解释你的错误)。

如果没有,请在开头添加一个检查/断点quicksort()以检查None并在找到输入时转储:

if left is None or right is None:
  print("Invalid call to 'quicksort()' with inputs:\na=%s, l=%s, r=%s" % (arr, left, right))
  breakpoint()

推荐阅读