0% found this document useful (0 votes)
12 views

Python notes

Uploaded by

nuriaa.ferrerr
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

Python notes

Uploaded by

nuriaa.ferrerr
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 41

Núria Ferrer Noguera CodeWars ‘24

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

There are three numeric types in Python:


● int
● float
● complex (are written with a "j" as the imaginary part)

1.1.1. RANDOM NUMBER

1.2. Python strings


- You can assign a multiline string to a variable by using three quotes
- Check string: “free” in txt or “free” not in txt →bool (True/ False) / if or while
"free" in txt:

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:

- Reverse / inverse string:


b[::-1]

1.2.2. Format strings


The format() method takes the passed arguments, formats them, and places them
in the string where the placeholders {} are:

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:

1.2.3. Escape characters

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()

frase= " 1 2 3 4 5 "


frase= frase.replace(" ", "")
# Resultat: "12345"

6
- strip ()

1.3. Python bool


In fact, there are not many values that evaluate to False, except empty values, such
as (), [], {}, "", the number 0, and the value None. And of course the value False
evaluates to False.

-isinstance()

1.4. Python operators


Python divides the operators in the following groups:

● Arithmetic operators
● Assignment operators
● Comparison operators
● Logical operators
● Identity operators
● Membership operators
● Bitwise operators

7
1.4.1. Python Arithmetic Operators

1.4.2. Python Bitwise 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

1.5. Python lists

#result = ['apple', 'blackcurrant', 'watermelon', 'cherry']

If you insert less items than you replace, the new items will be inserted where you
specified, and the remaining items will move accordingly:

#result = ['apple', 'watermelon']

#result= ['apple', 'banana', 'watermelon', 'cherry']

- 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.

The del keyword can also delete the list completely.

1.5.1. Loop lists


Loop Through a List: for x in thisList
Loop Through the Index numbers: for x in range(len(thisList))

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.

LIST COMPREHENSION / Filtrar una lista


y = "1 2 3 4"
newlist = [x for x in y.split()]
print(newlist)

fruits = ["apple", "banana", "cherry", "kiwi", "mango"]


newlist = [x for x in fruits if "a" in x]
print(newlist)

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:

squares = list(map(lambda x: x**2, range(10)))

o, un equivalente:

11
squares = [x**2 for x in range(10)]

que es más conciso y legible.

Una lista de comprensión consiste de corchetes rodeando una expresión seguida de la


declaración for y luego cero o más declaraciones for o if. El resultado será una nueva
lista que sale de evaluar la expresión en el contexto de los for o if que le siguen. Por
ejemplo, esta lista de comprensión combina los elementos de dos listas si no son iguales:

[(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]

[(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)]

newlist = [x for x in range(10) if x < 5]

- Expression
Set the values in the new list to upper case:
newlist = [x.upper() for x in fruits]

Set all values in the new list to 'hello':


newlist = ['hello' for x in fruits]

Return "orange" instead of "banana":


newlist = [x if x != "banana" else "orange" for x in fruits]
#['apple', 'orange', 'cherry', 'kiwi', 'mango']

1.5.3. Sort lists


- Sort the list alphabetically: thislist.sort()
- Sort the list descending: thislist.sort(reverse = True)

12
1.5.3.1. Customize sort function

- Sort the list based on how close the number is to 50:


def myfunc(n):
return abs(n - 50)

thislist = [100, 50, 65, 82, 23]


thislist.sort(key = myfunc)
print(thislist)

#[50, 65, 23, 82, 100]

- By default, the sort() method is case-sensitive, resulting in all capital


letters being sorted before lower case letters:
Perform a case-insensitive sort of the list:
thislist = ["banana", "Orange", "Kiwi", "cherry"]
thislist.sort(key = str.lower)
print(thislist)

#['banana', 'cherry', 'Kiwi', 'Orange']

1.5.4. Copy lists


mylist = thislist.copy()
mylist = list(thislist)

1.5.5. Join lists


list3 = list1 + list2

for x in list2:
list1.append(x)

list1.extend(list2)

1.5.6. Sumar los elementos de una lista con la función sum ()


suma_de_notas = sum(notas)

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.

Hi ha vàries maneres de fer una còpia, una és utilitzar el mètode copy().

-----------------------------------------------------------
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.

1.5.8. Comprensión de listas

1.6. Python dictionaries

1.7. Python collections (Arrays) recap


def main():

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

print("\n #example for list")

tabla = [5,6]

print (tabla)

print (tabla[0])

tabla.append(10)

15
print(tabla)

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

print("\n #example for tuple")

t = 'a', 'b', 5

print(t)

v = ([1, 2, 3], [3, 2, 1])

print(v)

v[0].append(5)

print(v)

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

print("\n #example for set")

basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}

print(basket)

a = set('apple')

print(a)

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

print("\n #example for dictionary")

#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)

print('jack' not in tel)

l = list(tel)

print('resultado de list(): ', l)

for z in l:

print (z)

print(sorted(tel))

for k,v in tel.items():

print (k,v)

print(tel[k])

for k in tel.items():

print(k)

print(tel.values())

1.8. If…Else

- Python supports the usual logical conditions from mathematics:


● Equals: a == b
● Not Equals: a != b
● Less than: a < b
● Less than or equal to: a <= b
● Greater than: a > b
● Greater than or equal to: a >= b

- Pass statement: (also for a for loop)


if b > a:
pass

- If not
if not a > b:
print("a is NOT greater than b")

- Short Hand If ... Else:


print("A") if a > b else print("B")

print("A") if a > b else print("=") if a == b else print("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")

1.10. For loop


1.10.1. range()
- The range() function defaults to 0 as a starting value, however it is possible
to specify the starting value by adding a parameter: range(2, 6), which
means values from 2 to 6 (but not including 6):
for x in range(2, 6):
print(x)

- The range() function defaults to increment the sequence by 1, however it is


possible to specify the increment value by adding a third parameter: range(2,
30, 3):
for x in range(2, 30, 3):
print(x)
- The break Statement
- The continue Statement
- The else Statement
- The pass Statement: if b > a: pass

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.

- If the number of arguments is unknown, add a * before the parameter name:


def my_function(*kids):
print("The youngest child is " + kids[2])

my_function("Emil", "Tobias", "Linus")

- 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:

- Return Values: def my_function(x): return 5 * x


- The pass Statement
- Positional-Only Arguments:

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

print("\n\nRecursion Example Results")


tri_recursion(6)

#Result:
Recursion Example Results
1
3

19
6
10
15
21

1.12. Python Lambda


A lambda function is a small anonymous function.

A lambda function can take any number of arguments, but can only have one
expression.

lambda arguments : expression

1.12.1. Why Use Lambda Functions?


The power of lambda is better shown when you use them as an anonymous
function inside another function.

Say you have a function definition that takes one argument, and that
argument will be multiplied with an unknown number:

- Use that function definition to make a function that always doubles


the number you send in:

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:

1.13. Python Lambda


1.13.1. The __init__() Function
The examples above are classes and objects in their simplest form, and are
not really useful in real life applications.

To understand the meaning of classes we have to understand the built-in __init__()


function.

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:

1.13.3. Object Methods


Objects can also contain methods. Methods in objects are functions that
belong to the object.

Let us create a method in the Person class:

1.13.4. The self parameter


The self parameter is a reference to the current instance of the class, and is
used to access variables that belongs to the class.

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

1.14. Python modules


import platform

x = dir(platform)
print(x)

You can choose to import only parts from a module, by using the from keyword.

1.15. Python math


1.15.1. Built-in Math Functions
- The min() and max() functions can be used to find the lowest or highest
value in an iterable:

23
- The abs() function returns the absolute (positive) value of the specified
number:

- The pow(x, y) function returns the value of x to the power of y (xy).

- The round() function returns a floating point number that is a rounded


version of the specified number, with the specified number of decimals:

round(number, digits)

1.15.2. The math module

- The math.sqrt() method for example, returns the square root of a number:

- The math.ceil() method rounds a number upwards to its nearest integer,


and the math.floor() method rounds a number downwards to its nearest
integer, and returns the result:

- The math.pi constant, returns the value of PI (3.14...):


- math.e

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.

2.2. Reverse string

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
##
##

Com inicialitzar (1) una matriu amb llistes:

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):

# Inicialitzar la sèrie amb els primers n elements sent 1:

serie = [1] * n

# Generar els següents m-n elements de la sèrie:

for i in range(n, m):


nuevo_elemento = sum(serie[i-n:i])
serie.append(nuevo_elemento)

return serie

3.5. Me hago rico


def si_mitad (cadena):
suma_cadena=0
for c in cadena:
suma_cadena += int(c)

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 i in range(4, len(valores)):


v = int(valores[i])
v4 = max(v1 + v, v2, v3)
v1 = v2
v2 = v3
v3 = v4
print(v3)

linea = input() #sys.stdin.readline()


#print(linea, len(linea))
valores = linea.split(' ')
29
#print(ord(linea[0]), ord(linea), type(linea[0]), type(linea))

3.7. Sobran Caramelos


n_casos = int(input())

for _ in range(n_casos):
first_line = input()
second_line = input()

first_line = first_line.split(" ")


caramels_total = int(first_line[0])

max_resta = 0
for d in second_line.split(" "):
resta = caramels_total % int(d)
if resta > max_resta:
max_resta = resta

print(max_resta)

3.8. Llegar Meta


import sys

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

if per_x == met_x and per_y == met_y:


paso_encontrado = n_paso
found = True

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])

3.9. Reinas enemigas


number = int(input())

for i in range(number):

line = input().split(" ")


31
nl = [int(x) for x in line]

if (nl[0] == nl[2]) or (nl[1] == nl[3]) or abs(nl[0] - nl[2]) == abs(nl[1] - nl[3]):


print("SON ENEMIGAS")
else:
print("AMIGAS PARA SIEMPRE")

3.10. MCD
import sys

# calcula el mcd de dos numeros


# para ello utilizamos el algoritmo de euclides
# el m.c.d de a y b es el m.c.d. de b y a módulo b, si a módulo b es cero, entonces
el m.c.d. es b
def mcd(a, b):
if b == 0:
return a
resto = a % b
return mcd(b, resto)

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

3.12. Pasa a Mayúsculas


import sys

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

for i in range(0, len(word)-1):


# Look for a candidate pair of vowels in the word
if (isVowel(word[i]) and isVowel(word[i+1])):
# Check that there are no vowels before or after

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

# This is a real pair of vowels swap them


outputWord = outputWord[:i] + word[i+1] + word[i] + outputWord[i+2:]

print(outputWord)

35
3.14. Periodic numbers

3.15. working with dicts


l = []
p = dict()
e=0
mvp = ""

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")

3.16. Comparar si un string és igual o no


l = []
b = True

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")

3.17. suma consecutiva


n = input()
p = input()

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)

if rn == 1: print("You tend to be critical of yourself.")


elif rn == 2: print("You have a great deal of unused capacity which you have not turned to
your advantage.")
elif rn == 3: print("While you have some personality weaknesses, you are generally able to
compensate for them.")
elif rn == 4: print("At times you are extroverted, affable, sociable, while at other times you
are introverted, wary, reserved.")
elif rn == 5: print("Disciplined and self-controlled outside, you tend to be worrisome and
insecure inside.")
elif rn == 6: print("At times you have serious doubts as to whether you have made the right
decision or done the right thing.")
elif rn == 7: print("You prefer a certain amount of change and variety and become
dissatisfied when hemmed in by restrictions and limitations.")
elif rn == 8: print("You pride yourself as an independent thinker and do not accept others'
statements without satisfactory proof.")
elif rn == 9: print("You have found it unwise to be too frank in revealing yourself to others.")

3.18. INTERPRETACIÓ DE FORMULES 𝑚𝑒𝑎𝑛 𝑣𝑎𝑙𝑢𝑒 = 𝑥 = 𝑚𝑖𝑡𝑗𝑎𝑛𝑎

3.19. Calculador d’hores

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

3.20. The royal battle game

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

You might also like