Python算法《向量,矩阵》

65 篇文章 4 订阅
5 篇文章 1 订阅

 先做记录,后续逐步分析优化

# -*- coding : utf-8 -*-
#Author: Vick.Pan Create at 2019/8/6 10:10
#File  : Vector.py
import math

class Error(Exception):

    def size_Error(self):
        return Exception("Must have the same size")

    def value_Error(self):
        return Exception("invalide operand!")

    def index_Error(self):
        return Exception("Index out of range!")

    def not_vector_Error(self):
        return Exception("Please give any vector!")

class Vector(Error):
    def __init__(self, components=[]):
        self.__components = list(components)

    def set(self, components):
        if len(components) > 0:
            self.__components = list(components)
        else:
            raise self.not_vector_Error()

    def __str__(self):
        return "(" + ",".join(map(str, self.__components)) + ")"

    def component(self, i):
        if type(i) is int and -len(self.__components) <= i < len(self.__components):
            return self.__components[i]
        else:
            raise self.index_Error()

    def eulidlength(self):
        summe = 0
        for c in self.__components:
            summe += c**2
        return math.sqrt(summe)

    def __len__(self):
        return len(self.__components)

    def changeComponent(self, pos, value):
        assert (-len(self.__components <= pos < len(self.__components)))
        self.__components[pos] =value

    def __add__(self, other):
        size = len(self)
        if size == len(other):
            result = [self.__components[i] + other.component(i) for i in range(size)]
            return Vector(result)
        else:
            raise self.size_Error()

    def __sub__(self, other):
        size = len(self)
        if size == len(other):
            result = [self.__components[i] - other.component(i) for i in range(size)]
            return result
        else:
            raise self.size_Error()

    def __mul__(self, other):
        if isinstance(other, float) or isinstance(other, int):
            ans = [c * other for c in self.__components]
            return ans
        elif (isinstance(other, Vector) and (len(self) == len(other))):
            size = len(self)
            summe = 0
            for i in range(size):
                summe += self.__components[i] * other.component(i)
            return summe
        else:
            self.value_Error()

    def zeroVector(dimension):
        assert(isinstance(dimension, int))
        return Vector([0] * dimension)

    def unitBasisVector(self, dimension, pos):
        assert(isinstance(dimension, int)) and (isinstance(pos, int))
        ans = [0] * dimension
        ans[pos] = 1
        return Vector(ans)

a = [1, 2, 3]
b = [4, 5]
va = Vector(a)
vb = Vector(b)

c = va + vb
print(c)

 

# -*- coding : utf-8 -*-
#Author: Vick.Pan Create at 2019/8/6 11:05
#File  : matrix.py

class Matrix():
    def __init__(self,matrix):
        self.__matrix = matrix
        self.__width = len(a[0])
        self.__height = len(a)

    def __str__(self):
        ans = ""
        for i in range(self.__height):
            ans += "|"
            for j in range(self.__width):
                if j < self.__width -1:
                    ans += str(self.__matrix[i][j]) + ","
                else:
                    ans += str(self.__matrix[i][j]) + "|\n"
        return ans

    def changeComponent(self, x, y, value):
        assert x in range(self.__height) and y in range(self.__width), "changeComponent: indices out of bounds"
        self.__matrix[x][y] = value

    def component(self, x, y):
        assert x in range(self.__height) and y in range(self.__width), "changeComponent: indices out of bounds"
        return self.__matrix[x][y]

    def width(self):
        return self.__width

    def height(self):
        return self.__height


a = [[1, 2, 3],
     [4, 5, 6]]
m = Matrix(a)
m.changeComponent(0, 3, 10)

print(m)

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值