1.计算矩阵的面积和周长:
class Rectangle: def __init__(self, width, height): self.width = width self.height = height def area(self): return self.width * self.height def perimeter(self): return 2 * (self.width + self.height) if __name__ == "__main__": rectangle = Rectangle(5, 10) print("矩形面积:", rectangle.area()) print("矩形周长:", rectangle.perimeter())
2.将矩阵转置后,计算该矩阵与另一个矩阵的和并返回一个新的矩阵对象。
class Matrix: def __init__(self,data): self.data=data #矩阵转置 def transpose(self): rows=len(self.data) cols=len(self.data[0]) transpose_data=[[0 for _ in range(rows)]for _ in range(cols)] for i in range(rows): for j in range(cols): transpose_data[j][i]=self.data[i][j] return Matrix(transpose_data) #计算两矩阵之和 def add(self,other_matrix): rows=len(self.data) cols=len(self.data[0]) if rows !=len(other_matrix.data) or cols != len(other_matrix.data[0]): raise ValueError("两个矩阵维度不一致") result_data=[[0 for _ in range(cols)]for _ in range(rows)] for i in range(rows): for j in range(cols): result_data[i][j]=self.data[i][j]+other_matrix.data[i][j] return Matrix(result_data) if __name__ == "__main__": matrix1=Matrix([[1,2,3],[4,5,6]]) matrix2=Matrix([[7,8,9],[10,11,12]]) print("矩形1的转置:") transposed_matrix1=matrix1.transpose() for row in transposed_matrix1.data: print(row) print("矩阵1和矩阵2的和:") sum_matrix=matrix1.add(matrix2) for row in sum_matrix.data: print(row)
3.栈的基本操作
class Stack: def __init__(self): self.items = [] def push(self, item): self.items.append(item) def pop(self): if self.is_empty(): raise ValueError("栈为空") return self.items.pop() def is_empty(self): return len(self.items) == 0 if __name__ == "__main__": stack = Stack() stack.push(1) stack.push(2) stack.push(3) while not stack.is_empty(): print(stack.pop())
4.链表的基本操作
class Node: def __init__(self, value): self.value = value self.next = None class LinkedList: def __init__(self, head=None): self.head = head def insert(self, value): new_node = Node(value) if self.head is None: self.head = new_node else: current = self.head while current.next is not None: current = current.next current.next = new_node def delete(self, value): if self.head is None: return if self.head.value == value: self.head = self.head.next return current = self.head while current.next is not None: if current.next.value == value: current.next = current.next.next return current = current.next def traverse(self): current = self.head while current is not None: print(current.value) current = current.next if __name__ == "__main__": linked_list = LinkedList() linked_list.insert(1) linked_list.insert(2) linked_list.insert(3) linked_list.delete(2) linked_list.traverse()
5.队列的基本操作
class Queue: def __init__(self): self.items = [] def is_empty(self): return len(self.items) == 0 def enqueue(self, item): self.items.append(item) def dequeue(self): if not self.is_empty(): return self.items.pop(0)#对于栈的操作为:self.items.pop() def size(self): return len(self.items) if __name__ == "__main__": q = Queue() print(q.is_empty()) # True q.enqueue(1) q.enqueue(2) q.enqueue(3) print(q.size()) # 3 print(q.dequeue()) # 1 print(q.dequeue()) # 2 print(q.size()) # 1
6.Histogram类封装直方图
(1)定义带一个整数参数n的构造函数,用于初始化存储数据的列表,列表长度为n,列表各元素的初始值为0.
(2)定义实例对象方法addDataPoint(self,i),用于增加一个数据点
(3)定义用于计算数据点个数之和、平均值、最大值、最小值的实例对象方法,即count()、mean()、max()、min()。(4)定义用于绘制简单直方图的实例对象方法draw()
import random class Histogram: def __init__(self,n): self.__numlist=[] for i in range(n): self.__numlist.append(0) #print(self.__numlist) def addDataPoint(self,i): self.__numlist[i]+=1 def count(self,data_account): return data_account def mean(self,data_account,List_account): a=data_account/List_account return (a) def Max(self): return max(self.__numlist) def Min(self): return min(self.__numlist) def draw(self): for i in range(len(self.__numlist)): print("{}:".format(i),end="") for j in range(self.__numlist[i]): print("#".format(i),end="") print("") if __name__=="__main__": List_account=10#规定numlist的大小 histogram=Histogram(List_account) Data_account=100 for i in range(0,Data_account):#生成0~99一百个数字 random_number=random.randint(0,9)#随机生成0~9 histogram.addDataPoint(random_number)#将生成的随机数放到列表中 print("数据点个数的个数:{}".format(Data_account)) print("数据点个数的平均值:{}".format(histogram.mean(Data_account, List_account))) print("数据点个数的最大值{}".format(histogram.Max())) print("数据点个数的最小值{}".format(histogram.Min())) histogram.draw()
结果:
7.Color类封装使用RGB颜色模型表示颜色及相应功能
(1)定义带三个0到255的整数参数r、g、b的构造函数,用于初始化对应于红、绿、蓝三种颜色分量的实例对象属性_r、_g和_b
(2)通过装饰器@property定义三个可以作为属性访问的实例对象方法r()、g()和b()
(3)定义用于计算颜色亮度的方法luminance(self):Y = 0.299 r + 0.587g + 0.114b
(4)定义用于转换为灰度颜色亮度的方法toGray(self):由亮度四舍五入取整得到,(int(round(luminance())),int(round(luminance())),int(round(luminance())))
(5)定义用于比较两种颜色兼容性的方法isCompatible(self, c)。颜色兼容性指在以一种颜色为背景时另一种颜色的可阅读性。一般而言,前景色和背景色的亮度差至少应该是128。例如,白纸黑字的亮度差为255
class Color: """表示RGB模型的类""" def __init__(self, r=0, g=0, b=0): """构造函数""" self._r = r #Red红色分量 self._g = g #Green绿色分量 self._b = b #Blue蓝色分量 @property def r(self): return self._r @property def g(self): return self._g @property def b(self): return self._b def luminance(self): """计算并返回颜色的亮度""" return .299*self._r + .587*self._g + .114*self._b def toGray(self): """转换为灰度颜色""" y = int(round(self.luminance())) return Color(y, y, y) def isCompatible(self, c): """比较前景色和背景色是否匹配""" return abs(self.luminance() - c.luminance()) >= 128.0 def __str__(self): """重载方法,输出:(r, g, b)""" return '({},{},{})'.format(self._r,self._g,self._b) #常用颜色 WHITE = Color(255, 255, 255) BLACK = Color( 0, 0, 0) RED = Color(255, 0, 0) GREEN = Color( 0, 255, 0) BLUE = Color( 0, 0, 255) CYAN = Color( 0, 255, 255) MAGENTA = Color(255, 0, 255) YELLOW = Color(255, 255, 0) #测试代码 if __name__ == '__main__': c = Color(255, 200, 0) #ORANGE(橙色) print('颜色字符串:{}'.format(c)) #输出颜色字符串 print('颜色分量:r={},g={},b={}'.format(c.r, c.g, c.b)) #输出各颜色分量 print('颜色亮度:{}'.format(c.luminance())) #输出颜色亮度 print('转换为灰度颜色:{}'.format(c.toGray())) #输出转换后的灰度颜色 print('{}和{}是否匹配:{}'.format(c,RED,c.isCompatible(RED))) #比较与红色是否匹配
结果: