#coding:utf-8
'''
author: Li huanhai
'''
#About Sequential List
class SeqList(object):
def __init__(self, size=10):
self.max = size
#init the Sequential list
self.num = 0
self.data = [None] * self.max
#judge the Slist is or not is empty
def is_empty(self):
return self.num is 0
#judge the Slist is or not is full
def is_full(self):
return self.num is self.max
#表末尾添加元素
def append_end(self, value):
if self.num >= self.max:
print("The list is full!")
else:
self.data[self.num] = value
self.num += 1
#获取任意位置元素值
#list下标从0开始,位置从1开始算起
def get(self, index):
if not isinstance(index, int):
raise TypeError #类型错误
elif 0 < index <= self.max:
return self.data[index - 1]
else:
raise IndexError #索引错误
#改变给定位置的元素值
def set(self, index, value):
if not isinstance(index, int):
raise TypeError
elif 0 < index <= self.max:
self.data[index - 1] = value
else:
raise IndexError
#返回表长
def count(self):
return self.num
#在表中任意位置插入一个元素
def insert(self, index, value):
if not isinstance(index, int):
raise TypeError
elif self.num >= self.max:
print("The list is full!")
elif index < 1 or index > self.num:
raise IndexError
else:
for i in range(self.num, index - 1, -1):
self.data[i] = self.data[i - 1]
self.data[index - 1] = value
self.num += 1
#根据值返回第一个与该值相等的元素的下标
def locate(self, value):
for i in range(self.num):
if self.data[i] == value:
return i
return -1
#删除任意位置的元素
def remove(self, index):
if not isinstance(index, int):
raise TypeError
elif index < 1 or index > self.num:
raise IndexError
else:
for i in range(index, self.num):
self.data[i - 1] = self.data[i]
self.num -= 1
#删除线性表末尾的值
def remove_end(self):
if self.num == 0:
print("The list is empty!")
else:
self.data[self.num - 1] = None
self.num -= 1
#打印线性表:
def print_list(self):
if self.num == 0:
print("The list is empty!")
else:
for i in range(self.num):
print(self.data[i], end=' ')
if i == self.num - 1:
print("\n")
#删除整个列表
def destroy(self):
self.__init__()
if __name__ == '__main__':
seqlist = SeqList()
print(seqlist.is_empty())
print(seqlist.is_full())
for i in range(4):
seqlist.append_end(1)
seqlist.print_list()
seqlist.insert(4, 3)
seqlist.print_list()
print(seqlist.locate(1))
print(seqlist.count())
print(seqlist.get(4))
seqlist.set(4, 10)
print(seqlist.get(4))
seqlist.print_list()
seqlist.remove(4)
seqlist.print_list()
seqlist.remove_end()
seqlist.print_list()
seqlist.destroy()
seqlist.print_list()
在VScode里面编辑显示结果,如图: