Skip to content

Commit 31823c7

Browse files
Merge pull request wangzheng0822#90 from quanxing/master
修改了delete方法和插入方法
2 parents 779814f + 6931086 commit 31823c7

File tree

1 file changed

+30
-7
lines changed

1 file changed

+30
-7
lines changed

python/05_array/myarray.py

Lines changed: 30 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -9,35 +9,53 @@ class MyArray:
99
"""A simple wrapper around List.
1010
You cannot have -1 in the array.
1111
"""
12+
1213
def __init__(self, capacity: int):
14+
1315
self._data = []
1416
self._count = 0
1517
self._capacity = capacity
1618

1719
def __getitem__(self, position: int) -> int:
20+
1821
"""Support for subscript.
1922
Perhaps better than the find() method below.
2023
"""
2124
return self._data[position]
2225

2326
def find(self, index: int) -> Optional[int]:
27+
2428
if index >= self._count or index <= -self._count: return None
2529
return self._data[index]
2630

2731
def delete(self, index: int) -> bool:
32+
2833
if index >= self._count or index <= -self._count: return False
34+
2935
self._data[index:-1] = self._data[index+1:]
3036
self._count -= 1
37+
# 真正将数据删除并覆盖原来的数据 ,这个需要增加
38+
self._data = self._data[0:self._count]
39+
print ('delet function',self._data)
3140
return True
3241

3342
def insert(self, index: int, value: int) -> bool:
34-
if index >= self._count or index <= -self._count: return False
43+
44+
#if index >= self._count or index <= -self._count: return False
3545
if self._capacity == self._count: return False
36-
self._data.insert(index, value)
46+
# 如果还有空间,那么插入位置大于当前的元素个数,可以插入最后的位置
47+
if index >= self._count:
48+
self._data.append(value)
49+
# 同上,如果位置小于0 可以插入第0个位置.
50+
if index < 0:
51+
print (index)
52+
self._data.insert(0, value)
53+
3754
self._count += 1
3855
return True
3956

4057
def insert_to_tail(self, value: int) -> bool:
58+
4159
if self._count == self._capacity: return False
4260
if self._count == len(self._data):
4361
self._data.append(value)
@@ -47,19 +65,24 @@ def insert_to_tail(self, value: int) -> bool:
4765
return True
4866

4967
def __repr__(self) -> str:
68+
5069
return " ".join(str(num) for num in self._data[:self._count])
5170

5271
def print_all(self):
72+
5373
for num in self._data[:self._count]:
54-
print(f"{num}", end=" ")
74+
print("{num}", end=" ")
5575
print("\n", flush=True)
5676

5777
if __name__ == "__main__":
5878
a = MyArray(6)
5979
for i in range(6):
6080
a.insert_to_tail(i)
6181

62-
a.delete(2)
63-
print(a)
64-
a.insert_to_tail(7)
65-
print(a)
82+
print('origin',a)
83+
a.delete(4)
84+
print ('delete ',a)
85+
86+
a.insert(100,10000)
87+
print (a)
88+

0 commit comments

Comments
 (0)