我在班上有一个任务,用Java和Python实现一些东西。我需要用两种语言实现IntegerStack。所有的值都应该保存在一个数组中,还有一些元数据值,比如head()index。你知道吗
当我实现this is Java时,我只创建一个最大大小的数组(我选择):
public class IntegerStack {
public static int MAX_NUMBER = 50;
private int[] _stack;
private int _head;
public IntegerStack() {
_stack = new int[MAX_NUMBER];
_head = -1;
}
public boolean emptyStack() {
return _head < 0;
}
public int head() {
if (_head < 0)
throw new StackOverflowError("The stack is empty."); // underflow
return _stack[_head];
}
// [...]
}
我真的不知道如何在Python中做到这一点。我查看了一些教程,它们都说python中的数组具有my_array = [1,2,3]
语法。但它是不同的,因为我可以使用它作为一个列表,并附加我想要的项目。所以我可以创建一个for循环,并将50个零元素初始化到一个Python数组中,但它会和Java中的一样吗?我不清楚Python列表与数组有何不同。你知道吗
首先,在Python中需要区分数组和列表。 这里所说的是
list
类,但也有actual arrays,它们与Java中的数组大致相同。你知道吗Python的{{CD1>}类似于java的^ {< CD3>},和C++的^ {CD4>}类似。你知道吗
换句话说,这里有三种可能的解决方案:
list
,只需向其添加元素。你知道吗array
最接近Java的数组。你知道吗关于
list
的使用,如果您的目标是用N个空元素初始化它,那么您可以做的是:或者更别致的方法
如果您想实现接近java版本的东西,可以通过导入numpy来使用numpy数组。Numpy数组是类似的,因为它们和java一样是不可变的对象。然后可以在构造函数中编写:
否则,您可以使用python本身的可变列表对象,在本例中,列表实际上已经是一个堆栈,正如您在data structures的python文档中看到的那样:
但是,第一个版本的性能更高,因为每次更改可变的python对象时都必须复制它们,而不可变的对象只是创建的,没有名称引用它的旧对象被垃圾收集。你知道吗
在python中,如果您声明如下数组:
您正在声明一个head为-1的空数组,可以使用.append()函数将值附加到该数组中,并以与java中相同的方式访问它们。无论出于何种目的,它们都是同一件事
相关问题 更多 >
编程相关推荐