如何为未排序的列表编写pop(item)方法



我正在为考试做准备,实现一些基本的数据结构,遇到了以下问题。我想实现一个未排序的链表,并且已经实现了一个pop()方法,但无论是在语法上还是在概念上,我都不知道如何使函数有时接受参数,有时不接受参数。我希望这是有道理的。

def pop(self):
current = self.head
found = False
endOfList = None
while current != None and not found:
if current.getNext() == None:
found = True
endOfList = current.getData()
self.remove(endOfList)
self.count = self.count - 1
else:
current = current.getNext()
return endOfList

我想知道如何使语句unsortedList.pop(3)有效,3只是一个示例,unsortedList是该类的一个新实例。

使用具有默认值的参数的基本语法(以及常见用例)如下所示:

def pop(self, index=None):
if index is not None:
#Do whatever your default behaviour should be

然后,你只需要根据论点确定你希望自己的行为如何改变。我只是猜测这个参数应该指定应该从列表中弹出的元素的索引。

如果是这种情况,您可以直接使用有效的默认值,而不是None,例如0

def pop(self, index=0):

首先,在函数中添加一个具有默认值的参数:

def pop(self, item=None):

现在,在代码if item is None:中,您可以执行"无参数"操作;否则,使用item。你是想在逻辑上向上切换,还是向下切换,取决于你的逻辑。在这种情况下,item is None可能意味着"匹配第一项",因此您可能需要一个检查item is None or current.data == item:的循环。

有时,您需要为一个可以合法为None的参数执行此操作,在这种情况下,您需要选择一个不同的sentinel。这里(以及其他地方的博客文章)有一些关于不同选择的利弊的问题。但有一种方法:

class LinkedList(object):
_sentinel = object()
def pop(self, item=_sentinel):

除非有人将LinkedList的私有_sentinel类成员用作列表项是有效的,否则这是有效的。(如果有效的——例如,因为你正在用这些东西构建调试器——你就必须变得更加棘手。)

这方面的术语有点棘手。引用文档:

当一个或多个顶级参数的形式为parameter = expression时,该函数被称为具有"默认参数值"。

要理解这一点:"参数"(或"形式参数")是函数被定义为要接受的东西;"arguments"是在调用表达式中传递给函数的内容;"parameter-values"(或"actual parameters",但这只会使事情更加混乱)是函数体接收的值。因此,从技术上讲,提及"默认参数"或"带默认参数的参数"是不正确的,但两者都很常见,因为即使是专家也会觉得这些东西令人困惑。(如果您很好奇,或者还没有感到困惑,请参阅参考文档中的函数定义和调用,以获取完整的详细信息。)

您的考试是专门使用Python的吗?如果没有,您可能需要研究函数重载。Python不支持这一功能,但许多其他语言都支持,并且是解决这类问题的一种非常常见的方法。

在Python中,使用具有默认值的参数可以获得很多好处(正如Michael Mauderer的示例所指出的)。

def pop(self, index=None):
prev = None
current = self.head
if current is None:
raise IndexError("can't pop from empty list")
if index is None:
index = 0 # the first item by default (counting from head)
if index < 0:
index += self.count
if not (0 <= index < self.count):
raise IndexError("index out of range")
i = 0
while i != index:
i += 1
prev = current
current = current.getNext()
assert current is not None # never happens if list is self-consistent
assert i == index
value = current.getData()
self.remove(current, prev)
##self.count -= 1 # this should be in self.remove()
return value

最新更新