1 '''
2 定义一个顺序表
3 max:顺序表的默认长度为10
4 num:顺序表中的元素个数
5 '''
6 # 定义一个顺序表
7 class sequence:
8 def __init__(self, max=10):
9 self.max = max
10 self.data = [None] * self.max
11 self.num = 0
12
13 # 统计顺序表元素数量
14 def count(self):
15 return self.num
16
17 # 判断顺序表是否为空
18 def isEmpty(self):
19 return self.num == 0
20
21 # 判断顺序表空间是否存满
22 def isFull(self):
23 return self.num == self.max
24
25 '''
26 从顺序表添加元素
27 '''
28
29 # 头插法
30 def add(self, value):
31 for j in range(self.num, 0, -1):
32 self.data[j] = self.data[j - 1]
33 self.data[0] = value
34 self.num += 1
35
36 # 尾插法
37 def append(self, value):
38 self.data[self.num] = value
39 self.num += 1
40
41 # 从指定位置插入元素
42 def insert(self, index, value):
43 if index < 1:
44 self.add(value)
45 if index > self.num + 1:
46 self.append(value)
47 for j in range(self.num, index - 1, -1):
48 self.data[j] = self.data[j - 1]
49 self.data[index - 1] = value
50 self.num += 1
51
52 # 判断某元素是否存在于顺序表中
53 def isExist(self, value):
54 for j in range(self.num):
55 if self.data[j] == value:
56 return True
57 else:
58 return False
59
60 # 查询某元素的位置
61 def __index__(self, value):
62 if self.isExist(value):
63 for j in range(self.num):
64 if self.data[j] == value:
65 return j
66 else:
67 return -1
68 else:
69 return "该元素不存在"
70
71 # 根据索引查询对应的元素
72 def __getitem__(self, index):
73 if not isinstance(index, int):
74 raise TypeError
75 if 0 <= index < self.num:
76 return self.data[index - 1]
77 else:
78 raise IndexError
79
80 # 根据索引修改顺序表的元素
81 def __setitem__(self, index, value):
82 if not isinstance(index, int):
83 raise TypeError
84 if 0 <= index < self.num:
85 self.data[index - 1] = value
86 else:
87 raise IndexError
88
89 # 从顺序表中删除元素
90 # 根据索引删除元素
91 def __delete__(self, index):
92 if not isinstance(index, int):
93 raise TypeError
94 if index < 0 or index > self.num:
95 raise IndexError
96 for j in range(index - 1, self.num):
97 if j == self.num - 1:
98 self.data[j] = None
99 else:
100 self.data[j] = self.data[j + 1]
101 self.num -= 1
102
103 # 直接删除元素
104 def __delitem__(self, value):
105 for i in range(self.num):
106 if self.data[i] == value:
107 self.__delete__(i+1)
108 return
109 # 遍历顺序表
110 def show(self):
111 print('<', end=' ')
112 for i in range(0, self.num):
113 # if i !=self.num-1:
114 print(self.data[i], end=' ')
115 print('>')
116
117
118 if __name__ == '__main__':
119 s = sequence()
120 s.add(13)
121 s.add(43)
122 s.add(90)
123 s.show()
124 s.append(21)
125 s.append(22)
126 s.append(43)
127 s.show()
128 s.insert(2, 67)
129 print('目前顺序表中元素个数:%d' % s.count())
130 s.show()
131 print('判断元素90是否在顺序表中:', s.isExist(90))
132 print('查看顺序表中第三个元素是%d' % s.__getitem__(3))
133 print('修改顺序表中第四个元素的值')
134 s.__setitem__(4, 78)
135 s.show()
136 print('删除第一个元素')
137 s.__delete__(1)
138 s.show()
139 print('删除元素21')
140 s.__delitem__(21)
141 s.show()