1.12. Solutions: Lecture 1#

1.12.1. Exercise 1.1#

  • ex_1.1.py

#!/usr/bin/python
'''
  * Write a program that reads an integer given as input from the user 
    and determines whether it is divisible by 2, 3, 5, or 7.
  * Encapsulate the check into a function taking as input two numbers,
    and write a program that asks the user to insert two numbers 
    and checks whether the first is divisible by the other one (and vice-versa).
'''

def check_ratio (numerator, denominator):
  return (numerator % denominator) == 0


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


def main () :
    '''
    Funzione che implementa il programma principale
    '''

    number = int (input ('insert a number: '))
    dividers = [2., 3., 5., 7.]
    for div in dividers :
      if (check_ratio (number, div)) : 
        print (str (number) + ' is divisible by ' + str (div))
      else :  
        print (str (number) + ' is NOT divisible by ' + str (div))


    number = int (input ('insert a numerator: '))
    diviser = int (input ('insert a denominator: '))
    if (check_ratio (number, diviser)) : 
      print (str (number) + ' is divisible by ' + str (diviser))
    else :  
      print (str (number) + ' is NOT divisible by ' + str (diviser))


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


if __name__ == "__main__":
    main ()

1.12.2. Exercise 1.2#

  • ex_1.2.py

#!/usr/bin/python
'''
  * Write a program that, given the three sides of a triangle, 
    determines whether the triangle is acute-angled, rectangular-angled or obtuse-angled.
'''

def main () :
    '''
    Funzione che implementa il programma principale
    '''
    sides = []
    sides.append (float (input ('insert the first side size: ')))
    sides.append (float (input ('insert the second side size: ')))
    sides.append (float (input ('insert the third side size: ')))
    sides.sort ()
    print ('I lati inseriti sono i seguenti:')
    print (sides)

    if (sides[0]**2 + sides[1]**2 < sides[2]**2)   : print ('obtuse-angled') 
    elif (sides[0]**2 + sides[1]**2 > sides[2]**2) : print ('acute-angled')
    else                                           : print ('rectangular-angled')


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


if __name__ == "__main__":
    main ()

1.12.3. Exercise 1.3#

  • ex_1.1.py

#!/usr/bin/python
'''
  * Write a program that, by using a `while` loop, 
    returns the Fibonacci sequence up to the n-th term
    and stores it in a python `list`.
'''


def main () :
    '''
    Funzione che implementa il programma principale
    '''
    elements_num = int (input ('number of elements to calculate: '))

    fibonacci = [int (0), int (1)]
    if elements_num < 2 :
      print (fibonacci[:elements_num])
    index = int (2)
    while index < elements_num :
      fibonacci.append (fibonacci[-1] + fibonacci[-2])
      index += 1
    print (fibonacci)  


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


if __name__ == "__main__":
    main ()

1.12.4. Exercise 1.4#

  • ex_1.1.py

#!/usr/bin/python
'''
  * Write a program that, by using a `for` loop, 
    returns the Fibonacci sequence up to the n-th term
    and stores it in a python `dictionary`, 
    where the `key` represents the index of each element
    and `value` its actual value.
'''


def main () :
    '''
    Funzione che implementa il programma principale
    '''

    fibonacci = {}
    fibonacci[0] = int (0)
    fibonacci[1] = int (1)

    elements_num = int (input ('number of elements to calculate: '))

    # the module itertools would allow to do this in a more compact way
    # https://docs.python.org/3/library/itertools.html
    if elements_num < 3 :
      for key in fibonacci.keys () :
        print ('element', key, ' : ', fibonacci[key])
        elements_num -= 1
        if elements_num == 0 : break

    for key in range (2, elements_num) :
      fibonacci[key] = fibonacci[key-1] + fibonacci[key-2]

    for key in fibonacci.keys () :
      print ('element', key, ' : ', fibonacci[key])


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


if __name__ == "__main__":
    main ()

1.12.5. Exercise 1.5#

  • ex_1.5.py

#!/usr/bin/python
'''
  * Define a function that returns the Fibonacci sequence up to the n-th term.

    `````{hint}
    The function prototype could be

    ```python
    def fibonacci (n) :
        """A function that calculates the Fibonacci sequence up to the n-th term

        Args:
            n (int): the n-th term of the sequence

        Returns:
            list: a list with the Fibonacci sequence
        """
    ```
    `````
  * Test the function with a `main` program,
    filling a `list` with the elements of the sequence.
  * Create a new list containing only the elements with even index in the `list`.  
  * Create a new list containing only the elements with odd index in the `list`.
  * Move the function in a library and import it in the main program.
'''

from fibonacci import fibonacci


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


def main () :
    '''
    Funzione che implementa il programma principale
    '''

    elements_num = int (input ('number of elements to calculate: '))
    l_fibo = fibonacci (elements_num)
    print (l_fibo)
    l_fibo_even = l_fibo[::2] # slice from beginning to end with step 2
    l_fibo_odd = l_fibo[1::2] # slice from second element (1) to end with step 2
    print (l_fibo_even)
    print (l_fibo_odd)


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


if __name__ == "__main__":
    main ()

  • fibonacci.py

def fibonacci (elements_num) :
    """A function that calculates the Fibonacci sequence up to the n-th term

    Args:
        n (int): the n-th term of the sequence

    Returns:
        list: a list with the Fibonacci sequence
    """
    fibonacci = [int (0), int (1)]
    if elements_num < 2 :
      return fibonacci[:elements_num]
    index = int (2)
    while index < elements_num :
      fibonacci.append (fibonacci[-1] + fibonacci[-2])
      index += 1
    return fibonacci

1.12.6. Exercise 1.6#

  • ex_1.6.py

#!/usr/bin/python
'''
  * By writing a suitable program and functions,
    verify whether the value of variables passed to a function
    get modified in the main program, 
    if they are changed inside the function.
  * Perform the check for the various types described during the lecture.
'''

def double_it (number) :
    number *= 2
    print ('inside', number)


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


def add_element (input_list) :
    input_list.append (input_list[-1])


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


def main () :
    '''
    Funzione che implementa il programma principale
    '''


    m_number = 3.
    print ('outside before', m_number)
    double_it (m_number)
    print ('outside after', m_number)

    test_list = [3]
    add_element (test_list)
    print (test_list)


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


if __name__ == "__main__":
    main ()

1.12.7. Exercise 1.7#

  • ex_1.7.py

#!/usr/bin/python
'''
  * Write a python program that determines the solution of second-order
    equations
'''

from math import sqrt
import sys


def main () :
    '''
    Funzione che implementa il programma principale
    '''
    print ('starting from the equation ax^2 + bx +c = 0 in the real domain')
    param_a = float (input ('insert the value of a: '))
    param_b = float (input ('insert the value of b: '))
    param_c = float (input ('insert the value of c: '))
    print ('solving equation :')
    print (str (param_a) + 'x^2 + ' + str (param_b) + 'x + ' + str (param_c) + ' = 0')
    delta = param_b ** 2 - 4 * param_a * param_c
    if (delta < 0) : 
        print ('no real solutions exist')
        sys.exit (1)
    x_1 =  (-1 * param_b - sqrt (delta)) / 2 * param_a
    x_2 =  (-1 * param_b + sqrt (delta)) / 2 * param_a
    print ('x1 = ' + str (x_1))
    print ('x2 = ' + str (x_2))
    message = str (param_a) + 'x^2 + ' + str (param_b) + 'x + ' + str (param_c) + ' = '
    if (x_1 < 0) : message += '(x+' + str (-x_1) + ')'
    else         : message += '(x' + str (-x_1) + ')'
    if (x_2 < 0) : message += '(x+' + str (-x_2) + ')'
    else         : message += '(x' + str (-x_2) + ')'
    print (message)


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


if __name__ == "__main__":
    main ()

1.12.8. Exercise 1.8#

  • ex_1.8.py

#!/usr/bin/python
'''
  * Write a python program that finds the list of prime integer numbers
    smaller than 100, starting by knowing that 2 is a prime number
'''

from math import sqrt
import sys



def check_ratio (numerator, denominator):
    return (numerator % denominator) == 0


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


def main () :
    '''
    Funzione che implementa il programma principale
    '''
    l_primes = [2]
    for num in range (3,100) :
        is_prime = True
        for prime in l_primes :
            if check_ratio (num, prime) :
                is_prime = False
                break
        if is_prime : l_primes.append (num)
    print (l_primes)


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


if __name__ == "__main__":
    main ()

1.12.9. Exercise 1.9#

  • ex_1.9.py

#!/usr/bin/python
'''
  * Write a python program that finds the decomposition in prime factors
    of a positive integer number, implementing the algorithm 
    in a function encapsulated in a python module
  * Write a test function, in the library, 
    that checks the correctness of the procedure for all numbers 
    from 1 to 100  
'''

from primes import check_ratio, decompose
from math import sqrt
import sys



def check_ratio (numerator, denominator):
    return (numerator % denominator) == 0


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


def main () :
    '''
    Funzione che implementa il programma principale
    '''
    number = 1
    while number > 0 :
        number = int (input ('insert an integer number (-1 to quit): '))
        if number < 0 : break
        decomposition = decompose (number)
        print (decomposition)


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


if __name__ == "__main__":
    main ()