【问题标题】:Writing a push method for an Array based implementation of ADT Stack为基于数组的 ADT Stack 实现编写推送方法
【发布时间】:2021-09-25 09:27:54
【问题描述】:

我必须为基于数组的堆栈编写一个推送方法,该堆栈被实现为 ArrayStack 类。

import ctypes
from typing import Any

def _new_array(capacity: int) -> 'py_object_Array_<capacity>':
"""Return a new array with the specified capacity that stores
references to Python objects.
"""
if capacity < 1:
    raise ValueError('_new_array: capacity must be >= 1')
PyCArrayType = ctypes.py_object * capacity
a = PyCArrayType()
for i in range(len(a)):
    a[i] = None
return a

创建 ArrayStack 的实例使用上面的 _new_array() 方法

class ArrayStack:

def __init__(self, iterable=[]) -> None:
    
    self._n = 0  # number of elements stored in the stack
    self._items = _new_array(1)  # backing array

    for elem in iterable:
        self.push(elem)

使用 append 方法如下:self._items.append(x),给了我一个错误'py_object_Array_1' object has no attribute 'append',所以我使用了self._items[0],但它不会将元素推送到堆栈

 def push(self, x: Any) -> None:
    
    self._items[0] = x

你能告诉我我做错了什么吗?谢谢

【问题讨论】:

    标签: python python-3.x stack


    【解决方案1】:

    每次执行 self._items[0] = XYZ 时,都会覆盖存储在该索引中的项目 0。 我建议你做的是继续跟踪到目前为止你插入了多少元素。就做self._items[inserted] = x

    import ctypes
    from typing import Any
    
    def _new_array(capacity: int) -> 'py_object_Array_<capacity>':
        """Return a new array with the specified capacity that stores
        references to Python objects.
        """
        if capacity < 1:
            raise ValueError('_new_array: capacity must be >= 1')
        PyCArrayType = ctypes.py_object * capacity
        a = PyCArrayType()
        for i in range(len(a)):
            a[i] = None
        return a
    
    
    class ArrayStack:
        def __init__(self, iterable=[]) -> None:
            self._items = _new_array(10)  # backing array
            self.capacity = len(self._items)
            self.inserted = 0
    
            for elem in iterable:
                self.push(elem)
    
        def push(self, x: Any) -> None:
            assert self.inserted < self.capacity, "Your array it larger than the capacity"
            self._items[self.inserted] = x
            self.inserted += 1
    

    然后stack = ArrayStack([1,2,3,4,5,6,7,8,9,10]) 就可以了,因为我们设置了一个包含 10 个元素的堆栈,但 stack = ArrayStack([1,2,3,4,5,6,7,8,9,10,11]) 不起作用,因为您不能将 11 个元素插入到 10 元素数组中。

    还有这个部分:

        for i in range(len(a)):
            a[i] = None
    

    是多余的

    【讨论】:

    • 非常感谢您的回复。很抱歉我之前没有提到它,但是除了只编辑 push 方法之外,是否可以在不编辑任何内容的情况下实现这一点?
    • 是的,我们可以使用您定义的变量self._n,但每次都查找len(self._items) 效率低。
    猜你喜欢
    • 2015-12-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-14
    • 2023-03-20
    • 2018-12-29
    • 2013-02-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多