#!/usr/bin/env python # coding: utf-8 # # Python Clase 3: Strings and Lists # # Strings # # A sequence of characters # In[6]: s = 'hellou, how are you?' # In[7]: type(s) # ### string - immutable object # cannot modify it # In[42]: s[1] = 'a' # Everything in python is Oriented Object (oo) # # s is an object and one can apply a method # In[8]: s.capitalize(), s.upper() #OO - s.method() # In[9]: s.count('o'), s.count('ou') #we'll see later more aboyt regular expressions # In[19]: s.replace('o','i') #** see murcielago's homework # In[43]: s.replace('e', 'a', 1) #solamente una vez # In[13]: s.split(' ') #what happen with helliu? immutable object, strings dont change # In[17]: b = 'hello \t' + "how \n " + 'are' + 'you'*2 # they can 'sum' and 'multiply' # In[18]: print b # In[20]: c = 'roma' #** See anagramas' work d ='amor' # In[21]: sorted(c) == sorted(d) # ## Cadenas con eslavones # In[23]: s # In[26]: len(s) # ### indexing # In[27]: s[0], s[1] # In[29]: s[0:6], s[:6] #print only hellou # In[30]: s[16:20] #only imprimir you? # In[32]: s[-1] #indices can start counting from the end # In[33]: s[-4:] # In[34]: s.split(' ')[-1] #we'll see more on 'lists' section # In[35]: j =0 for i in s: #usual ex. is to print by pairs if j%2 ==0: print i j+=1 # ### Slicing # In[36]: s[::2] #in python, that's easy. Example: print every 3 from 9 to 16 # In[37]: s[::-1] #ex. print upside-down --- Exercise: do it by hand # #### Palindromo ? # In[38]: pal = 'anita lava la tina' #why pal != pal[::-1]? # In[39]: pal2 = pal.replace(' ', '') # In[40]: pal2 == pal2[::-1] #Examples: # Some men interpret nine memos # Was it a cat I saw? # O, a kak Uwakov lil vo kawu kakao! # ## Format string syntax # # printing statements # In[44]: num = 1/3. num # In[45]: '%e'%num #scientific notation # In[46]: '%4.2f' % num # float with some specifications # In[47]: '{0:4.2f}'.format(num) #Using format is much better than % # In[48]: '%.1f' % 2.567, '{0:.2f}'.format(2.567) # In[50]: #More formats from IPython.display import Image Image("figures/types.png") # In[51]: t = 0.001 y= 10.456 # In[52]: print 'At t=%g s, the height of the ball is %.2f m.' % (t, y) # In[53]: print 'At t={t:g} s, the height of the ball is {y:.2f} m.'.format( t=t, y=y) # # Lists # mutable objects # In[54]: colors = ['red', 'blue', 'green', 'black', 'white'] # no need to define, as in C++ # In[57]: type(colors) # In[58]: lista = [1, 'a', 3, 'hola'] #it can contain a mix of whathever, ..use numpy, more efficient lista # In[59]: colors[2] # for i in colors: # In[60]: colors[-2] # In[61]: # Slice notation colors[2:4] # In[62]: colors[::2] # In[63]: # lists are mutable objects # In[64]: colors[0] = 'yellow' # In[65]: colors # ### what else I can do? # colors. # In[68]: colors = ['red', 'blue', 'green', 'black', 'white'] # In[69]: colors.append('blue') # in-place # In[70]: colors # In[71]: colors + ['blue'] # it creates a new object # In[72]: colors # ## nested lists # In[75]: nest = [1,2,3,[4,5,['target']]] nest # In[76]: nest[3][2][0] # # Assignment operator # #Everything is an object # In[80]: a = [1, 2, 3] # Exercise # In[81]: b = a # In[82]: a # In[83]: b # In[84]: a is b # In[86]: b[1]= 'hi' #what's the 'a' value?? # In[87]: a #what happen?? ... asigning, modifies the attributes. # In[89]: id(a) == id(b) #better to make a copy of b, so it doesnt modify # In[90]: #python 3 -- old_list.copy() # old_list[:] -- copiar elementos b = list(a) # In[91]: id(b)== id(a) # ## modify a list in place # evitar crear espacios de memoria # # a = [1, 2, 3] # # b= a # b point to a # # a.append(4) # # print b # In[92]: a = [1, 2, 3] # In[93]: id(a) # In[94]: a = ['a', 'b', 'c'] # In[100]: id(a) # the id changed, cause it created another list # In[96]: # siempre no, y me regreso a = [1, 2, 3], id(a) # In[97]: a[:] = [1, 2, 3] # In[98]: a # In[101]: id(a) #the id remained, as the list was only modified # ## back # In[114]: colors = ['red', 'blue', 'green', 'black', 'white'] # In[115]: colors.pop() # In[116]: colors # if wants to remove something it isn't # In[117]: colors.remove('green') # In[118]: colors # In[119]: ## adding two colors at the same time? colors.append(['blue','purple']) # In[120]: colors # In[121]: colors = ['red', 'blue', 'green', 'black', 'white'] # In[122]: colors.extend(['blue', 'purple']) #in-place # In[123]: colors # In[124]: rcolors = colors[::-1] #assigment rcolors # In[125]: rcolors2 = list(colors) #creating a copy rcolors2 # In[126]: rcolors2.reverse() #in-place, a method modifies the attributes rcolors2 # ## sort # In[127]: sorted(rcolors) #new object # In[128]: rcolors # In[129]: rcolors.sort() # in-place # In[130]: rcolors # In[131]: rcolors.count('blue') # ## random # In[132]: import random # In[133]: random.random() #random numbers within [0,1] # In[134]: random.randint(1, 10) # In[135]: random.choice(colors) #chin-chan-pu # In[136]: suits = ['hearts', 'clubs', 'diamonds', 'spades'] suits # In[137]: random.shuffle(suits) suits # # ** Homework 4 # # # * Dos números amigos son dos números enteros positivos a y b tales que la suma de los divisores propios de uno es igual al otro número y viceversa # # los divisores propios de 220 son 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 y 110, que suman 284; # los divisores propios de 284 son 1, 2, 4, 71 y 142, que suman 220. # # (220, 284), (1184, 1210), (17 296, 18 416) y (9 363 584, 9 437 056) # # * Un número perfecto es un número natural que es igual a la suma de sus divisores propios positivos. Dicho de otra forma, un número perfecto es aquel que es amigo de sí mismo. # # 28, 496 y 8128 # # * Numero abundante σ(x) > 2x. La suma de todos los divisores positivos de x, incluido el propio x sumen más que dicho número 24. Sus divisores son 1, 2, 3, 4, 6, 8, 12, 24 cuya suma es 60. Puesto que 60 es mayor que 2×24=48, el número 24 es abundante (sino, deficiente) y su abundancia es σ(x) - 2x (σ(x)= 2x es perfecto) # # 12, 18, 20, 24, 30 # In[30]: #Esta función permite comprobar si dos números positivos son amigos. # In[33]: #Usando la función anterior, comprobamos si un número natural n>1 es perfecto. # In[57]: #Esta función nos indica si el número n>1 es deficiente, perfecto o abundante.