Page 1 of 1

import math class Vec: def __init__(self, contents = []): """ Constructor defaults to empty vector

Posted: Sun May 15, 2022 1:18 pm
by answerhappygod
import math
class Vec:
def __init__(self, contents = []):
"""
Constructor defaults to empty
vector
INPUT: list of elements to initialize a
vector object, defaults to empty list
"""
self.elements = contents
return
def __abs__(self):
"""
Overloads the built-in function
abs(v)
returns the Euclidean norm of vector
v

"""
self.product=0
for i in
range(len(self.elements)):

self.elements=abs(self.elements)

self.product+=self.elements*self.elements
return math.sqrt(self.product)
def __add__(self, other):
"""Overloads the + operator to support
Vec + Vec
raises ValueError if vectors are
not same length
"""
self.addition=[]

if(len(self.elements)!=len(other.elements)):
raise ValueError
for i in
range(len(self.elements)):

self.addition.append(self.elements+other.elements)
return self.addition
def __sub__(self, other):
"""
Overloads the - operator to support Vec
- Vec
Raises a ValueError if the lengths of
both Vec objects are not the same
"""
self.subtraction=[]

if(len(self.elements)!=len(other.elements)):
raise ValueError
for i in
range(len(self.elements)):

self.subtraction.append(self.elements-other.elements)
return self.subtraction
def __mul__(self, other):
"""Overloads the * operator to
support
- Vec * Vec (dot product)
raises ValueError if vectors are not same length in the case of dot
product
- Vec * float
(component-wise product)
- Vec * int
(component-wise product)
"""
if type(other) == Vec: #define dot
product
#FIXME: IMPLEMENT
self.dotproduct=0

if(len(self.elements)!=len(other.elements)):
raise
ValueError
for i in
range(len(self.elements)):

self.dotproduct+=self.elements*other.elements
return
self.dotproduct
elif type(other) == float or
type(other) == int: #scalar-vector multiplication
#FIXME: IMPLEMENT
self.scalar=[]
for i in
range(len(self.elements)):

self.scalar.append(self.elements[i]*other)
return self.scalar
def __rmul__(self, other):
"""Overloads the * operation to
support
- float * Vec
- int * Vec
"""
self.scalar=[]
for i in
range(len(self.elements)):

self.scalar.append(self.elements[i]*other)
return self.scalar
def __str__(self):
"""returns string representation of
this Vec object"""
return str(self.elements)
Your Task:
Assuming 𝐴∈ℝ𝑛×𝑛A∈Rn×n is a Matrix object,
and 𝑏→∈ℝ𝑛b→∈Rn is a Vec object, implement a
function solve_qr(A, b) that uses the QR-factorization
of 𝐴A to compute and return the solution to the
system 𝐴𝑥→=𝑏→Ax→=b→.
Hints: