首页 > 解决方案 > TypeError:Python 中的“int”和“NoneType”实例之间不支持“>”

问题描述

我的代码中出现此错误:

文件“C:\Users\angelica\Documents\ING.DE SISTEMAS\Semestre VI\ADA\popes.py”,第 35 行,在求解 upper_bound = upper_bound_search(popes, 0, len_popes-1 , n)

文件“C:\Users\angelica\Documents\ING.DE SISTEMAS\Semestre VI\ADA\popes.py”,第 9 行,在 upper_bound_search 如果 x > arr[hi]:

TypeError:“int”和“NoneType”
实例之间不支持“>” TypeError:“int”和“NoneType”实例之间不支持“>”。

我知道这一定是逻辑错误,但我似乎看不出问题出在哪里。如果有人可以帮助我,我将不胜感激。

from sys import stdin

MAX = 5005
Y,P,pope = None,None,[ None for _ in range(MAX) ]

def upper_bound_search(arr, lo, hi, x):
  if x <= arr[lo]:
    return lo
  if x > arr[hi]:
    return -1

  mid = ((lo+hi))//2
  if x == arr[mid]:
    return mid

  elif x > arr[mid]:
    if mid+1 <= hi and x <= arr[mid+1]:
      return mid+1
    else:
      return upper_bound_search(arr, mid+1, hi, x)
  else:
    if mid-1 >= lo  and x > arr[mid-1]:
      return mid
    else:
      return upper_bound_search(arr,lo, mid-1, x)



def solve(year, popes):
  a,b,c = -1, -1, -1
  len_popes = len(popes)
  for i in range(len_popes):
    y = popes[i] 
    n = y + year -1
    upper_bound = upper_bound_search(popes, 0, len_popes-1 , n)
    temp = (upper_bound - i)
    if a < temp :
      a = temp
      b = y
      c = popes[upper_bound]
  return a,b,c
def main():
  global Y,P,pope
  line = stdin.readline()
  while len(line)!=0:
    Y,P = int(line),int(stdin.readline())
    for p in range(P): pope[p] = int(stdin.readline())
    ans = solve(Y, pope)
    print('{0} {1} {2}'.format(ans[0], ans[1], ans[2]))
    line = stdin.readline()
    if len(line)!=0: line = stdin.readline()

main()

另外,我正在添加我用作测试的条目。

11
20
1
2
3
6
8
12
13
13
15
16
17
18
19
20
20
21
25
26
30
31

标签: python

解决方案


您将全局pope列表初始化为 5005None的列表。这意味着len(pope)将评估为 5005。您用于测试的数据的值远小于 5005。

当你打电话时upper_bound_search(),你这样称呼它:

upper_bound = upper_bound_search(popes, 0, len_popes-1 , n)

这意味着hi将有一个值 5004 (5005 - 1 = 5004)。

在您的main()函数中,您只填充全局列表的第一个P索引:pope

for p in range(P): pope[p] = int(stdin.readline())

因此,只有列表中的第一P项将具有整数值,而列表中的所有其他项将具有 value None。用你提供的测试数据,P比5005小很多。

然后,当线

if x > arr[hi]:

在 中达到upper_bound_search()hi值为 5004。arr[hi]计算结果为None,并且x是整数。>运算符没有为 定义,None因为说None小于或大于某个数值没有任何意义。

您可以尝试的是P-1作为hi. 或者您也可以尝试pope通过附加数据来让您的列表动态增长,而不是用一个非常大的列表来浪费内存。


推荐阅读