2012-09-24 3 views
0

저는 이것을 간단하게 유지하는 법을 모르겠습니다 ... 누군가가 내 코드를보고 싶고 제 기능이 왜 그렇게 작동하지 않는지 말해 주어야합니다 ...파이썬에서 제 수업을 호출 할 때의 문제

I 클래스가 있습니다

class PriorityQueue(object): 
'''A class that contains several methods dealing with queues.''' 

    def __init__(self): 
     '''The default constructor for the PriorityQueue class, an empty list.''' 
     self.q = [] 

    def insert(self, number): 
     '''Inserts a number into the queue, and then sorts the queue to ensure that the number is in the proper position in the queue.''' 
     self.q.append(number) 
     self.q.sort() 

    def minimum(self): 
     '''Returns the minimum number currently in the queue.''' 
     return min(self.q) 

    def removeMin(self): 
     '''Removes and returns the minimum number from the queue.''' 
     return self.q.pop(0) 

    def __len__(self): 
     '''Returns the size of the queue.''' 
     return self.q.__len__() 

    def __str__(self): 
     '''Returns a string representing the queue.''' 
     return "{}".format(self.q) 

    def __getitem__(self, key): 
     '''Takes an index as a parameter and returns the value at the given index.''' 
     return self.q[key] 

    def __iter__(self): 
     return self.q.__iter__() 

을 그리고 텍스트 파일을, 내 수업 시간에 몇 가지 방법을 통해 그것을 실행이 기능이 있습니다

def testQueue(fname): 
    infile = open(fname, 'r') 
    info = infile.read() 
    infile.close() 
    info = info.lower() 
    lstinfo = info.split() 
    queue = PriorityQueue() 
    for item in range(len(lstinfo)): 
     if lstinfo[item] == "i": 
      queue.insert(eval(lstinfo[item + 1])) 
     if lstinfo[item] == "s": 
      print(queue) 
     if lstinfo[item] == "m": 
      queue.minimum() 
     if lstinfo[item] == "r": 
      queue.removeMin() 
     if lstinfo[item] == "l": 
      len(queue) 
     #if lstinfo[item] == "g": 

나를 위해 무엇을 작동하지 않는 queue.minimum과 012에 대한 나의 전화입니다..

쉘에서 수동으로 작업하면 파일이 읽히고 파일의 지시 사항을 따라갈 때 작동하기 때문에 완전히 당황 스럽습니다. minimumremoveMin()은 작동하지 않습니다. 셸에 값을 표시하면 removeMin() 그러나 목록에서 가장 낮은 숫자가 제거됩니다.

클래스 메쏘드가 정의하는 것처럼 내가하고있는 것을 표시하지 않는 것은 무엇을 잘못하고 있습니까?

IE :

def minimum(self): 
    return min(self.q) 

내 기능에서 호출 할 때 최소를 표시하지 않나요?

+1

코드를 올바르게 들여 쓰고 {} 버튼을 사용하여 형식을 지정하십시오. – geoffspear

답변

6

아니요, def minimum(self): return min(self.q)은 호출시 아무 것도 표시하지 않습니다. print(queue.minimum())에서와 같이 출력을 인쇄하는 경우에만 표시됩니다. 예외는 Python 프롬프트/REPL에서 코드를 실행하는 경우입니다 (기본값은 표현식이 None이 아닌 경우입니다).

+0

그래서 올바른 출력을 얻기 위해 모든 if 문에 print 문을 삽입해야합니까? –

+0

맞습니다. – octern

+0

예, 맞습니다. 또는 각 if 문 내부에서'ret = queue.minimum()'과 같은 변수에 반환 값을 저장 한 다음 마지막'if' 문 다음에'print (ret)'를 쓸 수 있습니다. –

1

정상적으로 작동합니다. 당신은 가치를 반환하고 있습니다.

print queue.minimum() 

또는 캡처되지 반환 값을 인쇄

rval = queue.minimum() 
print rval 

대부분 통역의 유틸리티의 기능입니다 : 당신이 값을 표시하려면

은, 당신도 할 필요가있다. 자바 스크립트 콘솔에서 동일한 동작을 볼 수 있습니다.

관련 문제