猿问

简单的堆栈长度

我已尝试阅读此内容,并且可以使该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())


慕哥6287543
浏览 117回答 2
2回答

万千封印

您可以为您的类实现该__len__方法:HardwareIDdef __len__(self):    return len(self.get_stack())实现此方法将实现所需的行为:s = HardwareID()print(len(s))  # 0s.push("A value")s.push("B value")print(len(s))  # 2s.pop()print(len(s))  # 1

守着星空守着你

解决您的问题的一个简单方法是将以下方法添加到您的课程中。def __len__(self):     return len(self.items)
随时随地看视频慕课网APP

相关分类

Python
我要回答