#!/usr/bin/env python3 from random import random, randint from math import sqrt from numbers import Number class Vector(list): # <<<1 """ Vector with operations Vector + Vector Vector - Vector scalar * Vector Vector * scalar Vector / scalar abs(Vector) for the norm of given vector """ def __init__(self, iterator=()): """ Vector() -> new, empty vector Vector(iterable) -> new vector, initialized from iterator """ list.__init__(self, iterator) def __mul__(self, alpha): if not isinstance(alpha, Number): raise TypeError("cannot multiply vector by non numeric type") return Vector(a*alpha for a in self) def __rmul__(self, alpha): if not isinstance(alpha, Number): raise TypeError("cannot multiply vector by non numeric type") return Vector(alpha*a for a in self) def __imul__(self, alpha): for i in range(len(self)): self[i] *= alpha return self def __neg__(self): return Vector(-a for a in self) def __truediv__(self, alpha): return Vector(a/alpha for a in self) def __itruediv__(self, alpha): for i in range(len(self)): self[i] /= alpha return self def __floordiv__(self, alpha): return Vector(a//alpha for a in self) def __ifloordiv__(self, alpha): for i in range(len(self)): self[i] //= alpha return self def __add__(self, other): return Vector(a+b for a, b in zip(self, other)) def __iadd__(self, other): for i in range(len(self)): self[i] += other[i] return self def __sub__(self, other): return Vector(a-b for a, b in zip(self, other)) def __isub__(self, other): for i in range(len(self)): self[i] -= other[i] return self def __abs__(self): return sqrt(sum(a*a for a in self)) def __repr__(self): return "Vector([{}])".format(", ".join(map(str, self))) def __str__(self): return "({})".format(", ".join(map(str, self))) @classmethod def zero(cls, n): return cls([0]*n) # >>>1 def randomVector(n, style="uniform"): """ Retourne un Vector de longeur n contenant des valeurs aléatoires. """ if style == 'uniform': v = Vector(randint(0, 10*n) for i in range(n)) elif style == 'steps': v = Vector([randint(0, 10*n)]) for i in range(1, n): if random() < 10/n: v.append(randint(0, 10*n)) else: v.append(v[-1]) elif style == 'mountains': v = Vector([randint(-n, n)]) step = randint(-n//2, n//2) for i in range(1, n): if random() < 10/n: step = randint(-n//2, n//2) v.append(v[-1]+step) else: raise ValueError("Invalid tyle '{}'".format(style)) return v