使用python从头开始实现数组



我的老师要求我使用python实现一个数组,而不使用任何内置函数,但我很困惑,我不知道如何?这是一个完整的问题……

Write a program in Python to implement the “Array” data structure. Perform operations like add or insert, delete or remove and display. Your program should be able to add/insert at any position in an array or remove/delete any element from an array. Take care of extreme conditions such as an empty array or full array and display an appropriate message to the user.

任何帮助都将是非常感激的。

可以将数组存储在列表L中,并为每个列表操作编写一个函数。例如,要在列表L中搜索元素x并返回x在L中第一次出现的索引,而不是使用内置函数索引,您将实现线性搜索算法。因此,下面的代码是不正确的,因为它使用了内置函数index:

def search(L,x):
return L.index(x)

下面的代码是可以接受的,因为你自己正在实现线性搜索算法(可能你的老师希望你从头开始编写程序,这是一个很好的实践):

def search(L,x):
#input: a list L and an element x
#output: the index of first occurrence of x in L, or -1 if x not in L
n = len(L)
for i in range(n):
if L[i] == x:
return i
return -1    
L=[3,1,4,2]
print(search(L,7))

最新更新