Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
"""
Sempre que default args (l e d neste caso) são mutáveis,
vivem de chamada para chamada
"""
def f(l=[]):
l.append(4)
return l
print f([1,2,3])
print f([1,2,3])
print f()
print f()
def k(chave, d={}):
d[chave] = 1
return d
print k("ola")
print k("adeus")
import math
class Circle:
"""represent circles"""
def __init__(self, c, r):
"""Receives a Point2D c which is the center,
and a float r which is the radius"""
self.c = c
self.r = r
def area(self):
"""Returns the area of self"""
return math.pi * self.r**2
def perimeter(self):
"""Returns the perimeter of self"""
return 2 * math.pi * self.r
def changeArea(self, factor):
"""Changes the area of self by a factor given by factor.
For example:
factor = 1.4 increases the area by 40%
factor = 0.5 reduces the area to half"""
self.r = math.sqrt(factor * self.r**2 )
"""
area = pi * r**2
areaNova
-------- = 0.5
areaAntiga
rN**2
---------- == 0.5
rA**2
rN**2 = 0.5 * rA**2
rN = sqrt(0.5 * rA**2)
"""
class Frac:
def __init__(self, num, den):
""" Constroi um objecto Frac com num como numerador e den como denominador """
self.num = num
self.den = den
def getNum(self):
""" Devolve o numerador """
return self.num
def getDen(self):
""" Devolve o denominador """
return self.den
def __str__(self):
return "{0} / {1}".format(self.num, self.den)
def gcd_alternativo(self, a, b):
sol = 1
i = 1
while i <= a and i <= b:
if a % i == 0 and b % i == 0:
sol = i
i+=1
return sol
def gcd_alternativo2(self, a, b):
for i in range(min(a,b), 1, -1):
if a % i == 0 and b % i == 0:
return i
def gcd(self, a, b):
m = min(a,b)
sol = 1
for i in range(2,m+1):
if a % i == 0 and b % i == 0:
sol = i
return sol
def simplify(self):
d = self.gcd( self.num, self.den)
return Frac( self.num / d , self.den / d )
def add(self, f2):
""" Adiciona a fraccao actual com a fraccao f2 """
"""
# Desnecessario este if, mas aumenta a performance se na maior parte dos casos
# os denominadores forem iguais
if self.getDen() == f2.getDen():
return Frac(self.getNum() + f2.getNum(), self.getDen())
"""
n_num = f2.getDen() * self.getNum() + self.getDen() * f2.getNum()
n_den = self.getDen() * f2.getDen()
n_f = Frac(n_num, n_den)
return n_f.simplify()
def multiply(self, f2):
n_num = self.getNum() * f2.getNum()
n_den = self.getDen() * f2.getDen()
n_f = Frac(n_num, n_den)
return n_f.simplify()
def __eq__(self, f2):
return self.num * f2.getDen() == f2.getNum() * self.den
""" Alternativamente """
f1_ = self.simplify()
f2_ = self.simplify()
return f1_.getNum() == f2_.getNum() and f1_.getDen() == f2_.getDen()
def __lt__(self, f2):
""" Returns whether or not self is lower than f2 """
pass
# TODO: TRABALHO DE CASA
def __float__(self):
""" Converts self to a float """
return float(self.den) / float(self.num)
def __add__(self, p2):
""" Returns self + p2 """
return self.add(p2)
def __mul__(self, p2):
""" Returns self * p2 """
return self.multiply(p2)
""" Simplify """
f = Frac(4,2)
#print f.gcd(32, 24)
#print f.gcd_alternativo(32, 24)
#print f.gcd_alternativo2(32, 24)
#print f.simplify()
""" Operations """
#print Frac(1,3).add(Frac(1,2))
#print Frac(1,3).multiply(Frac(1,2))
#print Frac(2,3).multiply(Frac(3,2))
""" Magic Methods """
#print Frac(2,3) == Frac(4,6)
#print Frac(2,3).__eq__(Frac(4,6))
#print Frac(2,4) == Frac(4,6)
#print float(Frac(2,4))
#print Frac(2,4).__float__()
#print 2/4
#print Frac(1,3).add(Frac(1,2))
#print Frac(1,3) + Frac(1,2)
print Frac(2,3) * Frac(3,2)
print Frac(2,3).multiply(Frac(3,2))
"""
TPC:
print Frac(2,3) < Frac(1,3) # False
print Frac(1,3) < Frac(2,3) # True
"""
class IntSet(object):
"""An intSet is a set of integers"""
#Information about the implementation (not the abstraction)
#The value of the set is represented by a list of ints, self.vals.
#Each int in the set occurs in self.vals exactly once.
def __init__(self, lista=None):
"""Create an empty set of integers"""
self.vals = []
if lista:
for i in lista:
if i not in self.vals:
self.vals.append(i)
def insert(self, e):
"""Assumes e is an integer and inserts e into self"""
if not e in self.vals:
self.vals.append(e)
def member(self, e):
"""Assumes e is an integer
Returns True if e is in self, and False otherwise"""
return e in self.vals
def remove(self, e):
"""Assumes e is an integer and removes e from self
Raises ValueError if e is not in self"""
try:
self.vals.remove(e)
except:
raise ValueError(str(e) + ' not found')
def getMembers(self):
"""Returns a list containing the elements of self.
Nothing can be assumed about the order of the elements"""
return self.vals[:]
def __str__(self):
"""Returns a string representation of self"""
self.vals.sort()
result = ''
for e in self.vals:
result = result + str(e) + ','
return '{' + result[:-1] + '}' #-1 omits trailing comma
def isEmpty(self):
return self.vals == []
def size(self):
return len(self.vals)
def subset(self, other):
v = True
for element in self.vals:
if element not in other:
v = False
return v
# TODO
i = IntSet()
import math # for the distance methods
class Point2D:
"""represent points in 2D space"""
def __init__(self, x = 0.0, y = 0.0):
"""Assume x,y are ints or floats"""
self.x = float(x)
self.y = float(y)
def getX(self):
return self.x
def getY(self):
return self.y
def setX(self, newX):
self.x = float(newX)
def setY(self, newY):
self.y = float(newY)
def distanceOrigin(self):
return math.sqrt( self.x**2 + self.y**2 )
def distance(self, p):
return math.sqrt( (self.x-p.x)**2 + (self.y-p.y)**2 )
def __str__(self):
return "Point({}, {})".format(self.x, self.y)
#from point2d import Point2D
#from rectangle import Rectangle
#from triangle import Triangle
#r = Rectangle(Point2D(1,1), Point2D(3,1), Point2D(3,3))
#print r.isSquare(0.0001)
#t = Triangle(Point2D(1,1), Point2D(1,3), Point2D(4,1))
#print t.perimeter(), t.area(), t.isEquilateral(0.0001)
class Mut:
def __init__(self, v=0):
self.contador = v
def metodo(self):
self.contador += 1
class Imut:
def __init__(self, v=0):
self.contador = v
def metodo(self):
novo_contador = self.contador + 1
return Imut(novo_contador)
m = Mut()
m.metodo()
print m.contador
i = Imut()
j = i.metodo()
print j.contador
import math
class Triangle:
"""represent triangles"""
def __init__(self, p1, p2, p3):
"""
Receives the three triangle's vertices
"""
self.p1 = p1
self.p2 = p2
self.p3 = p3
def perimeter(self):
"""Returns the perimeter of self""" # codigo a completar pelos alunos
return self.p1.distance(self.p2) + \
self.p2.distance(self.p3) + \
self.p3.distance(self.p1)
def area(self):
"""Returns the area of self"""
d1 = self.p1.distance(self.p2)
d2 = self.p2.distance(self.p3)
d3 = self.p3.distance(self.p1)
s = self.perimeter()/2.0
return math.sqrt(s * (s-d1) * (s-d2) * (s-d3))
def isEquilateral(self, delta):
"""Assumes delta is a positive float
Returns True if self is equilateral, False otherwise
To avoid comparing floats for strict equality, comparisons are made "within delta" """
d1 = self.p1.distance(self.p2)
d2 = self.p2.distance(self.p3)
d3 = self.p3.distance(self.p1)
return abs(d1 - d2) < delta and abs(d3 - d2) < delta
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment