5.4. Examples: Lecture 5#

5.4.1. A simple class to handle rational numbers#

  • fraction.py

#!/usr/bin/python
'''
a simple class to handle fractions of integer numbers
'''


from math import gcd
import sys


def lcm (a, b) :
    """least common multiple 

    Args:
        a (int): the first number
        b (int): the second number

    Returns:
        int: the least common multiple of the two numbers
    """
    return a * b / gcd (a,b)


# ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- 


class Fraction :
    '''
    a simple class implementing a high-level object
    to handle fractions and their operations
    '''

    def __init__ (self, numerator, denominator) :
        """the constructor: initialises all the variables needed
        for the high-level object functioning

        Args:
            numerator (int): the numerator of the fraction
            denominator (int): the denominator of the fraction

        Raises:
            ValueError: Denominator cannot be zero
            ValueError: Numerator must be an integer
            ValueError: Denominator must be an integer
        """
        if denominator == 0 :
            raise ValueError ('Denominator cannot be zero')
        if type(numerator) != int:
            raise TypeError ('Numerator must be an integer')
        if not isinstance(denominator, int ): # alternative way to check the type
            raise TypeError ('Denominator must be an integer')
        
        # this allows to avoid calculating the LCM in the sum and subtraction
        common_divisor = gcd (self.numerator, self.denominator) # greatest common divisor 
        self.numerator = numerator // common_divisor
        self.denominator = denominator // common_divisor
        
    def print (self) :        
        '''
        prints the value of the fraction on screen
        '''
        print (str (self.numerator) + '/' + str (self.denominator))

    def ratio (self) :
        '''
        calculates the actual ratio between numerator and denominator,
        practically acting as a casting to float
        '''
        return self.numerator / self.denominator


    def __add__ (self, other) :
        """implements the addition of two fractions.
        Note that this function will be callable with the + symbol
        in the program

        Args:
            other (Fraction): the fraction to be added to the current one

        Returns:
            Fraction: the addition of the two fractions
        """
        new_numerator = self.numerator * other.denominator + other.numerator * self.denominator
        new_denominator = self.denominator * other.denominator
        return Fraction (new_numerator, new_denominator)
    
    def __sub__ (self, other) :
        """implements the subtraction of two fractions.
        Note that this function will be callable with the - symbol
        in the program

        Args:
            other (Fraction): the fraction to be subtracted from the current one

        Returns:
            Fraction: the subtraction of the two fractions
        """
        new_numerator = self.numerator * other.denominator - other.numerator * self.denominator
        new_denominator = self.denominator * other.denominator
        return Fraction (new_numerator, new_denominator)
    
    def __mul__ (self, other) :
        """
        implements the multiplications of two fractions.
        Note that this function will be callable with the * symbol
        in the program

        Args:
            other (Fraction): the fraction to be multiplied from the current one

        Returns:
            Fraction: the multiplication of the two fractions
        """
        new_numerator = self.numerator * other.numerator
        new_denominator = self.denominator * other.denominator
        return Fraction (new_numerator, new_denominator)
    
    def __truediv__ (self, other) :
        '''
        implements the ratio of two fractions.
        Note that this function will be callable with the / symbol
        in the program

        Args:
            other (Fraction): the fraction to be divided from the current one

        Returns:
            Fraction: the ratio of the two fractions
        '''
        if other.numerator == 0 :
            print ('Cannot divide by zero')
            sys.exit (1)
        
        new_numerator = self.numerator * other.denominator
        new_denominator = self.denominator * other.numerator
        return Fraction (new_numerator, new_denominator)


# ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- 


def testing ()  :
    '''
    Function to test the class behaviour, called in the main program
    '''

    print ('Initial fractions:')
    frac1 = Fraction (3, 4)
    frac1.print ()
    print ('ratio: ', frac1.ratio ())

    frac2 = Fraction (1, 2)
    frac2.print ()
    print ('ratio: ', frac2.ratio ())
    
    sum_frac = frac1 + frac2
    print ('\nSum :')
    sum_frac.print ()
    
    diff_frac = frac1 - frac2
    print ('\nDifference:')
    diff_frac.print ()
    
    prod_frac = frac1 * frac2
    print ('\nProduct:')
    prod_frac.print ()
    
    div_frac = frac1 / frac2
    print ('\nDivision:')
    div_frac.print ()
    

# ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- 

    
if __name__ == "__main__" :
    testing ()

5.4.2. A simple test of a lambda function#

  • lambda.py

#!/usr/bin/python
'''
a simple example of lambda function definition
'''

def square (a):
    return a**2


# ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- 

    
if __name__ == "__main__" :

    number = 5
    print (square (number))
    print ((lambda x : x**2)(number))

    f = lambda x : x**2
    print (f (number))

5.4.3. A simple test of the map function#

  • map.py

#!/usr/bin/python
'''
a simple example of the map function use
'''

def square (a):
    return a**2


# ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- 

    
if __name__ == "__main__" :

    # create a list to be used as an example
    lista = list (range (-5, 5))

    squared = list (map (square, lista))

    for e, esq in zip (lista, squared) :
        print (e, esq)

    squared2 = list (map (lambda x : x**2, lista))

    for e, esq in zip (lista, squared2) :
        print (e, esq)

5.4.4. A simple test of the filter function#

  • filter.py

#!/usr/bin/python
'''
a simple example of the filter function use
'''

    
if __name__ == "__main__" :

    lista = list (filter (lambda x: x % 2 == 0, range(-5, 5)))
    for e in lista : print (e)