2017-01-30 4 views
2

객체가 힙 내부에 있는지 확인하려고합니다.힙 내부의 객체인지 확인

import heapq 

class Heap(object): 
    def __init__(self): 
     self.heap = [] 

    def push(self, priority, cell): 
     heapq.heappush(self.heap, (priority, cell)) 

    def pop(self): 
     cell = heapq.heappop(self.heap)[1] 
     return cell 

    def contains(self, cell): 
     if(cell in self.heap): 
      return True 
     return False 

    def isEmpty(self): 
     return len(self.heap) == 0 

이 셀 클래스 :

class Cell(object): 
    def __init__(self, x, y): 
     self.X = x 
     self.Y = y 

    def __eq__(self, other): 
     return int(self.X) == int(other.X) and int(self.Y) == int(other.Y) 

내가 Heap 클래스를 사용 나는이 같은 봐 HeapCell 클래스가

AttributeError: 'tuple' object has no attribute 'X' 

: 그러나, 나는이 오류가 계속 이렇게 : contains 메서드를 사용할 때 오류가 발생합니다.

from Heap import Heap 
from Cell import Cell 

class Test(object): 
    def __init__(self): 
     self.myHeap = Heap() 
     cell = Cell(2, 3) 

     self.myHeap.push(1, cell) 

     if self.myHeap.contains(cell) == False: 
      print("not in heap") 

test = Test() 

내가 뭘 잘못하고 있니? 어떤 도움을 주시면 감사하겠습니다.

+0

'self.myHeap'은 위에서 만든'Heap' 클래스의'Heap' 객체입니다. 더 명확하게하기 위해 더 많은 코드가 추가되었습니다. –

+0

'List'에서'priority'와'Object Cell'을 푸시하고 있습니까 ?? 그냥'셀'을리스트에 넣고'self.myHeap'은 무엇입니까? '자기'를 제거한 다음 당신이 무엇을 가지고 있는지 말해보십시오. –

+0

자기가 정의한 것을 확인했습니다. 코드를 편집하지 못했습니다. –

답변

1

문제는 contains 방법입니다.

def contains(self, cell): 
    if(cell in self.heap): 
     return True 
    return False 

self.head(priority, Cell) 튜플들의 목록이다. 그리고 실제로 Cells을이 목록의 요소 (튜플)와 비교하므로 Cell.__eq__() 메서드가 호출되고 예외가 발생합니다.

+0

그래서'(priority, Cell) .__ eq __()'를하려고합니까? 거기에 세포가 들어 있는지 확인할 방법이 있습니까? 나는 단지'셀'에있는'X'와'Y' 값과 비교할 수 있습니다. 꽤 많이 묻는 것은,'Cell' 객체를'__eq __()'메소드 내부에서 터플로 가져 오는 방법일까요? –

+1

네, 그렇지만 효과적인 방법은 아닙니다. [heap queue theory] (https://docs.python.org/2/library/heapq.html#theory)를보다 자세히 읽어보십시오. 어쨌든 당신이 할 수있는 것은''self inheap의 x에 대한 셀 [x [1] : ... '입니다. –

+0

감사합니다! 다시 힙 대기열 이론을 살펴 보겠습니다. –