0

これを単純に保つ方法がわかりません...誰かが私のコードを見て、私の関数が正常に機能しない理由を教えてください...

私はクラスを持っています:

 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ですqueue.removeMin()

シェルで手動で行うとすべて機能します。ファイルを読み取ってファイル内の文字から指示を取得すると、機能しますが、シェルに値が表示されないため、完全に困惑していminimumますremoveMin()。ただし、removeMin()リストから最小の番号が削除されます。

クラスメソッドが定義するように、何をしているのかが表示されないのは何が間違っているのでしょうか?

IE:

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

関数から呼び出すときに最小値を表示するべきではありませんか?

4

2 に答える 2

6

No, def minimum(self): return min(self.q) won't display anything when called. It'll only display something if you print the output, as in print(queue.minimum()). The exception to this is when executing code from the Python prompt/REPL, which prints expressions by default (unless they're None).

于 2012-09-24T02:45:14.927 に答える
1

It's working as it should. You're just returning a value.

If you want the value to display, you need to do either:

print queue.minimum()

or

rval = queue.minimum()
print rval

Printing an uncaptured return value is a utility feature of most interpreters. you'll see the same behavior in a javascript console.

于 2012-09-24T02:46:36.133 に答える