print("Hello\nWorld!")
type('5668.413')
type(True)
int(1.0)
# Usar // irá dividir para um int
25 // 5
30 * (2 * 60)
indices = "O índice"
len(indices)
concat = " é top"
(3 * indices) + 2 * concat
print("Teste pular\nlinha")
print("Teste tab\tlinha")
print("Uma barra\\ no meio da String!")
upper = "upper case?"
upper.upper()
upper.replace("upper", "LOWER")
upper.find("?")
# Lists e Tuples
ratings = (1, 2, 3)
ratings[2]
new_tuple = (3, 5)
concat_tuple = ratings + new_tuple
concat_tuple[2:4]
sorted(ratings)
# Nesting (uma tuple dentro de uma tuple)
NT = (1, (2, 3), 4, 5, 6)
NT[1][0]
# Lists
l = ["Teste", 1, 1.2]
l[0:3]
l.extend([4, 5])
l.append(7)
l
l[0] = 156
del(l[0])
"Split;By;Delimiter".split(";")
# Copiar uma lista
A = [1,2,3,4,5]
B = A[:]
B
B=["a","b","c"]
B[1:]
B[2]
# Sets
set1 = {1, 2, 3, 4, 5, 5, 5, 6, 6, 6, 7}
set1
set(A)
set1.add(41)
set1.remove(2)
set1
# Usar o IN para verificar se há um item no set
121 in set1
set2 = {1,2,3,89,99}
set2.issubset(set2)
S={'A','B','C'}
U={'A','Z','C'}
S & U
S.union(U)
# Dictionaries
dict1 = {"Crisis": 1985, "Kingdom": 1996, "Identity": 2004}
"Crisis" in dict1
dict1.values()
a = 6
a == 6
age = 18
if (age > 18):
print("Menor de idade")
elif(age == 18):
print("Acabou de fazer 18")
else:
print("Maior de idade")
if (age > 18 and age <= 30 or age == 10):
print("Age is {}".format(str(age)))
elif (age <= 5):
print("Too young")
else:
print("I don't know anymore")
list = range(1, 10)
for i in (list):
print(str(i))
squares = ['red', 'yellow', 'green', 'purple', 'blue']
for i in range(len(squares)):
squares[i] = 'white'
print(squares)
for square in squares:
square = 'red'
print(square)
for i, square in enumerate(squares):
print("Index: {}, Square: {}".format(str(i), square))
newSquares = []
i = 0
while (i < len(squares) and squares[i] == 'white'):
newSquares.append(squares[i])
i += 1
newSquares
A=[3,4,5]
for a in A:
print(a)
# Funções
def calculate(a, b):
return a + b
calculate(1, 4)
lista = [1, 8, 7, 5, 3, 2, 4, 8, 19]
for i in range(len(lista)):
if (i < len(lista) - 1):
print(str(calculate(lista[i], lista[i + 1])))
sum(lista)
listaOrdenada = sorted(lista)
listaOrdenada
lista.sort()
lista
def ordenar(lista):
return sorted(lista)
novaLista = [8, 9, 5, 1, 3, 4, 6]
print(ordenar(novaLista))
def printNames(*names):
for name in names:
print(name)
printNames("Nome 1", "Nome 2", "Nome 3", "Nome 4")
type(1)
type(lista)
type(a)
class Circle(object):
def __init__(self, radius = 10, color = 'red'):
self.radius = radius
self.color = color
def addRadius(self, radius):
self.radius = self.radius + radius
def changeColor(self, color):
self.color = color
class Rectangle(object):
def __init__(self, color, height, width):
self.color = color
self.height = height
self.width = width
redCircle = Circle(10, 'red')
redCircle.color = "green"
redCircle.color
redCircle.addRadius(10)
redCircle.radius
redCircle.changeColor('Blue')
redCircle.color
dir(redCircle)
newCircle = Circle(radius = 20, color = 'red')
newCircle.color
file1 = open("dados/example1.txt", "w")
file1.name
file1.mode
print(file1.closed)
file1.write("File 1\nFile 2\nFile 3")
with open("dados/example1.txt", "r") as file1:
stuff = file1.read()
print(file1.closed)
print(stuff)
stuff
with open("dados/example1.txt", "r") as file1:
stuff = file1.readlines()
print(file1.closed)
print(stuff)
stuff
with open("dados/example1.txt", "r") as file1:
stuff = file1.readlines(14)
print(stuff)
with open("dados/example2.txt", "w") as file2:
file2.write("New file using With Open")
file2.closed
lines = ["Linha 1\n", "Linha 2\n", "Linha 3\n", "Linha 4\n"]
with open("dados/example3.txt", "w") as file3:
for line in lines:
file3.write(line)
with open("dados/example3.txt", "r") as wfile3:
writtenFile = wfile3.readlines()
writtenFile
# Copiando os dados de um arquivo existente para outro arquivo, criando um example5.txt e copiando os dados de example4.txt
with open("dados/example3.txt", "r") as file3:
with open("dados/example4.txt", "w") as file4:
for line in file3:
file4.write(line)
# Comparando os arquivos copiados
file3Str = ""
file4Str = ""
with open("dados/example3.txt", "r") as file3:
file3Str = file3.readlines()
with open("dados/example4.txt", "r") as file4:
file4Str = file4.readlines()
if (file3Str == file4Str):
print("File3 and File4 are equals")
else:
print("File3 and File4 are different")
import pandas as pd
# Gerar um arquivo CSV para estudo
with open("dados/csv_data.csv", "w") as csvFile:
csvFile.write("Id;Description;Data\n")
csvFile.write("1;Car;206\n")
csvFile.write("2;Bus;1511\n")
csvFile.write("3;Bike;13\n")
csvFile.write("4;Motorcycle;895\n")
csvFile.write("5;Truck;332\n")
csvFile.write("6;Plane;60\n")
df = pd.read_csv("dados/csv_data.csv", delimiter = ";")
df.head()
# Criando um dataframe
dictionary = {
'Id': [1, 2, 3, 4, 5],
'Description': ['Car', 'Bus', 'Bike', 'Motorcycle', 'Truck'],
'Data': [206, 1511, 13, 895, 332]
}
df2 = pd.DataFrame(dictionary)
df2.head()
# Particionar partes de um DataFrame em outro
df3 = pd.DataFrame(df2[['Id', 'Description']])
df3.head()
item = df3.iloc[0, 1]
item
df4 = pd.DataFrame({
'years': [1998, 1998, 1997, 1982, 2005, 2004, 2005, 2005, 2004, 2001]
})
# Dados distintos, sem duplicatas
df4["years"].unique()
# Filtrando o DataFrame apenas pelos anos maiores que 2000
df4[df4["years"] > 2000]
df3.to_csv("dados/data_frame.csv")
df5 = pd.DataFrame({'a':[1,2,1],'b':[1,1,1]})
df5['a'] == 1
import numpy as np
# Arrays 1D - 1 Dimensão
a = np.array([1, 2, 3, 4, 5])
type(nparray)
a.size
a.ndim
a.shape
a.dtype
f = np.array([1.5, 1.2, 5.3, 12.0, 14.1])
f.dtype
f[0:2]
f[0:2] = 85.4, 12.3
f[0:2]
# Soma de dois vetores sem numpy
u = [0, 1]
v = [1, 0]
z = []
for i, j in zip(u, v):
z.append(i + j)
print(z)
# Soma de dois vetores com numpy
u = np.array([0, 1])
v = np.array([1, 0])
z = np.array(u + v)
z
y = np.array([1, 2])
z = 2 * y
z
z = np.dot(u, v)
z
z = u + 1
z
z.mean()
z.max()
z.min()
z.std()
np.linspace(-5, 5, num = 5)
np.linspace(-5, 5, num = 100)
np.sin(u)
import matplotlib.pyplot as plt
%matplotlib inline
x = np.linspace(-10, 10, 100)
y = np.sin(x)
plt.gcf().set_size_inches(16, 8)
plt.plot(x, y)
# Arrays 2D - 2 Dimensões (Matrizes)
a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
n = a.ndim
n
a.shape
a.size
a[0, 0:3]
a[2, 2:4]
a[1, 0]
m1 = np.array([[0, 1, 2], [3, 4, 5]])
m2 = np.array([[4, 3, 5], [2, 0, 1]])
mr = m1 + m2
mr
mr2 = m1 * m2
mr2
mr3 = 2 * m1
mr3
# Multiplicação matricial
m1 = np.array([[1, 2, 3], [4, 5, 6]])
m2 = np.array([[1, 2], [3, 4], [5, 6]])
mr = np.dot(m1, m2)
mr
int(3.2)
A='1234567'
A[1::2]
Name="Michael Jackson"
Name.find('el')
A='1'
B='2'
A+B
'1,2,3,4'.split(',')
A=[1,'a']
B=[2,1,'d']
A+B
V={'A','B'}
V.add('C')
V
V={'A','B','C'}
V.add('C')
V
A=['1','2','3']
for a in A:
print(2*a)
def Add(x,y):
z=y+x
return(y)
Add('1', '1')