1.1. Mathematics

1.1.1. Builtin

1.1.1.1. Constans

  • inf or Infinity

  • -inf or -Infinity

  • 1e6 or 1e-4

1.1.1.2. Functions

  • abs()

  • round()

  • pow()

  • sum()

  • min()

  • max()

  • divmod()

  • complex()

1.1.2. math

1.1.2.1. Constants

import math

math.pi
math.e

1.1.2.2. Degree/Radians Conversion

import math

math.degrees(x)
math.radians(x)

1.1.2.3. Rounding to lower

import math

math.floor(3.14)                # 3
math.floor(3.00000000000000)    # 3
math.floor(3.00000000000001)    # 3
math.floor(3.99999999999999)    # 3

1.1.2.4. Rounding to higher

import math

math.ceil(3.14)                 # 4
math.ceil(3.00000000000000)     # 3
math.ceil(3.00000000000001)     # 4
math.ceil(3.99999999999999)     # 4

1.1.2.5. Logarithms

import math

math.log(x)     # if base is not set, then ``e``
math.log(x, base=2)
math.log(x, base=10)
math.log10()

math.exp(x)

1.1.2.6. Linear Algebra

import math

math.sqrt()
math.pow(x, y)
import math

math.hypot()    # 2D, since Python 3.8 also multiple dimensions
math.dist()     # Euclidean distance, Since Python 3.8

1.1.2.7. Trigonometry

import math

math.sin()
math.cos()
math.tan()
import math

math.sinh()
math.cosh()
math.tanh()
import math

math.asin(x)
math.acos(x)
math.atan(x)
math.atan2(x)
import math

math.asinh(x)
math.acosh(x)

1.1.2.8. Infinity

from math import isinf


isinf(float('inf'))         # True
isinf(float('Infinity'))    # True
isinf(float('-inf'))        # True
isinf(float('-Infinity'))   # True

isinf(1e308)                # False
isinf(1e309)                # True

isinf(1e-9999999999999999)  # False

1.1.2.9. Absolute value

abs(1)          # 1
abs(-1)         # 1

abs(1.2)        # 1.2
abs(-1.2)       # 1.2
from math import fabs

fabs(1)         # 1.0
fabs(-1)        # 1.0

fabs(1.2)       # 1.2
fabs(-1.2)      # 1.2
from math import fabs

vector = [1, 0, 1]

abs(vector)
# TypeError: bad operand type for abs(): 'list'

fabs(vector)
# TypeError: must be real number, not list
from math import sqrt


def vector_abs(vector):
    return sqrt(sum(n**2 for n in vector))


vector = [1, 0, 1]
vector_abs(vector)
# 1.4142135623730951
from math import sqrt


class Vector:
    def __init__(self, x, y, z):
        self.x = x
        self.y = y
        self.z = z

    def __abs__(self):
        return sqrt(self.x**2 + self.y**2 + self.z**2)


vector = Vector(x=1, y=0, z=1)
abs(vector)
# 1.4142135623730951

1.1.3. Assignments

1.1.3.1. Trigonometry

English
  1. Read input (angle in degrees) from user

  2. User will type int or float

  3. Print all trigonometric functions (sin, cos, tg, ctg)

  4. If there is no value for this angle, raise an exception

Polish
  1. Program wczytuje od użytkownika wielkość kąta w stopniach

  2. Użytkownik zawsze podaje int albo float

  3. Wyświetl wartość funkcji trygonometrycznych (sin, cos, tg, ctg)

  4. Jeżeli funkcja trygonometryczna nie istnieje dla danego kąta podnieś stosowny wyjątek

Hint
  • input('Type angle [deg]: ')

1.1.3.2. Euclidean distance 2D

English
  1. Given are two points A: Tuple[int, int] and B: Tuple[int, int]

  2. Coordinates are in cartesian system

  3. Points A and B are in two dimensional space

  4. Calculate distance between points using Euclidean algorithm

  5. Function must pass doctest

Polish
  1. Dane są dwa punkty A: Tuple[int, int] i B: Tuple[int, int]

  2. Koordynaty są w systemie kartezjańskim

  3. Punkty A i B są w dwuwymiarowej przestrzeni

  4. Oblicz odległość między nimi wykorzystując algorytm Euklidesa

  5. Funkcja musi przechodzić doctest

Input
def euclidean_distance(A, B):
    """
    >>> A = (1, 0)
    >>> B = (0, 1)
    >>> euclidean_distance(A, B)
    1.4142135623730951

    >>> euclidean_distance((0,0), (1,0))
    1.0

    >>> euclidean_distance((0,0), (1,1))
    1.4142135623730951

    >>> euclidean_distance((0,1), (1,1))
    1.0

    >>> euclidean_distance((0,10), (1,1))
    9.055385138137417
    """
    x1 = ...
    y1 = ...
    x2 = ...
    y2 = ...
    return ...
../../_images/math-euclidean-distance.png

Figure 57. Calculate Euclidean distance in Cartesian coordinate system

Hint
  • System Message: WARNING/2 (distance(a, b) = \sqrt{(x_2 - x_1)^2 + (y_2 - y_1)^2)

    latex exited with error [stdout] This is pdfTeX, Version 3.14159265-2.6-1.40.18 (TeX Live 2017/Debian) (preloaded format=latex) restricted \write18 enabled. entering extended mode (./math.tex LaTeX2e <2017-04-15> Babel <3.18> and hyphenation patterns for 84 language(s) loaded. (/usr/share/texlive/texmf-dist/tex/latex/base/article.cls Document Class: article 2014/09/29 v1.4h Standard LaTeX document class (/usr/share/texlive/texmf-dist/tex/latex/base/size12.clo)) (/usr/share/texlive/texmf-dist/tex/latex/base/inputenc.sty (/usr/share/texlive/texmf-dist/tex/latex/base/utf8.def (/usr/share/texlive/texmf-dist/tex/latex/base/t1enc.dfu) (/usr/share/texlive/texmf-dist/tex/latex/base/ot1enc.dfu) (/usr/share/texlive/texmf-dist/tex/latex/base/omsenc.dfu))) (/usr/share/texlive/texmf-dist/tex/latex/amsmath/amsmath.sty For additional information on amsmath, use the `?' option. (/usr/share/texlive/texmf-dist/tex/latex/amsmath/amstext.sty (/usr/share/texlive/texmf-dist/tex/latex/amsmath/amsgen.sty)) (/usr/share/texlive/texmf-dist/tex/latex/amsmath/amsbsy.sty) (/usr/share/texlive/texmf-dist/tex/latex/amsmath/amsopn.sty)) (/usr/share/texlive/texmf-dist/tex/latex/amscls/amsthm.sty) (/usr/share/texlive/texmf-dist/tex/latex/amsfonts/amssymb.sty (/usr/share/texlive/texmf-dist/tex/latex/amsfonts/amsfonts.sty)) (/usr/share/texlive/texmf-dist/tex/latex/anyfontsize/anyfontsize.sty) (/usr/share/texlive/texmf-dist/tex/latex/tools/bm.sty) (./math.aux) (/usr/share/texlive/texmf-dist/tex/latex/amsfonts/umsa.fd) (/usr/share/texlive/texmf-dist/tex/latex/amsfonts/umsb.fd) ! Missing } inserted. <inserted text> } l.13 ... b) = \sqrt{(x_2 - x_1)^2 + (y_2 - y_1)^2$ [1] (./math.aux) ) (see the transcript file for additional information) Output written on math.dvi (1 page, 524 bytes). Transcript written on math.log.

1.1.3.3. Euclidean distance n dimensions

English
  1. Given are two points A: Sequence[int] and B: Sequence[int]

  2. Coordinates are in cartesian system

  3. Points A and B are in N-dimensional space

  4. Points A` and ``B must be in the same space

  5. Calculate distance between points using Euclidean algorithm

  6. Function must pass doctest

Polish
  1. Dane są dwa punkty A: Sequence[int] i B: Sequence[int]

  2. Koordynaty są w systemie kartezjańskim

  3. Punkty A i B są w N-wymiarowej przestrzeni

  4. Punkty A i B muszą być w tej samej przestrzeni

  5. Oblicz odległość między nimi wykorzystując algorytm Euklidesa

  6. Funkcja musi przechodzić doctest

Input
def euclidean_distance(A, B):
    """
    >>> A = (0,1,0,1)
    >>> B = (1,1,0,0)
    >>> euclidean_distance(A, B)
    1.4142135623730951

    >>> euclidean_distance((0,0,0), (0,0,0))
    0.0

    >>> euclidean_distance((0,0,0), (1,1,1))
    1.7320508075688772

    >>> euclidean_distance((0,1,0,1), (1,1,0,0))
    1.4142135623730951

    >>> euclidean_distance((0,0,1,0,1), (1,1,0,0,1))
    1.7320508075688772

    >>> euclidean_distance((0,0,1,0,1), (1,1))
    Traceback (most recent call last):
        ...
    ValueError: Points must be in the same dimensions
    """
    return ...
Hint
  • distance(a, b) = \sqrt{(x_2 - x_1)^2 + (y_2 - y_1)^2 + ... + (n_2 - n_1)^2}

  • for n1, n2 in zip(A, B)

1.1.3.4. Matrix multiplication

  • Complexity level: hard

  • Lines of code to write: 6 lines

  • Estimated time of completion: 20 min

  • Filename: solution/math_matmul.py

English
  1. Multiply matrices using nested for loops

  2. Function must pass doctest

Polish
  1. Pomnóż macierze wykorzystując zagnieżdżone pętle for

  2. Funkcja musi przechodzić doctest

Input
def matrix_multiplication(A, B):
    """
    >>> A = [[1, 0], [0, 1]]
    >>> B = [[4, 1], [2, 2]]
    >>> matrix_multiplication(A, B)
    [[4, 1], [2, 2]]

    >>> A = [[1,0,1,0], [0,1,1,0], [3,2,1,0], [4,1,2,0]]
    >>> B = [[4,1], [2,2], [5,1], [2,3]]
    >>> matrix_multiplication(A, B)
    [[9, 2], [7, 3], [21, 8], [28, 8]]
    """
    return
Hints
  • Zero matrix

  • Three nested for loops

1.1.3.5. Triangle

  • Complexity level: easy

  • Lines of code to write: 5 lines

  • Estimated time of completion: 10 min

  • Filename: solution/math_triangle.py

English
  1. Calculate triangle area

  2. User will input base and height

  3. Input numbers will be only int and float

  4. Function must pass doctest

Polish
  1. Obliczy pole trójkąta

  2. Użytkownik poda wysokość i długość podstawy

  3. Wprowadzone dane będą tylko int lub float

  4. Funkcja musi przechodzić doctest