A sequence of characters
s = 'hellou, how are you?'
type(s)
str
cannot modify it
s[1] = 'a'
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-42-c4127d7f42a9> in <module>() ----> 1 s[1] = 'a' TypeError: 'str' object does not support item assignment
Everything in python is Oriented Object (oo)
s is an object and one can apply a method
s.capitalize(), s.upper() #OO - s.method()
('Hellou, how are you?', 'HELLOU, HOW ARE YOU?')
s.count('o'), s.count('ou') #we'll see later more aboyt regular expressions
(3, 2)
s.replace('o','i') #** see murcielago's homework
'helliu, hiw are yiu?'
s.replace('e', 'a', 1) #solamente una vez
'hallou, how are you?'
s.split(' ') #what happen with helliu? immutable object, strings dont change
['hellou,', 'how', 'are', 'you?']
b = 'hello \t' + "how \n " + 'are' + 'you'*2 # they can 'sum' and 'multiply'
print b
hello how areyouyou
c = 'roma' #** See anagramas' work
d ='amor'
sorted(c) == sorted(d)
True
s
'hellou, how are you?'
len(s)
20
s[0], s[1]
('h', 'e')
s[0:6], s[:6] #print only hellou
('hellou', 'hellou')
s[16:20] #only imprimir you?
'you?'
s[-1] #indices can start counting from the end
'?'
s[-4:]
'you?'
s.split(' ')[-1] #we'll see more on 'lists' section
'you?'
j =0
for i in s: #usual ex. is to print by pairs
if j%2 ==0: print i
j+=1
h l o , h w a e y u
s[::2] #in python, that's easy. Example: print every 3 from 9 to 16
'hlo,hwaeyu'
s[::-1] #ex. print upside-down --- Exercise: do it by hand
'?uoy era woh ,uolleh'
pal = 'anita lava la tina' #why pal != pal[::-1]?
pal2 = pal.replace(' ', '')
pal2 == pal2[::-1]
#Examples:
# Some men interpret nine memos
# Was it a cat I saw?
# O, a kak Uwakov lil vo kawu kakao!
True
printing statements
num = 1/3.
num
0.3333333333333333
'%e'%num #scientific notation
'3.333333e-01'
'%4.2f' % num # float with some specifications
'0.33'
'{0:4.2f}'.format(num) #Using format is much better than %
'0.33'
'%.1f' % 2.567, '{0:.2f}'.format(2.567)
('2.6', '2.57')
#More formats
from IPython.display import Image
Image("figures/types.png")
t = 0.001
y= 10.456
print 'At t=%g s, the height of the ball is %.2f m.' % (t, y)
At t=0.001 s, the height of the ball is 10.46 m.
print 'At t={t:g} s, the height of the ball is {y:.2f} m.'.format(
t=t, y=y)
At t=0.001 s, the height of the ball is 10.46 m.
mutable objects
colors = ['red', 'blue', 'green', 'black', 'white'] # no need to define, as in C++
type(colors)
list
lista = [1, 'a', 3, 'hola'] #it can contain a mix of whathever, ..use numpy, more efficient
lista
[1, 'a', 3, 'hola']
colors[2] # for i in colors:
'green'
colors[-2]
'black'
# Slice notation
colors[2:4]
['green', 'black']
colors[::2]
['red', 'green', 'white']
# lists are mutable objects
colors[0] = 'yellow'
colors
['yellow', 'blue', 'green', 'black', 'white']
colors.<TAB>
colors = ['red', 'blue', 'green', 'black', 'white']
colors.append('blue') # in-place
colors
['red', 'blue', 'green', 'black', 'white', 'blue']
colors + ['blue'] # it creates a new object
['red', 'blue', 'green', 'black', 'white', 'blue', 'blue']
colors
['red', 'blue', 'green', 'black', 'white', 'blue']
nest = [1,2,3,[4,5,['target']]]
nest
[1, 2, 3, [4, 5, ['target']]]
nest[3][2][0]
'target'
a = [1, 2, 3] # Exercise
b = a
a
[1, 2, 3]
b
[1, 2, 3]
a is b
True
b[1]= 'hi' #what's the 'a' value??
a #what happen?? ... asigning, modifies the attributes.
[1, 'hi', 3]
id(a) == id(b) #better to make a copy of b, so it doesnt modify
True
#python 3 -- old_list.copy()
# old_list[:] -- copiar elementos
b = list(a)
id(b)== id(a)
False
evitar crear espacios de memoria
a = [1, 2, 3]
b= a # b point to a
a.append(4)
print b
a = [1, 2, 3]
id(a)
4537913216
a = ['a', 'b', 'c']
id(a) # the id changed, cause it created another list
4538473864
# siempre no, y me regreso a = [1, 2, 3], id(a)
a[:] = [1, 2, 3]
a
[1, 2, 3]
id(a) #the id remained, as the list was only modified
4538473864
colors = ['red', 'blue', 'green', 'black', 'white']
colors.pop()
'white'
colors # if wants to remove something it isn't
['red', 'blue', 'green', 'black']
colors.remove('green')
colors
['red', 'blue', 'black']
## adding two colors at the same time?
colors.append(['blue','purple'])
colors
['red', 'blue', 'black', ['blue', 'purple']]
colors = ['red', 'blue', 'green', 'black', 'white']
colors.extend(['blue', 'purple']) #in-place
colors
['red', 'blue', 'green', 'black', 'white', 'blue', 'purple']
rcolors = colors[::-1] #assigment
rcolors
['purple', 'blue', 'white', 'black', 'green', 'blue', 'red']
rcolors2 = list(colors) #creating a copy
rcolors2
['red', 'blue', 'green', 'black', 'white', 'blue', 'purple']
rcolors2.reverse() #in-place, a method modifies the attributes
rcolors2
['purple', 'blue', 'white', 'black', 'green', 'blue', 'red']
sorted(rcolors) #new object
['black', 'blue', 'blue', 'green', 'purple', 'red', 'white']
rcolors
['purple', 'blue', 'white', 'black', 'green', 'blue', 'red']
rcolors.sort() # in-place
rcolors
['black', 'blue', 'blue', 'green', 'purple', 'red', 'white']
rcolors.count('blue')
2
import random
random.random() #random numbers within [0,1]
0.18403039526102483
random.randint(1, 10)
9
random.choice(colors) #chin-chan-pu
'green'
suits = ['hearts', 'clubs', 'diamonds', 'spades']
suits
['hearts', 'clubs', 'diamonds', 'spades']
random.shuffle(suits)
suits
['hearts', 'spades', 'clubs', 'diamonds']
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)
28, 496 y 8128
12, 18, 20, 24, 30
#Esta función permite comprobar si dos números positivos son amigos.
(9437056, 9363584)
#Usando la función anterior, comprobamos si un número natural n>1 es perfecto.
8128 es perfecto.
#Esta función nos indica si el número n>1 es deficiente, perfecto o abundante.
24 es abundante por 12 unidades