Sortarea unei liste
lista = [10,34,11,8]
ok = 0
while ok==0:
ok =1
for i in range(0,len(lista)-1):
if(lista[i] > lista[i+1]):
aux = lista[i] # a,b = b,a
lista[i] = lista[i+1]
lista[i+1] = aux
ok = 0
print lista
Al n-lea element din sirul Fibonacci
n = 7
a = 1
b = 1
c = 0
for i in range(0,n-2):
c = a+b
a = b
b = c
if n==1 or n==2:
print 1
else:
print c
Definirea unei clase Multime, si a unor operatii: reuniune, intersectie, diferenta
class Multime:
def __init__ (self, lista):
self.n = 0
self.val = []
for i in range(0, len(lista)):
self.addEl(lista[i])
def contains (self, x):
for i in range(0,self.n):
if(self.val[i]==x):
return 1
return 0
def addEl (self, x):
if(self.contains(x)==0):
self.n += 1
self.val.append(x)
def reunion (self,l2):
nou = Multime(self.val)
for i in range(0,l2.n):
nou.addEl(l2.val[i])
return nou.val
def intersection(self,l2):
nou = Multime([])
for i in range(0, l2.n):
if(self.contains(l2.val[i])==1):
nou.addEl(l2.val[i])
return nou.val
def diferenta(self, l2):
nou = Multime([])
for i in range(0, self.n):
if(l2.contains(self.val[i])==0):
nou.addEl(self.val[i])
return nou.val
m1 = Multime([1,2,3])
m2 = Multime([3,4,5,6])
print "m1 U m2 = ",m1.reunion(m2)
print "m1 ^ m2 = ",m1.intersection(m2)
print "m1 \ m2 = ",m1.diferenta(m2)
Niciun comentariu:
Trimiteți un comentariu