python - 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
解决方案
您将全局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
通过附加数据来让您的列表动态增长,而不是用一个非常大的列表来浪费内存。
推荐阅读
- security - pdfbox - 如何以增量方式签署更新的文档或更改
- python - 如何在公会中获取每个成员的ID
- reactjs - 有没有办法在 React 的函数中调用你的主要组件?
- javascript - 我在 vue js 的样式标签中加载背景图像时遇到问题
- java - 在Java中将double转换为无符号整数
- html - 在 HTML 的 vs 代码中禁用波浪黄色下划线
- python - 将图像转换为范围为 [0,255] 而不是 [0,1] 的张量?
- python - Conway 的生命游戏 Python / PyGame 打印错误
- python - 如何跟踪单个棋子的移动?
- javascript - 在服务器端发生帖子后,如何使用客户端 JavaScript 显示警报?