我不知道如何保持这个简单。。。我也希望有人看看我的代码,告诉我为什么我的一个函数不能正常工作。。。你知道吗
我有一门课:
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()
的调用。你知道吗
我完全感到困惑,因为如果我在shell中手动执行,它都可以工作,当我读取文件并从文件中的字母中获取指令时,它也可以工作,但是minimum
和removeMin()
不会在shell中显示值,removeMin()
但是会从列表中删除最小的数字。你知道吗
我做错了什么,它没有显示它正在做什么,就像类方法定义的那样?你知道吗
即:
def minimum(self):
return min(self.q)
当我从函数中调用它时,它不应该显示最小值吗?你知道吗
不,
def minimum(self): return min(self.q)
在调用时不会显示任何内容。只有在打印输出时它才会显示一些内容,如print(queue.minimum())
。例外情况是从Python prompt/REPL执行代码时,默认情况下打印表达式(除非它们是None
)。你知道吗一切正常。你只是在返回一个值。你知道吗
如果要显示值,则需要执行以下任一操作:
或者
打印未捕获的返回值是大多数解释器的实用功能。您将在javascript控制台中看到相同的行为。你知道吗
相关问题 更多 >
编程相关推荐