Basics

* algoritmos

* arquitectura

* funciones basicas

input, output, variables, while, for, if, def, vectores, diccionario, tupla y lista, graficacion

https://github.com/cosmolejo?tab=repositories

* extra (tiempo)

arquitectura:

http://foobarnbaz.com/2012/07/08/understanding-python-variables/ (ayuda grafica)

en python : no hay un valor fijo de memoria maximo para almacenar variables, el valor maximo, depende de la memoria disponible en el computador


In [1]:
import sys
print ('maximo float: ',sys.float_info.max)
print ('minimo float: ',sys.float_info.min)
print ('int: numero de bits por digito ',sys.int_info.bits_per_digit, 'esto es: ', 2**sys.int_info.bits_per_digit)


maximo float:  1.7976931348623157e+308
minimo float:  2.2250738585072014e-308
int: numero de bits por digito  30 esto es:  1073741824

In [1]:
import matplotlib.pyplot as plt
import numpy as np
plt.close("all")

x=np.linspace(-10,10)

cuadrado=plt.plot(x,x*x)

plt.axhline(0,color='k')
plt.axvline(0,color='k')


plt.savefig("cuadrado_py.png")
plt.show()



In [7]:
import matplotlib.pyplot as plt
from numpy import *
plt.close("all")


datos=loadtxt("experimento.dat")
x=datos[:,0]
y=datos[:,1]
plt.grid(True)


xlin=linspace(0.0,1.2)

exp=plt.plot(x,y,'+',color='r',markersize=5)
linea=plt.plot(xlin,9.8*xlin+0.5,'-',color='b')
plt.text(0.6211,5.10204,"v(t)=9.8t + vo",fontsize=14)

plt.xlabel("t (segundos)")
plt.ylabel("v(m/s)")
plt.title("Datos experimento de caida libre")


plt.savefig("experimento_py.png")
plt.show()



In [2]:
#!/usr/bin/env python
import math
#recoleccion de informacion
vo=input("ingrese la velocidad inicial del cuerpo: ")
ang=input("ingrese el angulo con el cual es lanzado (formato deg): ")
g=9.8;
#calculos iniciales
ymax=(((vo**2)*(math.sin(ang)**2)))/(2*g)
xmax=(((vo*vo)*(math.sin(ang)*math.cos(ang)))/(g))
t=(((2*vo)*(math.sin(ang)))/g)
#si el angulo es igual a 90 distancia en x es 0 despreciando la friccion
if (ang==90):
    xmax=0
    print"el alcance horizontal  maximo es ",xmax
    print"el tiempo de vuelo es ",t
    print"la altura maxima es ",ymax     
#si el angulo esta entre 90 y 0 ....
else:
    if(ang<90 and ang>=0):
        print"el alcance horizontal  maximo es: ",xmax
        print"el tiempo de vuelo es ",t
        print"la altura maxima es: ",ymax  	
#si el angulo supera 90 grados los calculos serian negativos...
if (ang>90 and ang<360):
    ang=ang-90
    ymax=(((vo**2)*(math.sin(ang)**2)))/(2*g)
    xmax=((((vo**2)*(math.sin(ang)*math.cos(ang)))/(g)))*(-1)
    t=((((2*vo)*(math.sin(ang)))/g))*(-1)
    print"atencion!! su disparo fue realizado hacia el lado contrario..."
    print"el alcance horizontal  maximo es: ",xmax
    print"el tiempo de vuelo es: ",t
    print"la altura maxima es: ",ymax


ingrese la velocidad inicial del cuerpo: 50
ingrese el angulo con el cual es lanzado (formato deg): 45
el alcance horizontal  maximo es:  114.030186684
el tiempo de vuelo es  8.68268902586
la altura maxima es:  92.3516336817

'''

Un número perfecto es un número natural que es igual a la suma de sus divisores propios positivos. Así, 6 es un número perfecto porque sus divisores propios son 1, 2 y 3; y 6 = 1 + 2 + 3. Los siguientes números perfectos son 28, 496 y 8128. '''

num=input("ingrese un numero: ") i=1 suma=0 while i<=(num-1): cond=num%i if cond == 0: suma+=i i+=1

if suma==num: print"el numero %d es perfecto \n"%(num)

else: print"el numero %d es no perfecto \n"%(num)


In [6]:
def primo(f):
    i=2
    sw=0
    while i<=(f-1):
        comp=f%i
        if comp==0:
            sw=1
            return 0
            break
            
        i+=1
        
    if sw==0:
        return 1
n=input("ingrese un numero: ")
print"factores primos: \n"
i=1   
while i<=(n):
    comp=n%i 
    if comp==0:
        p=primo(i)
        if (p==1):
            print" %d \n"%(i)
            
    i=i+1


ingrese un numero: 10
factores primos: 

 1 

 2 

 5 


In [9]:
%matplotlib inline
from scipy import stats
from scipy import constants as cons

led=[1.6325,2.424,2.566,3.24050,3.7095]
lamb=[1.10e6,1.60514e6,1.70648e6,1.76367e6,2.14133e6]
slope, intercept, r_value, p_value, std_err = stats.linregress(lamb,led)
x=np.linspace(lamb[0],lamb[-1],100)
y=slope*x+intercept
plt.plot(lamb,led,'o')
plt.plot(x,y,'-')
plt.show()
h_planck=slope*cons.e/cons.c
h=cons.h
error=(h_planck-h)/h
print ('r: ',r_value)
print ('pendiente: ',slope)
print ('error: ',std_err)
print ('h_planck: ',h_planck)
print ('h_real: ',h)
print ('error_h: ',error)


('r: ', 0.96119867210661936)
('pendiente: ', 2.0465599971059753e-06)
('error: ', 3.3910545887664333e-07)
('h_planck: ', 1.0937401835598243e-33)
('h_real: ', 6.62607004e-34)
('error_h: ', 0.65066197151128258)

Diferencias entre listas y tuplas

Una lista puede ser alterada, no así una tupla. (cambiar sus valores internos)

Una tupla puede ser utilizada como clave en un diccionario, no así una lista.

Una tupla consume menos espacio que una lista


In [24]:
tupla = (1,2,3,4,5,6,7,8,9,10)
lista = [1,2,3,4,5,6,7,8,9,10]
 
print(tupla.__sizeof__()) # 52 bytes
print(lista.__sizeof__()) # 60 bytes


104
120

In [25]:
lista+[11,12,13,14]


Out[25]:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]

In [26]:
for i in range(len(lista)):
    lista[i]*=2
print lista


lista1=lista
lista1=lista*2
print lista1


[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

In [13]:
tupla+(11,12,13,14)


Out[13]:
(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14)

In [15]:
x = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}

print "x['Name']: ", x['Name']
print "x['Age']: ", x['Age']


x['Name']:  Zara
x['Age']:  7

In [28]:
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}

dict['Age'] = 8; # update existing entry
dict['School'] = "DPS School"; # Add new entry


print "dict['Age']: ", dict['Age']
print "dict['School']: ", dict['School']


dict['Age']:  8
dict['School']:  DPS School

In [29]:
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}

del dict['Name']; # remove entry with key 'Name'
dict.clear();     # remove all entries in dict
del dict ;        # delete entire dictionary

print "dict['Age']: ", dict['Age']
print "dict['School']: ", dict['School']


dict['Age']: 
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-29-ffffed7d78fa> in <module>()
      5 del dict ;        # delete entire dictionary
      6 
----> 7 print "dict['Age']: ", dict['Age']
      8 print "dict['School']: ", dict['School']

TypeError: 'type' object has no attribute '__getitem__'

tiempo


In [31]:
import time
time.strptime("15 Nov 10", "%d %b %y")


Out[31]:
time.struct_time(tm_year=2010, tm_mon=11, tm_mday=15, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=0, tm_yday=319, tm_isdst=-1)

In [34]:
#diferencia de tiempo
import random
t=random.randint(1, 10)
print t
t1=time.time()
time.sleep(t)
t2=time.time()
print 'pasaron: ',t2-t1,'segundos '


8
pasaron:  8.00856900215 segundos 

In [14]:
import numpy

matriz=numpy.zeros((5,2,4,5))
print matriz


[[[[ 0.  0.  0.  0.  0.]
   [ 0.  0.  0.  0.  0.]
   [ 0.  0.  0.  0.  0.]
   [ 0.  0.  0.  0.  0.]]

  [[ 0.  0.  0.  0.  0.]
   [ 0.  0.  0.  0.  0.]
   [ 0.  0.  0.  0.  0.]
   [ 0.  0.  0.  0.  0.]]]


 [[[ 0.  0.  0.  0.  0.]
   [ 0.  0.  0.  0.  0.]
   [ 0.  0.  0.  0.  0.]
   [ 0.  0.  0.  0.  0.]]

  [[ 0.  0.  0.  0.  0.]
   [ 0.  0.  0.  0.  0.]
   [ 0.  0.  0.  0.  0.]
   [ 0.  0.  0.  0.  0.]]]


 [[[ 0.  0.  0.  0.  0.]
   [ 0.  0.  0.  0.  0.]
   [ 0.  0.  0.  0.  0.]
   [ 0.  0.  0.  0.  0.]]

  [[ 0.  0.  0.  0.  0.]
   [ 0.  0.  0.  0.  0.]
   [ 0.  0.  0.  0.  0.]
   [ 0.  0.  0.  0.  0.]]]


 [[[ 0.  0.  0.  0.  0.]
   [ 0.  0.  0.  0.  0.]
   [ 0.  0.  0.  0.  0.]
   [ 0.  0.  0.  0.  0.]]

  [[ 0.  0.  0.  0.  0.]
   [ 0.  0.  0.  0.  0.]
   [ 0.  0.  0.  0.  0.]
   [ 0.  0.  0.  0.  0.]]]


 [[[ 0.  0.  0.  0.  0.]
   [ 0.  0.  0.  0.  0.]
   [ 0.  0.  0.  0.  0.]
   [ 0.  0.  0.  0.  0.]]

  [[ 0.  0.  0.  0.  0.]
   [ 0.  0.  0.  0.  0.]
   [ 0.  0.  0.  0.  0.]
   [ 0.  0.  0.  0.  0.]]]]