简单堆栈长度

问题描述 投票:-1回答:2

我已经尝试阅读此内容,并且可以使len()函数与除堆栈之外的所有内容一起使用。我尝试了多种不同的想法,并感到它很简单。有谁看到我遇到的问题。我没有任何线索。我会很感谢您的帮助。

class HardwareID():
    #empty list created
    def __init__(self):
        self.items = []
    #push for python
    def push(self, item):
        self.items.append(item)

    def pop(self):
        return self.items.pop()

    def is_empty(self):
        return self.items == []
    #implimented for learning
    def peek(self):
        if not self.is_empty():
            return self.items[-1]

    def get_stack(self):
        return self.items

s = HardwareID()

print ("The stack the right is the top")
s.push("LCD")
s.push("LED")
s.push("Mobile")
s.push("Charger")
s.push("Speaker")
s.push("Mouse")
s.push("Keyboard")
s.push("Laptop")
print (s.get_stack())
print (len(s))
s.pop()
s.pop()
s.pop()
print (s.get_stack())
python python-3.x
2个回答
0
投票

解决您的问题的简单方法是将以下方法添加到您的类中。

def __len__(self):
    return len(self.items)

0
投票

您可以为您的__len__类实现__len__方法:

HardwareID

实施此方法将实现所需的行为:

def __len__(self):
    return len(self.get_stack())
© www.soinside.com 2019 - 2024. All rights reserved.