Python自定义函数练习(持续更新中~)

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()





结果:

Python自定义函数练习(持续更新中~)_第1张图片

你可能感兴趣的:(编程训练,python,开发语言)