1-6
#! /usr/bin/env python
# _*_coding: utf-8 _*_
class Array(object):
def __init__(self, capacity, logicalSize=0, fillValue=None):
self._data = list()
for i in range(capacity):
self._data.append(fillValue)
self.logicalSize = logicalSize
def __len__(self):
return len(self._data)
def __str__(self):
return str(self._data)
# def __iter__(self):
# return iter(self._data)
def __getitem__(self, index):
if index < 0 or index >= self.size():
raise Exception("index excess")
else:
return self._data[index]
def __setitem__(self, index, value):
if index < 0 or index >= self.__len__():
raise Exception("index excess")
else:
self._data[index] = value
def size(self):
count = 0
for i in range(len(self._data)):
if self._data[i] != None:
count += 1
# print(count)
else:
break
return count
def grow(self):
while self.logicalSize >= len(self._data):
temp = Array(len(self._data) + 1)
for i in range(len(self._data)):
temp[i] = self._data[i]
self.logicalSize -= 1
self._data = temp
return self._data
def shrink(self):
"""
当数组的逻辑大小小于数组的物理大小的四分之一时,执行该方法,将数组的物理大小缩减为原来的1/2
:return:缩减后的数组
"""
l = len(self._data)
print(l)
while l // 4 > self.logicalSize:
temp = Array(len(self._data) // 2)
for i in range(self.logicalSize):
temp[i] = self._data[i]
l -= 1
self._data = temp
return self._data
def insert(self, index, newItem):
if len(self._data) == self.size():
self._data = self.grow()
for i in range(self.size(), index, -1):
self._data[i] = self._data[i - 1]
self._data[index] = newItem
return self._data
def pop(self, index):
if index < 0 or index > self.size():
raise Exception("index excess")
else:
for i in range(index, len(self._data) - 1):
self._data[i] = self._data[i + 1]
self.logicalSize -= 1
self._data.remove(len(self._data) - 1) # 还是要用到这个删除最后一个元素
return self._data
def __eq__(self, other):
if self.size() != other.size():
return False
else:
i = 0
while i < len(self._data):
if self._data[i] == other._data[i]:
i += 1
else:
return False
return True
if __name__ == "__main__":
array = Array(3, 3)
if array.logicalSize >= array.__len__():
array = array.grow()
print(array)
array[0] = 1
array[1] = 2
array[2] = 3
print(array.size(), array.__len__()) # 3 4
"""
插入数据
"""
array.insert(0, 0)
print(array) # [0, 1, 2, 3]
"""
删除元素
"""
print(array.pop(1)) # [0, 2, 3]
"""
比较
"""
array_t = Array(3, 3)
array_t[0] = 0
array_t[1] = 2
array_t[2] = 3
print(array == array_t) # True
"""
?如果Array要像列表一样的话,应该将__iter__方法从当前实现中删除,为什么说这是一个好的建议,并且此时应该如何修改__str__方法
如果将__iter__方法注释掉的,执行如下代码,将返回
for j in array:
print(j)
0
2
3
File "F:/Github/py-evm/4.5.2.py", line 130, in <module>
for j in array:
File "F:/Github/py-evm/4.5.2.py", line 23, in __getitem__
raise Exception("index excess")
Exception: index excess
如果不注释__iter__方法的话,则返回
0
2
3
知乎链接给出这样的解释:https://www.zhihu.com/question/44015086,for循环兼容两种机制
当没有__iter__方法但是实现了__getitem__时,for 会根据下标访问数组,并在index越界时停止,这是旧的迭代协议。
如果实现了__iter__方法时就使用__iter__方法。
那么现在来回答这问题,list的定义中实现__iter__方法,
# def __iter__(self, *args, **kwargs): # real signature unknown
# # Implement iter(self).
# pass
__iter__并没有使用iter函数,没有返回iterator,而是直接pass.
当list使用__iter__时,会返回一个下标迭代的iterator对象来代替,所以会出现index excess的异常。
那么该怎么修改__str__方法?
"""
for j in array:
print(j)
7.
#! /usr/bin/env python
# -*- coding: utf-8 -*-
'''
@author: liudaoqiang
@file: studycase
@time: 2018/8/28 7:14
'''
# from arrays import Array
class Array(object):
def __init__(self, capacity, fillValue=None):
self._data = list()
for i in range(capacity):
self._data.append(fillValue)
def __getitem__(self, index):
return self._data[index]
def __str__(self):
return str(self._data)
def __iter__(self):
return iter(self._data)
def __setitem__(self, index, value):
if index < 0 or index >= self.__len__():
raise Exception("index excess")
else:
self._data[index] = value
def __len__(self):
return len(self._data)
class Matrix(object):
def __init__(self, row, column, fillValue=None):
self._data = Array(row)
self.row = row
self.column = column
for i in range(row):
self._data[i] = Array(column, fillValue)
def __add__(self, other):
# temp = Matrix(self.row, self.column)
ta = Array(self.row)
for i in range(self.row):
ta[i] = Array(self.column, 1)
# print(ta)
for i in range(self.row):
for j in range(self.column):
ta[i][j] = self._data[i][j] + other._data[i][j]
return ta
def __str__(self):
result = " "
for row in range(self.row):
for col in range(self.column):
result += str(self._data[row][col]) + " "
result += "\n"
return result
"""
1 1 1 1
1 1 1 1
1 1 1 1
1 1 1 1
1 1 1 1
2 2 2 2
2 2 2 2
2 2 2 2
2 2 2 2
2 2 2 2
[<__main__.Array object at 0x000001B679ACCA20>,
<__main__.Array object at 0x000001B679ACCA58>,
<__main__.Array object at 0x000001B679ACCA90>,
<__main__.Array object at 0x000001B679ACCAC8>,
<__main__.Array object at 0x000001B679ACCB00>]
"""
matrx = Matrix(5, 4, 1)
matrx_t = Matrix(5, 4, 2)
print(matrx)
print(matrx_t)
matrx_tt = matrx + matrx_t
print(matrx_tt)
#! /usr/bin/env python
# -*- coding: utf-8 -*-
'''
@author: liudaoqiang
@file: studycase
@time: 2018/8/28 7:14
'''
# from arrays import Array
class Array(object):
def __init__(self, capacity, fillValue=None):
self._data = list()
for i in range(capacity):
self._data.append(fillValue)
def __getitem__(self, index):
return self._data[index]
def __str__(self):
return str(self._data)
def __iter__(self):
return iter(self._data)
def __setitem__(self, index, value):
if index < 0 or index >= self.__len__():
raise Exception("index excess")
else:
self._data[index] = value
def __len__(self):
return len(self._data)
class Matrix(object):
def __init__(self, row, column, fillValue=None):
self._data = Array(row)
self.row = row
self.column = column
for i in range(row):
self._data[i] = Array(column, fillValue)
def __add__(self, other):
# temp = Matrix(self.row, self.column)
# ta = Array(self.row)
# for i in range(self.row):
# ta._data[i] = Array(self.column, 1)
# # print(ta)
"""
为什么新定义的变量不能打印呢?奇怪啦
:param other:
:return:
"""
for i in range(self.row):
for j in range(self.column):
other._data[i][j] = self._data[i][j] + other._data[i][j]
return other
def __str__(self):
result = " "
for row in range(self.row):
for col in range(self.column):
result += str(self._data[row][col]) + " "
result += "\n"
return result
"""
1 1 1 1
1 1 1 1
1 1 1 1
1 1 1 1
1 1 1 1
2 2 2 2
2 2 2 2
2 2 2 2
2 2 2 2
2 2 2 2
3 3 3 3
3 3 3 3
3 3 3 3
3 3 3 3
3 3 3 3
"""
matrx = Matrix(5, 4, 1)
matrx_t = Matrix(5, 4, 2)
print(matrx)
print(matrx_t)
matrx_tt = matrx + matrx_t
print(matrx_tt)
#! /usr/bin/env python
# -*- coding: utf-8 -*-
'''
@author: liudaoqiang
@file: studycase
@time: 2018/8/28 7:14
'''
# from arrays import Array
class Array(object):
def __init__(self, capacity, fillValue=None):
self._data = list()
for i in range(capacity):
self._data.append(fillValue)
def __getitem__(self, index):
return self._data[index]
def __str__(self):
return str(self._data)
def __iter__(self):
return iter(self._data)
def __setitem__(self, index, value):
if index < 0 or index >= self.__len__():
raise Exception("index excess")
else:
self._data[index] = value
def __len__(self):
return len(self._data)
class Matrix(object):
def __init__(self, row, column, fillValue=None):
self._data = Array(row)
self.row = row
self.column = column
for i in range(row):
self._data[i] = Array(column, fillValue)
def __add__(self, other):
ta = Matrix(self.row, self.column) # 可以直接用Matrix初始化,前面已经定义了__init__构造函数就可以初始化了
for i in range(self.row):
for j in range(self.column):
ta._data[i][j] = self._data[i][j] + other._data[i][j]
return ta
def __str__(self):
result = " "
for row in range(self.row):
for col in range(self.column):
result += str(self._data[row][col]) + " "
result += "\n"
return result
"""
1 1 1 1
1 1 1 1
1 1 1 1
1 1 1 1
1 1 1 1
2 2 2 2
2 2 2 2
2 2 2 2
2 2 2 2
2 2 2 2
3 3 3 3
3 3 3 3
3 3 3 3
3 3 3 3
3 3 3 3
"""
matrx = Matrix(5, 4, 1)
matrx_t = Matrix(5, 4, 2)
print(matrx)
print(matrx_t)
matrx_tt = matrx + matrx_t
print(matrx_tt)
8-11
#! /usr/bin/env python
# _*_ coding: utf-8 _*_
class Node(object):
"""Represnet a single linked node"""
def __init__(self, data, next=None):
"""Instantiates a Node with a default next of Node"""
self.data = data
self.next = next
class TwoWayNode(Node):
def __init__(self, data, prev=None, next=None):
Node.__init__(self, data, next)
self.prev = prev
def length(node):
"""
:param node: 单链表
:return: 单链表长度
"""
lnth = 0
probe = node
while probe.next != None:
probe = probe.next
lnth += 1
return lnth
def insert(index, data, node):
if index <= 0 or node is None:
return Node(data, None)
else:
probe = node
while index > 1 and probe.next != None:
probe = probe.next
index -= 1
probe.next = Node(data, probe.next)
return probe
def pop(index, node):
if index <= 0 or node.next is None:
node = node.next
return node
else:
probe = node
# print(probe.data)
while index > 1 and probe.next.next != None:
probe = probe.next
index -= 1
probe.next = probe.next.next
return probe
def makeTwoWay(node):
probe = node
if probe.next == None:
return TwoWayNode(probe)
else:
lnth = length(node)
probe = node
print(probe.data)
index = lnth
twoway = TwoWayNode(probe.data)
tail = twoway
while index > 0:
probe = probe.next
tail.next = TwoWayNode(probe.data, tail)
tail = tail.next
index -= 1
return twoway
# 双链表结构可以顺序打印节点,也可以反序打印节点。
# 除了尾部的插入和删除,双链表结构上的操作时间复杂度和单链表一样;但是,双链表结构中的额外指针,需要一个额外的
# 空间复杂度线性的存储。在32位系统中,一个指针是4字节,64位是8字节,对于追求时间复杂度优先级低于空间复杂度的应用,
# 单链表是更好的选择
"""
创建单链表
"""
head = Node(None, None)
for i in range(2, 6):
head = Node(i, head)
"""
打印链表以及长度
5
4
3
2
4
"""
probe = head
while probe.next != None:
print(probe.data)
probe = probe.next
print(length(head))
"""
5
4
33
3
2
"""
insert(2, 33, head)
probe = head
while probe.next != None:
print(probe.data)
probe = probe.next
"""
链表为None时,链表上只有一个节点33
"""
headt = insert(2, 33, None)
print(headt.data)
"""
删除第4项3,主要链表的插入顺序是2,3,4,5,但是访问顺序是5,4,3,2,正如打印时一样,因此index = 3指的是5,4,33,3,2
中的第4项3
5
4
33
2
"""
pop(3, head)
probe = head
while probe.next != None:
print(probe.data)
probe = probe.next
"""
单链表生成双链表函数
5
4
33
2
"""
print("========")
twoway = makeTwoWay(head)
probe = twoway
while probe.next != None:
print(probe.data)
probe = probe.next