Intro to Programming with Python Practical Session 10





![Vector class – addition >>> Vector([1, 2, 3]) + Vector([4, 5, 6]) Vector([5, 7, Vector class – addition >>> Vector([1, 2, 3]) + Vector([4, 5, 6]) Vector([5, 7,](https://slidetodoc.com/presentation_image_h2/8ca28b74e37858813683d41b2a9854cc/image-6.jpg)
![Vector class – multiplication by scalar >>> Vector([1, 2, 3]) * 3 Vector([3, 6, Vector class – multiplication by scalar >>> Vector([1, 2, 3]) * 3 Vector([3, 6,](https://slidetodoc.com/presentation_image_h2/8ca28b74e37858813683d41b2a9854cc/image-7.jpg)
![Vector class – supporting dot product >>> Vector([1, 2, 3]) * 3 Vector([3, 6, Vector class – supporting dot product >>> Vector([1, 2, 3]) * 3 Vector([3, 6,](https://slidetodoc.com/presentation_image_h2/8ca28b74e37858813683d41b2a9854cc/image-8.jpg)
![Vector class – absolute value (norm) >>> abs(Vector([3, 4])) 5. 0 class Vector: … Vector class – absolute value (norm) >>> abs(Vector([3, 4])) 5. 0 class Vector: …](https://slidetodoc.com/presentation_image_h2/8ca28b74e37858813683d41b2a9854cc/image-9.jpg)
![Using the vector class >>> a = Vector([1, 2, 3]) >>> b = a*3 Using the vector class >>> a = Vector([1, 2, 3]) >>> b = a*3](https://slidetodoc.com/presentation_image_h2/8ca28b74e37858813683d41b2a9854cc/image-10.jpg)

























- Slides: 35

Intro to Programming with Python Practical Session #10: Object Oriented Programming 2 1

Plan 1. Vector class (OOP, operator overloading) 2. Hamming Distance 3. Gene Class 4. Machine parts 2

Vectors Includes only numbers (ints or floats in our case) can be added, subtracted, multiplied by constants, can be multiplied together We will implement some of these using operator overloading 3

Vector class – based on lists class Vector: def __init__(self, lst): '''lst is a list input to the vector''' self. lst = lst[: ] def __repr__(self): return 'Vector(' + repr(self. lst)+ ')' Create a copy of the list to allow this: >>> l = [1, 2, 3] >>> v = Vector(l) >>> l[0] = 0 >>> v Vector([1, 2, 3]) 4

Deep copy vs Shallow copy Does the elements in lst need deep or shallow copy? ? 5
![Vector class addition Vector1 2 3 Vector4 5 6 Vector5 7 Vector class – addition >>> Vector([1, 2, 3]) + Vector([4, 5, 6]) Vector([5, 7,](https://slidetodoc.com/presentation_image_h2/8ca28b74e37858813683d41b2a9854cc/image-6.jpg)
Vector class – addition >>> Vector([1, 2, 3]) + Vector([4, 5, 6]) Vector([5, 7, 9]) class Vector: … def __add__(self, other): “creating new vector that sums 2 vectors. NOT CHANGING ANY OF THE VECTORS” if not isinstance(other, Vector): raise Type. Error("vectors may only be added to other vectors”) elif len(self. lst) != len(other. lst): raise Value. Error("only vectors of the same length can be added”) else: new = [] for i in range(len(self. lst)): 6 new. append(self. lst[i] + other. lst[i]) return Vector(new)
![Vector class multiplication by scalar Vector1 2 3 3 Vector3 6 Vector class – multiplication by scalar >>> Vector([1, 2, 3]) * 3 Vector([3, 6,](https://slidetodoc.com/presentation_image_h2/8ca28b74e37858813683d41b2a9854cc/image-7.jpg)
Vector class – multiplication by scalar >>> Vector([1, 2, 3]) * 3 Vector([3, 6, 9]) class Vector: … def __mul__(self, x): new = [] for i in range(len(self. lst)): new. append(self. lst[i] * x) return Vector(new) 7
![Vector class supporting dot product Vector1 2 3 3 Vector3 6 Vector class – supporting dot product >>> Vector([1, 2, 3]) * 3 Vector([3, 6,](https://slidetodoc.com/presentation_image_h2/8ca28b74e37858813683d41b2a9854cc/image-8.jpg)
Vector class – supporting dot product >>> Vector([1, 2, 3]) * 3 Vector([3, 6, 9]) >>> Vector([1, 2, 3]) * Vector([4, 5, 6]) 32 class Vector: … def __mul__(self, x): if isinstance(x, Vector): if len(self. lst) != len(x. lst): raise Value. Error("cannot multiply vectors with different lengths”) else: prod = 0 for i in range(len(self. lst)): prod += self. lst[i] * x. lst[i] return prod elif (isinstance(x, int) or isinstance(x, float)): new = [] for i in range(len(self. lst)): 8 new. append(self. lst[i] * x) return Vector(new)
![Vector class absolute value norm absVector3 4 5 0 class Vector Vector class – absolute value (norm) >>> abs(Vector([3, 4])) 5. 0 class Vector: …](https://slidetodoc.com/presentation_image_h2/8ca28b74e37858813683d41b2a9854cc/image-9.jpg)
Vector class – absolute value (norm) >>> abs(Vector([3, 4])) 5. 0 class Vector: … def __abs__(self): return (self * self) ** 0. 5 9
![Using the vector class a Vector1 2 3 b a3 Using the vector class >>> a = Vector([1, 2, 3]) >>> b = a*3](https://slidetodoc.com/presentation_image_h2/8ca28b74e37858813683d41b2a9854cc/image-10.jpg)
Using the vector class >>> a = Vector([1, 2, 3]) >>> b = a*3 >>> c = a+b >>> print b Vector([3, 6, 9]) >>> print c Vector([4, 8, 12]) >>> b = 3*a Traceback (most recent call last): File "<pyshell#23>", line 1, in <module> b = 3*a Type. Error: unsupported operand type(s) for *: 'int' and 'instance' [Hint: see __radd__ , there is also an __rmul__ to use…] 10

"רב־צורתיות"( הוא : פולימורפיזם )בעברית , במדעי המחשב תכונה של שפות תכנות המאפשרת לטפל בערכים מטיפוסים שונים בעזרת ממשק תוכנה אחיד One perk of operator overloading - polymorphism >>> >>> >>> a = Vector([1, 2, 3]) b = a*3 c = a+b multi_things = [a, 7, c, 15] for k in multi_things: print(k, "* 3 =", k * 3) #Overloading lets us iterate and multiply different types the same way Vector([1, 2, 3]) * 3 = Vector([3, 6, 9]) 7 * 3 = 21 Vector([4, 8, 12]) * 3 = Vector([12, 24, 36]) 15 * 3 = 45 11

Plan 1. Vector class (OOP, operator overloading) 2. Hamming Distance 3. Gene Class 4. Machine Parts 12

String similarity • Given a string, how close is it to another string? • “Close”? • How can we define distance between strings? 13

String Distance Function A string distance function d should measure the difference between two strings s 1, s 2 ‘jello' 'hallo' 'hello' ‘billy' d can then be used for spell checking – we replace a word with an error with the closest correct word in the dictionary 14

String Distance Function – Cont. ? 'world' ? 'hello' ? ‘billy' 15

Hamming Distance http: //en. wikipedia. org/wiki/Hamming_distance • Use the number of positions at which the corresponding symbols are different • Examples: 16

Hamming Distance Implementation def hamming_distance(w 1, w 2): if len(w 1) != len(w 2): raise Value. Error("cannot compare strings of different length”) dist = 0 for i in range(len(w 1)): if w 1[i] != w 2[i]: dist += 1 return dist >>> hamming_distance('hallo', 'hello') 1 >>> hamming_distance('hallo', 'billy') 3 >>> hamming_distance('hallo', 'queen') 5 >>> hamming_distance('hallo', 'king') … Value. Error: "cannot compare strings of different length” 17

Plan 1. Vector class (OOP, operator overloading) 2. Hamming Distance 3. Gene Class 4. Machine Parts 18

Gene Class • A gene is a sequence of the letters A, G, C, T • Create a class Gene to represent a gene • Implement __init__, __repr__, __len__: >>> Gene('AGc t. GT CAa GTC') AGCTGTCAAGTC >>> len(Gene('AGc t. GT CAa GTC')) 12 • Input to __init__ is a string • Should remove spaces, and convert to upper case • Should validate input (only AGCT are allowed) • __repr__ should return the gene as a string • __len__ should return the number of letters 19

Gene Class – Constructor >>> Gene('AGc t. GT CAa GTC') AGCTGTCAAGTC • Input to __init__ is a string • Should remove spaces, and convert to upper case • Should validate input (only AGCT are allowed) class Gene: def __init__(self, seq): self. seq = seq. replace(' ', ''). upper() if not self. is_valid(): raise Value. Error("Invalid sequence!”) 20

Gene Class – is_valid class Gene: def __init__(self, seq): self. seq = seq. replace(' ', ''). upper() if not self. is_valid(): raise Value. Error("Invalid sequence!“) def is_valid(self): bases = "ACGT" for c in self. seq: if c not in bases: return False return True 21

Gene Class – __repr__ and __len__ >>> Gene('AGc t. GT CAa GTC') AGCTGTCAAGTC >>> len(Gene('AGc t. GT CAa GTC')) 12 • __repr__ should return the gene as a string • __len__ should return the number of letters class Gene: … def __repr__(self): return self. seq def __len__(self): return len(self. seq) 22

Gene Class – distance Implement a distance method that returns Hamming distance between genes >>> a = Gene('AGC TGT CAA GTC') >>> b = Gene('AGC TCT CTG GTA') >>> a. distance(b) 4 class Gene: … def distance(self, other): if len(self) != len(other): raise Value. Error( "sequence length is not the same”) dist = 0 for i in range(len(self)): if self. seq[i] != other. seq[i]: dist += 1 return dist 23

Plan 1. Vector class (OOP, operator overloading) 2. Hamming Distance 3. Gene Class 4. Machine Parts 24


Question class TRange: def __init__(self, min_temp, max_temp): self. min_temp = min_temp self. max_temp = max_temp def __repr__(self): return "<" + str(self. min_temp) +", "+ str(self. max_temp) + ">" 26


Question 28

29

30

31

32

var=lambda x: x+2 print (var(4)) #6 var = lambda x: x**2+3*x-2 print (var(3))#16 var=lambda x, y: (x+y)/(x-y) print (var(8, 4))#3 33

34

def f(x): return 5 -x def smooth(f): return lambda x: (f(x-1)+f(x+1))/3 def g(): return smooth(f) print(g()(2)) 35