Академический Документы
Профессиональный Документы
Культура Документы
Joaquim Gabarro
gabarro@cs.upc.edu
Computer Science
Universitat Politècnica de Catalunya
Ejemplos con for
Tiempo de cálculo
Programación Interactiva
Evaluación de un polinomio
Bibliografı́a
Ejemplos con for
Example: drawH(n)
>>> drawH(5)
* *
* *
*****
* *
* *
Veamos como imprimir los dos tipos de lineas horizontales que
aparecen en la H.
Recordemos que n ≥ 3 con lo que n-2>0.
>>> n=5
>>> print(n*’*’)
*****
>>> print(’*’ + (n - 2)*’ ’ + ’*’)
* *
>>>
Esquematicamente:
def drawH(n):
escribir n//2 veces
print(’*’ + (n - 2)*’ ’ + ’*’)
print(n*’*’)
escribir n//2 veces
print(’*’ + (n - 2)*’ ’ + ’*’)
Tratemos:
escribir n//2 veces
print(’*’ + (n - 2)*’ ’ + ’*’)
def drawH(n):
mid = n//2
for line in range(mid):
print(’*’ + (n - 2)*’ ’ + ’*’)
print(n*’*’)
for line in range(mid):
print(’*’ + (n - 2)*’ ’ + ’*’)
===== RESTART: C:/..../drawH.py =====
>>> drawH(9)
* *
* *
* *
* *
********
* *
* *
* *
* *
>>>
Ejemplo: Contando números primos
2, 3, 4, 5, 6, 7, 8, 9, 10
Hace falta buscar k in [6, 7, 8, 9]? Par que n=10 sea divisible
por 6 hace falta encontrar un z ≥ 2 tal que 6*z= 10 pero como
6*2 = 12 esto es imposible. Los casos 7, 8, 9 son similares.
Caso impar: n=9 tenemos [2, 3, 4 | 5, 6, 7, 8]
>>> n=9
>>> list(range(2, n//2+1))
[2, 3, 4]
>>> list(range(n//2+1, n))
[5, 6, 7, 8]
Hace falta buscar k in [5, 6, 7, 8]? Par que n=9 sea divisible
por 5 hace falta encontrar un z ≥ 2 tal que 5*z= 9 pero como
5*2 = 10 esto es imposible. Los casos 6, 7, 8 son similares.
Los ejemplos precedentes se pueden genralizar y formalizar sin
problema.
Conclusión: Independientemente de la paridad, es suficiente
recorrer range(2, n//2+1) con lo que tenemos:
def is_prime(n):
if n <= 1: return false
for k in range(2, n//2+1):
if n % k == 0: return False
return True
Finalmente (fichero count primes(n)):
def is_prime(n):
if n <= 1: return false
for k in range(2, n//2+1):
if n % k == 0: return False
return True
https://www.tutorialspoint.com/python/time_clock.htm
I Method time.clock() returns the current processor time as
a floating point number expressed in seconds on Unix and in
Windows it returns wall-clock seconds elapsed since the first
call to this function, as a floating point number.
I This is the function to use for benchmarking Python or timing
algorithms.
Example: Sleep time
def procedure():
time.sleep(2.5)
>>>
RESTART: C:/..../script_sleep_time.py
2.500300373589652 seconds process time
>>>
Tiempo de cálculo: count primes()
Fichero: count primes process time.py
import time
if __name__ == "__main__":
print(count_primes_process_time(100))
print(count_primes_process_time(10000))
print(count_primes_process_time(100000))
El tiempo de ejecución (en mi laptop) es:
>>>
RESTART: C:/.../Teo4/count_primes_process_time.py
(’Seconds process time: ’, 0.0004898137513077344)
(’Seconds process time: ’, 0.33380679151512876)
(’Seconds process time: ’, 28.312309173170494)
>>>
Primeros pasos en integración mumérica
Regla del rectángulo
b i=n
b−a
Z X
f (x) dx ≈ f (xi )
a n
i=0
I Notad b−a
n f (xi ) corresponde al area de un rectángulo de base
b−a
n y altura f (xi )
b−a
areai = f (xi ) = base × alturai
n
b−a b−a
I Notad que xi = x0 + i × n =a+ i× n
I En particular xn = a + n × b−a
n =b
Z b
f (x) dx ≈ area0 + area1 + · · · + arean
a
El programa consiste en un recorrido [0, . . . , n] que va calculando
las areai , 0 ≤ i ≤ n i acumula en una variable area total los valores
area total = 0
area total = area0
area total = area0 + area1
..
.
area total = area0 + area1 + · · · + arean
Caso: f (x) = x 2 (square function)
Recordad
>>> n= 10
>>> list(range(0,n+1))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
def integral_definida_sq(a,b,n):
x = a
base = (b - a) / n
area_total = 0
for i in range(0, n+1):
#calcular area rectangulo i-esimo
area_total = area_total + # area rectangulo i-esimo
x = x + base
return area
Fichero integral definida sq.py
def integral_definida_sq(a,b,n):
x = a
base = (b - a) / n
area_total = 0
for i in range(0, n+1):
altura = x * x
area = base * altura
area_total = area_total + area
x = x + base
return area_total
if __name__ == "__main__":
print(integral_definida_sq(0,1,1))
print(integral_definida_sq(0,1,10))
print(integral_definida_sq(0,1,100))
print(integral_definida_sq(0,1,1000))
print(integral_definida_sq(0,1,10000))
print(integral_definida_sq(0,1,100000))
print(integral_definida_sq(0,1,1000000))
El resultado es:
>>>
RESTART: C:...\integral_definida_sq.py
1.0
0.3849999999999999
0.3383500000000004
0.33383350000000095
0.3333833349999431
0.3333383333493713
0.3333338333339987
>>>
Rb R1
Recordad a x 2 dx = (b 3 − a3 )/3 entonces 0 x 2 dx = 1/3
>>> 1/3
0.3333333333333333
>>>
Recapitulemos.
I Hemos visto la función integral definida sq(a,b,n) que
era útil para integrar la funcion f (x) = x 2 .
I Si queremos canviar de funcion de f (x) = x 2 a f (x) = x 3
siempre podemos crear una cópia de
integral definida sq(a,b,n), bautizarla com
integral definida cube(a,b,n) y modificar
altura = x * x
por
altura = x*x*x
def my_square():
return lambda x: x*x
def my_cube():
return lambda x: x*x*x
def integral_definida(a,b,n,f):
x = a
base = (b - a) / n
area_total = 0
for i in range(0, n+1):
altura = f(x)
area = base * altura
area_total = area_total + area
x = x + base
return area_total
if __name__ == "__main__":
print(integral_definida(1, 100, 10000, my_square()))
print(integral_definida(1, 2, 1000, my_cube()))
Programación interactiva
Que pasa si nos equivocamos?
Typo None
>>> None
>>> type(None)
<class ’NoneType’>
>>> x=None
>>> type(x)
<class ’NoneType’>
>>> x=3
>>> type(x)
<class ’int’>
>>>
Ejemplo: la pertinaz lectura
I while...
I try...
While
http://anh.cs.luc.edu/python/hands-on/3.1/handsonHtml/
whilestatements.html
En castellano:
mientras tu te esta demasiado caliente :
a~
nade un poco de hielo
Recordad:
try:
x= int(input("entra el valor entero de la x: "))
except ValueError:
...
except KeyboardInterrupt:
...
...
https://docs.python.org/3/tutorial/errors.html
The try statement works as follows.
I First, the try clause (the statement(s) between the try and
except keywords) is executed.
I If no exception occurs, the except clause is skipped and
execution of the try statement is finished.
I If an exception occurs during execution of the try clause, the
rest of the clause is skipped. Then if its type matches the
exception named after the except keyword, the except clause
is executed, and then execution continues after the try
statement.
%Toma paloma
Evaluación de un polinomio
Ejemplo: Polynomial evaluation (1) P96767 en
Statement. Write a program that reads a number x and a
polynomial p(x) = c0 x 0 + c1 x 1 + · · · + cn x n , and computes p(x).
I Input. Input consists of a real number x followed by the
description of the polynomial p(x): the real coefficients
c0 , c1 , . . . , cn in this order. (The first sample input/output
corresponds to the evaluation of p(x) = 3 + 4x + 5x 2 at
x = 2.)
I Output. Print p(x) with 4 digits after the decimal point.
Public test cases
Input
2
3 4 5
Output
31.0000
x, c0 , c1 , c2 , . . . , cn
x, c0 , c1 , c2 , . . . , cn , marca de fin
Desarrollamos dos versiones, para el Shell, que utilizan distintas
marcas de final de secuencia.
I (I) Jutge: utiliza el package jutge que hay que importar.
Utiliza como marca de fin: primero return y luego Ctrl+d.
>>> int(input())
<--- aqui Ctrl + d y aparece
Traceback ...
EOFError: EOF when reading a line <--- EOF es End of File
x = read(float)
pot = 1.
coef = read(float)
res = coef
coef = read(float)
while coef is not None:
pot = pot*x
res += coef*pot
coef = read(float)
print("{0:0.4f}".format(res))
x = float(input())
pot = 1.
coef = float(input())
res = coef
coef = float(input())
while coef is not None:
pot = pot*x
res += coef*pot
coef = rich_float_read()
print("{0:0.4f}".format(res))
Un ejemplo de ejecución:
== RESTART: C:...\poli_shell.py ==
2
3
4
5
31.0000
>>>
Contando de nuevo primos
Ejemplo de while: contando primos
def better_count_primes(n):
count=0
for n in range (2,n+1):
if better_is_prime(n): count=count+1
return count
def better_count_primes(n):...
if __name__ == "__main__":
print(better_count_primes_process_time(100))
print(better_count_primes_process_time(10000))
print(better_count_primes_process_time(100000))
El resultado es:
RESTART: C:/.../Teo4/better_count_primes_process_time.py
(’Seconds process time: ’, 0.00027221356562224266)
(’Seconds process time: ’, 0.02408535388616865)
(’Seconds process time: ’, 0.5367300580096495)
>>>
I While statement:
http://anh.cs.luc.edu/python/hands-on/3.1/
handsonHtml/whilestatements.html
I Errors and Exceptions
https://docs.python.org/3/tutorial/errors.html