Python notes
Python notes
Python notes
1. Python Basics.............................................................................................................................. 2
1.1. Python data types and numbers............................................................................................2
1.1.1. RANDOM NUMBER..................................................................................................... 2
1.2. Python strings........................................................................................................................2
1.2.1. Slicing strings............................................................................................................... 3
1.2.2. Format strings.............................................................................................................. 3
1.2.3. Escape characters........................................................................................................4
1.2.4. String methods............................................................................................................. 5
1.3. Python bool........................................................................................................................... 7
1.4. Python operators................................................................................................................... 7
1.4.1. Python Arithmetic Operators........................................................................................ 8
1.4.2. Python Bitwise operators..............................................................................................8
1.5. Python lists............................................................................................................................ 9
1.5.1. Loop lists.................................................................................................................... 10
1.5.2. Range().......................................................................................................................11
LIST COMPREHENSION / Filtrar una lista.......................................................................... 11
1.5.3. Sort lists......................................................................................................................12
1.5.3.1. Customize sort function..................................................................................... 13
1.5.4. Copy lists.................................................................................................................... 13
1.5.5. Join lists......................................................................................................................13
1.5.6. Sumar los elementos de una lista con la función sum ()............................................ 13
1.5.7. IMPORTANT:.............................................................................................................. 14
1.5.8. Comprensión de listas................................................................................................ 15
1.6. Python dictionaries.............................................................................................................. 15
1.7. Python collections (Arrays) recap........................................................................................15
1.8. If…Else................................................................................................................................17
1.9. While loop............................................................................................................................18
1.10. For loop............................................................................................................................. 18
1.11. Python function..................................................................................................................19
1.11.1. Recursion..................................................................................................................19
1.12. Python Lambda................................................................................................................. 20
1.12.1. Why Use Lambda Functions?.................................................................................. 20
1.13. Python Lambda................................................................................................................. 21
1.13.1. The __init__() Function............................................................................................ 21
1.13.2. The __str__() Function............................................................................................. 22
1.13.3. Object Methods........................................................................................................ 22
1.13.4. The self parameter................................................................................................... 22
1.14. Python modules.................................................................................................................23
1.15. Python math...................................................................................................................... 23
1.15.1. Built-in Math Functions............................................................................................. 23
1.15.2. The math module..................................................................................................... 24
1.15.3. Math methods...........................................................................................................25
1.15.4. Math constants......................................................................................................... 26
2. Python How to............................................................................................................................ 27
2.1. How to Remove Duplicates From a Python List..................................................................27
2.2. Reverse string..................................................................................................................... 27
3. Basic exercises.......................................................................................................................... 27
3.1. Prime numbers.................................................................................................................... 27
3.2. Fibonnacci........................................................................................................................... 27
3.3. Inicialitzar matriu................................................................................................................. 28
3.4. N-bonnacci.......................................................................................................................... 28
3.5. Me hago rico........................................................................................................................28
3.6. Pescando............................................................................................................................ 29
3.7. Sobran Caramelos.............................................................................................................. 30
3.8. Llegar Meta......................................................................................................................... 30
3.9. Reinas enemigas.................................................................................................................31
3.10. MCD.................................................................................................................................. 32
3.11. Mediana.............................................................................................................................32
3.12. Pasa a Mayúsculas........................................................................................................... 33
1
1. Python Basics
1.1. Python data types and numbers
2
1.2.1. Slicing strings
- Specify the start index and the end index, separated by a colon, to return a
part of the string.
- Slice from the start: By leaving out the start index, the range will start at the
first character:
- Slice To the End: By leaving out the end index, the range will go to the end:
- Negative Indexing: Use negative indexes to start the slice from the end of
the string:
3
- The format() method takes unlimited number of arguments, and are placed into the
respective placeholders:
- You can use index numbers {0} to be sure the arguments are placed in the correct
placeholders:
4
1.2.4. String methods
5
OOObanana / ##banana## / bananaOOOO
- isalnum():
The isalnum() method returns True if all the characters are alphanumeric, meaning
alphabet letter (a-z) and numbers (0-9).
Example of characters that are not alphanumeric: (space)!#%&? etc.
- join(): The join() method takes all items in an iterable and joins them into one string.
A string must be specified as the separator.
- replace()
6
- strip ()
-isinstance()
● Arithmetic operators
● Assignment operators
● Comparison operators
● Logical operators
● Identity operators
● Membership operators
● Bitwise operators
7
1.4.1. Python Arithmetic Operators
- AND:
print(6 & 3)
#result = 2
"""
The & operator compares each bit and set it to 1 if both are 1, otherwise it is
set to 0:
6 = 0000000000000110
3 = 0000000000000011
--------------------
2 = 0000000000000010
====================
- <<
print(3 << 2)
"""
The << operator inserts the specified number of 0's (in this case 2) from the
right and let the same amount of leftmost bits fall off:
8
If you push 00 in from the left:
3 = 0000000000000011
becomes
12 = 0000000000001100
If you insert less items than you replace, the new items will be inserted where you
specified, and the remaining items will move accordingly:
- To append elements from another list to the current list, use the extend() method.
9
(If there are more than one item with the specified value, the remove() method
removes the first occurance)
If you do not specify the index, the pop() method removes the last item.
10
1.5.2. Range()
range(3,7)
# rang de 3 a 7, però no inclou el 7.
range(10)
# rang de 0 a 10, però no inclou el 10.
Por ejemplo, asumamos que queremos crear una lista de cuadrados, como:
>>>
>>> squares = []
>>> for x in range(10):
... squares.append(x**2)
...
>>> squares
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Nótese que esto crea (o sobreescribe) una variable llamada x que sigue existiendo luego
de que el bucle haya terminado. Podemos calcular la lista de cuadrados sin ningún efecto
secundario haciendo:
o, un equivalente:
11
squares = [x**2 for x in range(10)]
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
- The Syntax
newlist = [expression for item in iterable if condition == True]
The return value is a new list, leaving the old list unchanged.
- The iterable
You can use the range() function to create an iterable:
newlist = [x for x in range(10)]
- Expression
Set the values in the new list to upper case:
newlist = [x.upper() for x in fruits]
12
1.5.3.1. Customize sort function
for x in list2:
list1.append(x)
list1.extend(list2)
13
- count(): cantidad_sietes = notas.count(7.0)
1.5.7. IMPORTANT:
No es pot copiar una llista simplement escrivint llista2 = llista, perquè llista2 només serà
una referència a llista1, i els canvis realitzats a llista1 també es realitzaran automàticament
a llista2.
-----------------------------------------------------------
Com inicialitzar (#) una matriu amb llistes:
col=int(input())
fil=int(input())
m=[['#' for _ in range(x)] for _ in range (y)]
print(m)
Resultat 2x2
##
##
---------------------------------------------------------------
Com inicialitzar una llista:
llista = [v] * n
# a on v representa el valor i n el número d'elements.
14
---------------------------------------------------------------
Sumar el elements d'una llista:
sum(llista[n:m])
#suma el elements des de la posició n, inclòs, fins a l'element de la posició m, no inclòs.
#--------------------------------------------------
tabla = [5,6]
print (tabla)
print (tabla[0])
tabla.append(10)
15
print(tabla)
#--------------------------------------------------
t = 'a', 'b', 5
print(t)
print(v)
v[0].append(5)
print(v)
#--------------------------------------------------
print(basket)
a = set('apple')
print(a)
#--------------------------------------------------
#constructor
weight = dict([('Ramon',80),('Pedro',100),('Sara',50)])
print(weight)
tel={'jack':3445, 'sape':8970}
print(tel)
print(tel['jack'])
tel['guido'] = 1234
tel['jack'] = 1234
print(tel)
16
print('guido' in tel)
l = list(tel)
for z in l:
print (z)
print(sorted(tel))
print (k,v)
print(tel[k])
for k in tel.items():
print(k)
print(tel.values())
1.8. If…Else
- If not
if not a > b:
print("a is NOT greater than b")
17
1.9. While loop
With the while loop we can execute a set of statements as long as a condition is
true.
- The break Statement: With the break statement we can stop the loop even if the
while condition is true (also with for loop):
i=1
while i < 6:
print(i)
if i == 3:
break
i += 1
- The continue Statement: With the continue statement we can stop the current
iteration, and continue with the next (also with for loop)
i=0
while i < 6:
i += 1
if i == 3:
continue
print(i)
- The else Statement: With the else statement we can run a block of code once
when the condition no longer is true (also with for loop)
i=1
while i < 6:
print(i)
i += 1
else:
print("i is no longer less than 6")
18
1.11. Python function
def my_function():
print("Hello from a function")
my_function()
The terms parameter and argument can be used for the same thing: information that
are passed into a function.
- You can also send arguments with the key = value syntax.
- If the number of keyword arguments is unknown, add a double ** before the parameter
name:
1.11.1. Recursion
In this example, tri_recursion() is a function that we have defined to call itself
("recurse"). We use the k variable as the data, which decrements (-1) every
time we recurse. The recursion ends when the condition is not greater than 0
(i.e. when it is 0).
def tri_recursion(k):
if(k > 0):
result = k + tri_recursion(k - 1)
print(result)
else:
result = 0
return result
#Result:
Recursion Example Results
1
3
19
6
10
15
21
A lambda function can take any number of arguments, but can only have one
expression.
Say you have a function definition that takes one argument, and that
argument will be multiplied with an unknown number:
20
- Or, use the same function definition to make a function that always
triples the number you send in:
- Or, use the same function definition to make both functions, in the
same program:
All classes have a function called __init__(), which is always executed when the
class is being initiated.
Use the __init__() function to assign values to object properties, or other operations
that are necessary to do when the object is being created:
21
1.13.2. The __str__() Function
The __str__() function controls what should be returned when the class
object is represented as a string.
If the __str__() function is not set, the string representation of the object is
returned:
It does not have to be named self , you can call it whatever you like, but it
has to be the first parameter of any function in the class:
22
- Modify Object Properties: p1.age = 40
- Delete Object Properties: del p1.age
- Delete Objects: del p1
- The pass Statement: class Person:pass
x = dir(platform)
print(x)
You can choose to import only parts from a module, by using the from keyword.
23
- The abs() function returns the absolute (positive) value of the specified
number:
round(number, digits)
- The math.sqrt() method for example, returns the square root of a number:
24
1.15.3. Math methods
25
1.15.4. Math constants
26
2. Python How to
2.1. How to Remove Duplicates From a Python List
If you like to have a function where you can send your lists, and get them back without
duplicates, you can create a function and insert the code from the example above.
3. Basic exercises
3.1. Prime numbers
def es_primo(numero):
if numero < 2:
return False
for i in range(2, int(numero ** 0.5) + 1):
if numero % i == 0:
return False
return True
3.2. Fibonnacci
def es_fibonacci(numero):
a, b = 0, 1
while b < numero:
a, b = b, a + b
return b == numero or numero == 0
27
3.3. Inicialitzar matriu
Com inicialitzar (#) una matriu amb llistes:
col=int(input())
fil=int(input())
m=[['#' for _ in range(x)] for _ in range (y)]
print(m)
Resultat 2x2
##
##
col=int(input())
fil=int(input())
m=[[ 1 for _ in range(x)] for _ in range (y)]
print(m)
Resultat 2x2
11
11
3.4. N-bonnacci
def generar_serie(n, m):
serie = [1] * n
return serie
28
if suma_cadena % 2 != 0:
print("NO MITAD")
else:
meitat=0
i=0
while meitat != (suma_cadena/2) and meitat < (suma_cadena/2):
meitat += int(cadena[i])
i+=1
if meitat == (suma_cadena/2):
print(i)
else:
print("NO MITAD")
llista_principal = []
while True:
entrada_usuari = input().replace(" ", "")
if entrada_usuari == '0':
break
llista_principal.append(entrada_usuari[1:int(entrada_usuari[0])+1])
for x in llista_principal:
si_mitad(x)
3.6. Pescando
import sys
linea = input()#sys.stdin.readline()
valores = linea.split(' ')
while (linea != "0"):
v1 = int(valores[1])
v2 = max(v1, int(valores[2]))
v3 = max(v2, int(valores[3]))
for _ in range(n_casos):
first_line = input()
second_line = input()
max_resta = 0
for d in second_line.split(" "):
resta = caramels_total % int(d)
if resta > max_resta:
max_resta = resta
print(max_resta)
linea = sys.stdin.readline()
bloques = linea.split()
size_x = int(bloques[0])
size_y = int(bloques[1])
while size_x != 0 and size_y != 0:
mapa = []
linea = ['.']*size_x
for i in range (0, size_y):
mapa.append(linea.copy())
per_x = 0
per_y = 0
met_x = 0
met_y = 0
for y in range (0, size_y):
linea = sys.stdin.readline()
for x in range (0, size_x):
car = linea[x]
if (car == 'X'):
car = '.'
per_x = x
per_y = y
30
if (car == 'M'):
car = '.'
met_x = x
met_y = y
mapa[y][x] = linea[x]
linea = sys.stdin.readline().split()
num_pasos = int(linea[0])
paso_encontrado = -1
n_paso = 1
found = False
while n_paso <= num_pasos and not found:
paso = linea[n_paso]
if paso == 'N':
if mapa[per_y-1][per_x] != '#':
per_y -=1
if paso == 'S':
if mapa[per_y+1][per_x] != '#':
per_y +=1
if paso == 'E':
if mapa[per_y][per_x+1] != '#':
per_x +=1
if paso == 'O':
if mapa[per_y][per_x-1] != '#':
per_x -=1
n_paso += 1
if paso_encontrado == -1:
sys.stdout.write("NO\n")
else:
sys.stdout.write(str(paso_encontrado))
sys.stdout.write('\n')
linea = sys.stdin.readline()
bloques = linea.split()
size_x = int(bloques[0])
size_y = int(bloques[1])
for i in range(number):
3.10. MCD
import sys
def calcular_mcd():
valores = [int(x) for x in input().split()]
if valores[0] == 0:
return False
else:
resultado = valores[1] # el primer valor es el mcd
for x in valores[2:]:
resultado = mcd(max(resultado, x), min(resultado, x))
print(resultado)
return True
while calcular_mcd():
None
3.11. Mediana
import sys
def mediana():
valores = [int(x) for x in input().split()]
if valores[0] == 0:
return False
else:
valores = valores[1:]
valores.sort()
tam = len(valores)
32
if tam % 2 == 1:
print(valores[tam//2])
else:
v1 = valores[tam // 2-1]
v2 = valores[tam//2]
valor = (v1+v2)/2
# si la media de ambos es un entero debe salir sin el .0
if valor == int(valor):
valor = (int(valor))
print(valor)
return True
while mediana():
None
def es_vocal(c):
return c in ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']
def es_consonante(c):
return ('a'<=c <= 'z') and not es_vocal(c)
def minusculas(c):
if 'A' <= c <= 'Z':
return c.lower()
return c
def mayusculas(c):
if 'a' <= c <= 'z':
return c.upper()
return c
def caso():
linea = input()
resultado = ""
for i in range(0, len(linea)):
if es_vocal(linea[i]):
resultado += minusculas(linea[i])
elif es_consonante(linea[i]):
resultado += mayusculas(linea[i])
else:
resultado += linea[i]
print(resultado)
valor = int(input())
33
for _ in range(valor):
caso()
34
3.13. Newspeak vowel
def isVowel(c):
c = c.lower()
if (c=="a" or c=="e" or c=="i" or c=="o" or c=="u"):
return True
else:
return False
word = input()
outputWord = word
# Main program
if (i-1 >=0):
if (isVowel(word[i-1])):
# Found a vowel before, so discard this pair and continue the search
continue
if (i+2 <=len(word)-1):
if (isVowel(word[i+2])):
# Found a vowel after, so discard this pair and continue the search
continue
print(outputWord)
35
3.14. Periodic numbers
for x in range(int(input())):
l = input().split()
p[l[0]] = (2 * int(l[6])) + (4 * int(l[2]))
maxim = max(p.values())
for k, v in p.items():
if v == maxim:
mvp = k
e += 1
if e == 1:
print(mvp + " is the MVP with " + str(p[mvp]) + " points!")
else: print("DRAW")
while True:
36
i = input()
if i == "0": break
l.append(i)
u = input()
for x in l:
if x == u:
b = False
if b == True: print("0")
else: print("1")
sumN = 0
rsumN = 0
rrn = 0
sumP = 0
for x in n:
sumN += int(x)
for x in str(sumN):
rsumN += int(x)
for x in p:
sumP += ord(x)
while True:
if len(str(sumP)) == 1:
break
lsumP = sumP
sumP = 0
for x in str(lsumP):
sumP += int(x)
rn = str(sumP) + str(rsumN)
while True:
if len(str(rn)) == 1:
break
rrn = rn
rn = 0
for x in str(rrn):
37
rn += int(x)
i = input().split(",")[:7]
week = i[0].split(":")
i.pop(0)
wh = int(week[0])
wm = int(week[1])
38
l = []
sum = 0
h=0
for x in i:
r = x.strip(" ").split(":")
l.append(r)
for x in l:
sum += int(x[1])
if sum > 60:
sum -= 60
h += 1
h += int(x[0])
totalh = wh - h
totalm = wm - sum
39
3.21. Comparar valors a un diccionari
l = []
d = { "A": "Alpha", "B": "Bravo", "C": "Charlie", "D": "Delta", "E": "Echo", "F": "Foxtrot", ".":
"Decimal"}
while True:
i = input()
if i == "#":
break
l.append(i.split())
for x in l:
c = ""
for k in x:
for x in k:
print(x)
if x in d.keys(): c+= d[x] + " "
else: c+= x + " "
print(c)
40