2. Module dataclasses

Check out the slide.

[1]:
from dataclasses import dataclass
[2]:
@dataclass
class Point:
    x: float
    y: float
    z: float = 0.0
[3]:
p = Point(1.5, 2.5)
[4]:
p
[4]:
Point(x=1.5, y=2.5, z=0.0)
[5]:
def my_func():
    print("This is a function")
[6]:
my_func()
This is a function
[7]:
def multiply(x, y):
    return x*y

The function multiply expects two arguments: x and y. It returns x * y.

[8]:
multiply(3, 4)
[8]:
12

Por hacer

Show __add__

[9]:
x = 20
y = 19

if x > y:
    print(x, 'is greater than', y)
20 is greater than 19
[10]:
def compare(x, y):
    if x > y:
        print(x, 'is greater than', y)
    elif x < y:
        print(x, 'is less than', y)
    else:
        print(x, 'is equal to', y)
[11]:
if (x % 2 == 0) and (x % 3 == 0):
    print(x, 'can be divided by 6')
else:
    print(x, 'cannot be divided by 6')
20 cannot be divided by 6
[12]:
animals = ['dog', 'cat', 'sheep', 'alpaca']
[13]:
sorted(animals)
[13]:
['alpaca', 'cat', 'dog', 'sheep']
[14]:
len(animals)
[14]:
4
[15]:
animals[1]
[15]:
'cat'
[16]:
i = 0
while (i < 10):
    print(i)
    i += 1
0
1
2
3
4
5
6
7
8
9
[17]:
#i = 0
#while True:
#    if i > 20:
#        break
#    else:
#        i *= 1
#        print(i)
[18]:
for count in [1, 2, 3]:
    print(count)
1
2
3

Nota

Note that [expression1, expression2, ..., expressionN] is a list in Python.

[19]:
arr = [1, 2, 3]
for count in arr:
    print(count)
1
2
3
[20]:
for i in range(10):
    print(i)
0
1
2
3
4
5
6
7
8
9
[21]:
for color in ['red', 'blue', 'green']:
    print(color)
red
blue
green
[22]:
num = 1
for color in ['red', 'blue', 'green']:
    print(color, num)
    num += 1
red 1
blue 2
green 3
[23]:
condition = False

if condition == True:
    print("The condition is True")
else:
    print("The condition is False")
The condition is False
[24]:
if condition == True:
    pass
[25]:
if condition:
    pass
[26]:
assorted_list = [True, False, 1, 1.1, 1 + 2j, \
                 'Learn', b'Python']
[27]:
first_element = assorted_list[0]
first_element
[27]:
True
[28]:
assorted_list
[28]:
[True, False, 1, 1.1, (1+2j), 'Learn', b'Python']
[29]:
for item in assorted_list:
    print(type(item))
<class 'bool'>
<class 'bool'>
<class 'int'>
<class 'float'>
<class 'complex'>
<class 'str'>
<class 'bytes'>
[30]:
nested = [[1, 1, 1], [2, 2, 2], [3, 3, 3]]

for items in nested:
    for item in items:
        print(item, end=' ')
1 1 1 2 2 2 3 3 3

2.1. Fibonacci sequence

La sucesión

\[1, 1, 2, 3, 5, 8, 13, \ldots\]

es conocida como la sucesión de Fibonacci y sus números con frecuencia ocurren en la naturaleza. Lleva el nombre del comerciante y matemático italiano (Leonardo de Pisa, 1170-1250). Esta sucesión tiene la propiedad que, después de los primeros dos términos, cada término sucesivo es la suma de los dos términos precedentes.

\[\begin{aligned} t_1 &= 1\\ t_2 &= 1\\ t_3 &= 2 = t_1 + t_2\\ t_4 &= 3 = t_2 + t_3\\ t_5 &= 5 = t_3 + t_4\\ t_6 &= 8 = t_4 + t_5\text{ and so on}. \end{aligned}\]

Fibonacci propuso esta sucesión como una forma de modelar el crecimiento en el número de conejos producidos a partir de un solo par de conejos reproductores.

2.1.1. Recurrece relation for the Fibonacci sequence

\[t_1 = 1\text{ and } t_2 = 1\quad t_n = t_{n-2} + t_{n-1},\quad n\geq 3.\]
[31]:
a, b = 0, 1

while a < 1000:
    print(a, end = ' ')
    a, b = b, a + b
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
[32]:
from random import randint
[34]:
number = randint(1, 10)
niter = 0
print('Guess which number I chose between 1 to 10!')

while True:
    guess = int(input('Your guess: '))
    niter += 1
    if guess > number:
        print('Too high')
    elif guess < number:
        print('Too low')
    else:
        print(f'Needed {niter} iterations.')
        break
Guess which number I chose between 1 to 10!
Your guess: 5
Too high
Your guess: 3
Too high
Your guess: 4
Too high
Your guess: 2
Needed 4 iterations.

2.2. Python Classes

Python is an object oriented programming language. Almost everything in Python is an object, with its properties and methods.

Por hacer

First classes

[35]:
s = 'Hello!'
[36]:
s.upper()
[36]:
'HELLO!'
[37]:
s
[37]:
'Hello!'
[38]:
s2 = s.upper()
[39]:
s2
[39]:
'HELLO!'
[40]:
s
[40]:
'Hello!'
[41]:
text = 'AAaaAA'
[42]:
text.count('AA')
[42]:
2
[43]:
text.lower.count('a')
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-43-133adcbf8593> in <module>
----> 1 text.lower.count('a')

AttributeError: 'builtin_function_or_method' object has no attribute 'count'
[44]:
text.count('aA')
[44]:
1

Each object in Python is created from a class. Classes can be seen as object constructors, or «blueprints».

Create a class named MyClass, with a property named n:

[45]:
class MyClass:
    n = 5

Crete an object named LaMolina, and print the value of n:

[46]:
LaMolina = MyClass()
print(LaMolina)
<__main__.MyClass object at 0x7f1ba002dd60>