To Lecture Notes

IT 212 -- Oct 28, 2020

Review Exercises

  1. What is the output?
    a = int( );  b = float( );  c = str( );
    d = bool( );  e = list( );  f = dict( );
    print(a, b, c, d, e, f)
    
    # Output:
    0 0.0 False [] {}
    
    You get the default value of each datatype. The empty string, which is the default value for str, does not appear because the output from print('') is not visible. To make it visible, you need print(repr('')).
  2. Use a regular expression with the re.sub method to remove non-word characters from an input string. You did this for the Vehicle constructor method in Project 3a.
  3. Define a Pair class, whose objects represent ordered pairs of ints like this (3, 4). Supply __add__ and __mul__ methods that define + and * operators that act like this:
    (3, 4) + (5, 6) = (8, 10)
    (3, 4) * 2 = (6, 8)
    
    Translated to Python, this is
    p1 = new Pair(3, 4)
    p2 = new Pair(5, 6)
    print(p1 + p2, p1 * 2)
    # Output:
    (8, 10) (6, 8)
    
    Ans: Here is the Pair class:
    class Pair:
    
        def __init__(self, x, y):
            self.x = x
            self.y = y
    
        def __str__(self):
            return f'({self.x}, {self.y})'
    
        def __repr__(self):
            return str(self)
    
        def __eq__(self, other):
            return self.x == other.x and \
                   self.y == other.y
    
        def __add__(self, other):
            return Pair(self.x + other.x, \
                        self.y + other.y)
    
        def __mul__(self, other):
            return Pair(self.x * other, \
                        self.y * other)
    

Python Examples

Introduction to Java