4. Functions and Classes: Exercise

4. Functions and Classes: Exercise#

Name:

import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline

1. Functions#

Define the following functions and show some sample outputs.

  1. Factorial of n: \(1 \times 2 \times \cdots \times n\).

def factorial(n):
    """factorial of n"""
for n in range(1, 10):
    print(factorial(n))
None
None
None
None
None
None
None
None
None
  1. For a circle of radius r (default r=1), given x coordinate, return possible y coordinates (two, one, or None).

def circley(x, r=1):
    
  Cell In[4], line 2
    
    ^
SyntaxError: incomplete input
  1. Draw a star-like shape with n vertices, every m-th vertices connected, with default of n=5 and m=2.

def star(n=5, m=2):
    
  1. Any function of your interest

2. Classes#

  1. Define the Vector class with the following methods and test that they work correctly.

  • norm, normalize: as in the previous class (use L^p norm, with default p=2).

  • scale(s): multiply each component by scalar s.

  • dot(v): a dot product with another vector v.

class Vector:
    """A class for vector calculation."""
    
x = Vector([0, 1, 2])
x.vector
x.scale(3)
x.vector
y = Vector([1, 2, 3])
x.dot(y)
  1. Save the class Vector as a module vector.py.

  1. Import the module and test how it works.

import vector
import importlib
importlib.reload(vector) # This is needed after updating a module
x = vector.Vector([0, 1, 2])
x.vector