我目前正在学习一些关于算法和数据结构的类(class),并使用 Python 来实现我一直在学习的一些内容。
目前我正在实现一个基于固定大小数组的堆栈。考虑到 python 的特殊性,我选择使用 numpy.empty()。
对于我编写的测试,我基本上将 9 个元素插入堆栈。到目前为止,一切正常,因为生成的数组有 9 个元素以及另外 7 个元素的空间。
我开始弹出元素,当我达到数组中只有 4 个元素的临界点时,我希望数组将元素复制到大小为 8 的新数组中。
问题是,当我创建这个新数组时,它不是用空值创建的,而是已经填充了。
Here an image of my terminal at that specific step when debugging with PDB
我错过了什么吗?
编辑:似乎如果我使用 Python 3 一切都会按预期工作,Python 2 就是这种情况
class StackV2(object):
"""
This is the Stack version based on fixed size arrays
"""
def __init__(self):
self.array = numpy.empty(1, dtype=str)
self.size = 0
def push(self, value):
self.array[self.size] = value
self.size += 1
if len(self.array) == self.size:
self._resize_array(len(self.array) * 2)
def pop(self):
self.array[self.size - 1] = ""
self.size -= 1
if len(self.array) == (4 * self.size):
self._resize_array(len(self.array) / 2)
def _resize_array(self, factor):
new_array = numpy.empty(factor, dtype=str)
print(new_array)
index = 0
for i in range(0, self.size):
new_array[index] = self.array[i]
index += 1
self.array = new_array
最佳答案
简短回答
使用 numpy.zeros
而不是 numpy.empty
来消除新数组中的意外垃圾值。
详细信息
由 numpy.zeros
创建的数组的所有元素都初始化为“零值”。对于 dtype=str
的数组,这将是空字符串 ''
。
来自 Numpy docs :
Notes
empty, unlike zeros, does not set the array values to zero, and may therefore be marginally faster. On the other hand, it requires the user to manually set all the values in the array, and should be used with caution.
它在 Python 3(但不适用于 Python 2)中工作的事实是 undefined behavior 。基本上,这是 Numpy 开发人员没有计划的实现的一个怪癖。最佳实践是不要在代码中依赖此类内容。正如您所看到的,未定义行为的结果不能保证在版本、实现、运行代码的不同计算机等之间保持一致。
此外,听起来您可能对 Numpy 数组的工作原理有点困惑。 numpy 数组在创建时以固定大小开始。这与普通的 Python 列表 []
不同,后者会随着您向其中添加值而动态增长。
此外,您不需要在 _resize_array
中同时使用 index
和 i
。只需使用其中之一,如下所示:
for i in range(self.size):
new_array[i] = self.array[i]
除此之外,你的代码很好。
关于python - Numpy.empty() 创建具有非空值的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49711922/