最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Python實(shí)現(xiàn)棧的方法詳解【基于數(shù)組和單鏈表兩種方法】

 更新時(shí)間:2020年02月22日 11:11:47   作者:guyt_  
這篇文章主要介紹了Python實(shí)現(xiàn)棧的方法,結(jié)合實(shí)例形式詳細(xì)分析了Python基于數(shù)組和單鏈表兩種方法定義棧的相關(guān)操作技巧,需要的朋友可以參考下

本文實(shí)例講述了Python實(shí)現(xiàn)棧的方法。分享給大家供大家參考,具體如下:

前言

使用Python 實(shí)現(xiàn)棧。
兩種實(shí)現(xiàn)方式:

  • 基于數(shù)組 - 數(shù)組同時(shí)基于鏈表實(shí)現(xiàn)
  • 基于單鏈表 - 單鏈表的節(jié)點(diǎn)時(shí)一個(gè)實(shí)例化的node 對(duì)象

完整代碼可見GitHub:
https://github.com/GYT0313/Python-DataStructure/tree/master/5-stack

目錄結(jié)構(gòu):
在這里插入圖片描述
注:一個(gè)完整的代碼并不是使用一個(gè)py文件,而使用了多個(gè)文件通過繼承方式實(shí)現(xiàn)。

1. 超類接口代碼

arraycollection.py

"""
File: abstractcollection.py
Author: Ken Lambert
"""

class AbstractCollection(object):
  """An abstract collection implementation."""

  # Constructor
  def __init__(self, sourceCollection = None):
    """Sets the initial state of self, which includes the
    contents of sourceCollection, if it's present."""
    self._size = 0
    if sourceCollection:
      for item in sourceCollection:
        self.add(item)

  # Accessor methods
  def isEmpty(self):
    """Returns True if len(self) == 0, or False otherwise."""
    return len(self) == 0
  
  def __len__(self):
    """Returns the number of items in self."""
    return self._size

  def __str__(self):
    """Returns the string representation of self."""
    return "[" + ", ".join(map(str, self)) + "]"

  def __add__(self, other):
    """Returns a new bag containing the contents
    of self and other."""
    result = type(self)(self)
    for item in other:
      result.add(item)
    return result

  def __eq__(self, other):
    """Returns True if self equals other,
    or False otherwise."""
    if self is other: return True
    if type(self) != type(other) or \
      len(self) != len(other):
      return False
    otherIter = iter(other)
    for item in self:
      if item != next(otherIter):
        return False
    return True

abstractstack.py

"""
File: abstractstack.py
Author: Ken Lambert
"""

from abstractcollection import AbstractCollection

class AbstractStack(AbstractCollection):
  """An abstract stack implementation."""

  # Constructor
  def __init__(self, sourceCollection = None):
    """Sets the initial state of self, which includes the
    contents of sourceCollection, if it's present."""
    AbstractCollection.__init__(self, sourceCollection)

  # Mutator methods
  def add(self, item):
    """Adds item to self."""
    self.push(item)

2. 基于數(shù)組

運(yùn)行示例:
在這里插入圖片描述
代碼:
棧實(shí)現(xiàn):arraystack.py

"""
File: abstractstack.py
Author: Ken Lambert
"""

from abstractcollection import AbstractCollection

class AbstractStack(AbstractCollection):
  """An abstract stack implementation."""

  # Constructor
  def __init__(self, sourceCollection = None):
    """Sets the initial state of self, which includes the
    contents of sourceCollection, if it's present."""
    AbstractCollection.__init__(self, sourceCollection)

  # Mutator methods
  def add(self, item):
    """Adds item to self."""
    self.push(item)

數(shù)組實(shí)現(xiàn):arrays.py

"""
File: arrays.py

An Array is a restricted list whose clients can use
only [], len, iter, and str.

To instantiate, use

<variable> = array(<capacity>, <optional fill value>)

The fill value is None by default.
"""

class Array(object):
  """Represents an array."""

  def __init__(self, capacity, fillValue = None):
    """Capacity is the static size of the array.
    fillValue is placed at each position."""
    self._items = list()
    for count in range(capacity):
      self._items.append(fillValue)

  def __len__(self):
    """-> The capacity of the array."""
    return len(self._items)

  def __str__(self):
    """-> The string representation of the array."""
    return str(self._items)

  def __iter__(self):
    """Supports iteration over a view of an array."""
    return iter(self._items)

  def __getitem__(self, index):
    """Subscript operator for access at index."""
    return self._items[index]

  def __setitem__(self, index, newItem):
    """Subscript operator for replacement at index."""
    self._items[index] = newItem

3. 基于鏈表

運(yùn)行示例:
在這里插入圖片描述
代碼:
linkedstack.py

"""
linkedstack.py
"""

from node import Node
from abstractstack import AbstractStack

class LinkedStack(AbstractStack):
  """基于單鏈表實(shí)現(xiàn)棧-鏈表頭部為棧頂"""

  def __init__(self, source_collection=None):
    self._items = None
    AbstractStack.__init__(self, source_collection)

  def __iter__(self):
    """迭代-使用一個(gè)列表實(shí)現(xiàn), 列表第一項(xiàng)為單鏈表的最后一項(xiàng)"""
    def visit_nodes(node):
      if node != None:
        visit_nodes(node.next)
        temp_list.append(node.data)
    temp_list = []
    visit_nodes(self._items)
    return iter(temp_list)

  def peek(self):
    """返回棧頂元素"""
    self._prior_condition()
    return self._items.data

  def clear(self):
    """清空列表"""
    self._size = 0
    self._items = None

  def push(self, item):
    """入棧"""
    self._items = Node(item, self._items)
    self._size += 1

  def pop(self):
    """出棧"""
    self._prior_condition()
    old_item = self._items.data
    self._items = self._items.next
    self._size -= 1
    return old_item

  def _prior_condition(self):
    if self._size == 0:
      raise KeyError("The stack is empty.")

node.py

"""
鏈表結(jié)構(gòu)的節(jié)點(diǎn)類
"""

class Node(object):
  def __init__(self, data, next=None):
    self.data = data
    self.next = next

參考:《數(shù)據(jù)結(jié)構(gòu)(Python語言描述)》

更多關(guān)于Python相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python加密解密算法與技巧總結(jié)》、《Python編碼操作技巧總結(jié)》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》及《Python入門與進(jìn)階經(jīng)典教程

希望本文所述對(duì)大家Python程序設(shè)計(jì)有所幫助。

相關(guān)文章

  • python3 pathlib庫Path類方法總結(jié)

    python3 pathlib庫Path類方法總結(jié)

    這篇文章主要介紹了python3 pathlib庫Path類方法總結(jié),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2019-12-12
  • Python pip install之SSL異常處理操作

    Python pip install之SSL異常處理操作

    這篇文章主要介紹了Python pip install之SSL異常處理操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2020-09-09
  • Python爬蟲之UserAgent的使用實(shí)例

    Python爬蟲之UserAgent的使用實(shí)例

    今天小編就為大家分享一篇關(guān)于Python爬蟲之UserAgent的使用實(shí)例,小編覺得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來看看吧
    2019-02-02
  • Python基礎(chǔ)之函數(shù)用法實(shí)例詳解

    Python基礎(chǔ)之函數(shù)用法實(shí)例詳解

    這篇文章主要介紹了Python中函數(shù)用法,包括了函數(shù)的創(chuàng)建、定義、參數(shù)等,需要的朋友可以參考下
    2014-09-09
  • Python實(shí)現(xiàn)SSH隧道功能的示例代碼

    Python實(shí)現(xiàn)SSH隧道功能的示例代碼

    SSH隧道是利用SSH協(xié)議建立一個(gè)加密通道,以保護(hù)通過不安全網(wǎng)絡(luò)傳輸?shù)臄?shù)據(jù),本文將介紹如何使用Python來實(shí)現(xiàn)SSH隧道功能,感興趣的可以了解下
    2025-02-02
  • 怎樣用cmd命令行運(yùn)行Python文件

    怎樣用cmd命令行運(yùn)行Python文件

    這篇文章主要介紹了怎樣用cmd命令行運(yùn)行Python文件問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-06-06
  • python 與GO中操作slice,list的方式實(shí)例代碼

    python 與GO中操作slice,list的方式實(shí)例代碼

    這篇文章主要介紹了python 與GO中操作slice,list的方式實(shí)例代碼的相關(guān)資料,需要的朋友可以參考下
    2017-03-03
  • 詳解Python中行列式的計(jì)算

    詳解Python中行列式的計(jì)算

    矩陣的行列式是僅與方陣相關(guān)的標(biāo)量,?這篇文章主要為大家詳細(xì)介紹了如何利用Python實(shí)現(xiàn)行列式的計(jì)算,感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下
    2023-11-11
  • windows上徹底刪除jupyter notebook的實(shí)現(xiàn)

    windows上徹底刪除jupyter notebook的實(shí)現(xiàn)

    這篇文章主要介紹了windows上徹底刪除jupyter notebook的實(shí)現(xiàn),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2020-04-04
  • 詳解Python如何制作自動(dòng)發(fā)送微信的程序

    詳解Python如何制作自動(dòng)發(fā)送微信的程序

    這篇文章主要介紹了如何利用Python中的apscheduler和pyautogui模塊,制作一個(gè)自動(dòng)發(fā)送微信的程序。感興趣的小伙伴可以跟隨小編一起動(dòng)手試一試
    2022-01-01

最新評(píng)論

娱乐| 永泰县| 新源县| 轮台县| 郯城县| 柏乡县| 广南县| 白朗县| 普安县| 沧源| 东台市| 施秉县| 互助| 吴江市| 双江| 双柏县| 江门市| 五河县| 叙永县| 嘉定区| 乌兰浩特市| 彭水| 乐山市| 阳信县| 沧源| 凤凰县| 安泽县| 德保县| 鸡泽县| 甘谷县| 海口市| 西乌| 永靖县| 盐津县| 浮山县| 九江市| 祁连县| 昌黎县| 绥江县| 富平县| 东乌|