Reputation: 960
I don't know how to keep this simple... I'd like someone too look at my code and tell me why a function of mine is not working like it should...
I have a class:
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__()
And I have this function which will take a text file, and run it through some methods in my class:
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":
What is not working for me is my calls to queue.minimum
and queue.removeMin()
.
I'm completely baffled because if I do it manually in the shell, it all works, when I am reading the file and taking the instructions from the letters in my file, it also works, but minimum
and removeMin()
will not display the values in the shell, removeMin()
however WILL remove the lowest number from the list.
What am I doing wrong that it's not displaying what it is doing, like the class methods define?
IE:
def minimum(self):
return min(self.q)
Shouldn't it display the minimum when I call it from my function?
Upvotes: 0
Views: 116
Reputation: 15680
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.
Upvotes: 1
Reputation: 11044
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
).
Upvotes: 6