实现栈与Python [英] Implementing Stack with Python

查看:151
本文介绍了实现栈与Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想实现一个简单的堆栈使用数组的Python。我想知道,如果有人可以让我知道什么地方错了我的code。

 类myStack:
     高清__init __(个体经营):
         自= []

     高清的isEmpty(个体经营):
         返回self == []

     高清推送(个体经营,项目):
         self.append(项目)

     高清流行(个体经营):
         返回self.pop(0)

     高清尺寸(个体经营):
         返回LEN(个体经营)

    S = myStack()
    s.push(1)
    s.push('2')
    打印(s.pop())
    打印■
 

解决方案

我纠正下面的几个问题。此外,堆栈,在抽象的编程术语,通常是在您添加或从顶部删除数据收集,但实现的方式,你要添加到顶部和底部,这使得它成为队列中删除

 类myStack:
     高清__init __(个体经营):
         self.container = []#你不想将[]自我 - 当你这样做,你只是分配到名为`self`一个新的局部变量。您希望您的堆栈*有*一个列表,而不是*是*的列表。

     高清的isEmpty(个体经营):
         返回self.size()== 0#虽然没有什么错self.container == [],有一个内置的功能为目的,所以我们不妨用它。虽然我们在这,它往往是很好的使用自己的内部函数,所以行为更加一致。

     高清推送(个体经营,项目):
         self.container.append(项目)#附加在*容器*,而不是实例本身。

     高清流行(个体经营):
         从容器返回self.container.pop()#流行,这是从旧的版本,这是错误的固定

     高清尺寸(个体经营):
         返回的len(self.container)#长度的容器的

S = myStack()
s.push(1)
s.push('2')
打印(s.pop())
打印■
 

I am trying to implement a simple stack with Python using arrays. I was wondering if someone could let me know what's wrong with my code.

class myStack:
     def __init__(self):
         self = []

     def isEmpty(self):
         return self == []

     def push(self, item):
         self.append(item)

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

     def size(self):
         return len(self)

    s = myStack()
    s.push('1')
    s.push('2')
    print(s.pop())
    print s

解决方案

I corrected a few problems below. Also, a 'stack', in abstract programming terms, is usually a collection where you add and remove from the top, but the way you implemented it, you're adding to the top and removing from the bottom, which makes it a queue.

class myStack:
     def __init__(self):
         self.container = []  # You don't want to assign [] to self - when you do that, you're just assigning to a new local variable called `self`.  You want your stack to *have* a list, not *be* a list.

     def isEmpty(self):
         return self.size() == 0   # While there's nothing wrong with self.container == [], there is a builtin function for that purpose, so we may as well use it.  And while we're at it, it's often nice to use your own internal functions, so behavior is more consistent.

     def push(self, item):
         self.container.append(item)  # appending to the *container*, not the instance itself.

     def pop(self):
         return self.container.pop()  # pop from the container, this was fixed from the old version which was wrong

     def size(self):
         return len(self.container)  # length of the container

s = myStack()
s.push('1')
s.push('2')
print(s.pop())
print s

这篇关于实现栈与Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆