2017-04-04 80 views
0

我遇到以下代碼的問題。我試圖找到二叉搜索樹上兩個節點之間最不共同的祖先。我的代碼如下:'int'對象沒有屬性'val'

def Question4(T, r, p, q): 
    s, b = sorted([p.val, q.val]) 
    while not s <= r.val <= b: 
     r = r.left if s <= r.val else r.right 
    return r 
T = [[0, 1, 0, 0, 0], 
[0, 0, 0, 0, 0], 
[0, 0, 0, 0, 0], 
[1, 0, 0, 0, 1], 
[0, 0, 0, 0, 0]] 
r = 3 
p = 1 
q = 4 
Question4(T, r, p, q) 

當我試圖在這行代碼s, b = sorted([p.val, q.val])運行這段代碼我的終端輸出顯示AttributeError: 'int' object has no attribute 'val'我不知道什麼導致這,我擡頭一看類似的答案,但不能找到解決方案。如果有人有任何建議,我將不勝感激。

+1

對我來說似乎很簡單:'p'和'q'是整數。整數沒有'val'屬性。所以你不能做'p.val'或'q.val'。 – Kevin

回答

2

變量rpqint類型和他們沒有任何與之關聯的屬性val

現在你怎麼能找到它。使用內建函數dir

>>> r = 3 
>>> dir(r) 
['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__gt__', '__hash__', '__index__', '__init__', '__int__', '__invert__', '__le__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__round__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes'] 

你可以看到有一個與int對象相關聯的val屬性。

現在,如何解決上述問題。

def Question4(T, r, p, q): 
    s, b = sorted([p, q]) // remove .val 
    while not s <= r <= b: // remove .val 
     r = r.left if s <= r else r.right // also int doesn't have .right or .left attribute, you need to define your own class to represent this custom data type 
    return r 
T = [[0, 1, 0, 0, 0], 
[0, 0, 0, 0, 0], 
[0, 0, 0, 0, 0], 
[1, 0, 0, 0, 1], 
[0, 0, 0, 0, 0]] 
r = 3    // this is int object which don't have val attribute 
p = 1 
q = 4 
Question4(T, r, p, q) 
+0

這個答案和下面的答案都是正確的。謝謝你們的幫助。 – NoOrangeJuice

1

p,qr是整數。因此它們沒有val屬性。只是刪除.val這3個