簡體   English   中英

TypeError:在 Python 中的“int”和“NoneType”實例之間不支持“>”

[英]TypeError: '>' not supported between instances of 'int' and 'NoneType' in Python

我的代碼中出現此錯誤:

文件“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列表初始化為 5005 None的列表。 這意味着len(pope)將評估為 5005。您用於測試的數據的值遠小於 5005。

當您調用upper_bound_search()時,您可以這樣稱呼它:

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

這意味着hi的值為 5004 (5005 - 1 = 5004)。

在您的main() function 中,您僅填充pope全局列表的前P個索引:

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

因此,只有列表中的前P個項目將具有 integer 值,而列表中的所有其他項目將具有值None 根據您提供的測試數據, P遠小於 5005。

然后,當線

if x > arr[hi]:

upper_bound_search()中達到, hi的值為 5004。 arr[hi]的計算結果為Nonex是 integer。 >運算符沒有為None定義,因為說None小於或大於某個數值沒有任何意義。

您可以嘗試將P-1作為hi的值傳遞。 或者您也可以嘗試通過附加數據來讓您的pope列表動態增長,而不是用非常大的列表浪費 memory。

在您的全球聲明中

MAX = 5005

Y,P,pope = None,None,[None] * MAX

您在上限搜索中比較變量 pope 的 int 和 none。 None 是 python 中的非值,等效於某些其他編程語言中的 null。 考慮在數組中使用 0,這樣您就可以執行 integer 比較。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM