Skip to content

Instantly share code, notes, and snippets.

@ivalexandru
Last active January 21, 2018 07:22
Show Gist options
  • Save ivalexandru/494afdb236d1d0c5ab86a892c77e976f to your computer and use it in GitHub Desktop.
Save ivalexandru/494afdb236d1d0c5ab86a892c77e976f to your computer and use it in GitHub Desktop.
#Decomposition is segmenting the code into smaller parts, for easier reading and maintenance
def numeFunctie():
return "Nu printez doar returnez"
rezultat = numeFunctie()
print(rezultat)
print(type(rezultat)) #e str
def functie2():
return 'lorin salam', 2
print(functie2())
print(type(functie2())) #e tupla
#acum pun si parametrii
def fun3(a,b):
c= a+b
return c
rezultatul = fun3(12,3)
print(rezultatul)
#poti avea valori default pt parametrii
#parametri cu valori default ar trebui pusi ultimii
def default_parameter(a, b=4, c=5):
return a+b+c
rezult2 = default_parameter(3) #a=3
print(rezult2)
#SCOPE is like the range of use of a parameter inside a function
#parametrii sunt valabili DOAR IN INTERIOR FUNCTIE
def scope2(a):
a +=1
print(a)
return a
print(scope2(5))
#can't call a outside the function
#print(a) #ar da eroare
#NESTED FUNCTIONS = functie intr-o functie
#a scope of a nested function is only within the parent function
#cu nested func tre sa folosesti ;
def outer_fun(a):
def nested_fun(b):
return b * a;
a = nested_fun(a)
return a
print(outer_fun(4)) #prints 16
def f(a):
def g(b):
def h(c):
return a*b*c
return h
return g
print(f(5)(2)(3)) #prints 30
#5 e pt outer function, f
#2 e pt nested function, g
#3 e pt nested function, h
#RECURSIVE functions
#break down a problem into subproblems
#it's a function calling itself, over and over again
#daca n nu este unu, va face else-ul de mai multe ori
#doar cand n =1 face return si iesi din functie, respectiv din 'loop'
def factorial(n):
if n == 1:
return 1 #pt a iesi din recursion
else:
return n * factorial(n-1) #am folosit aceeasi functie in functia respectiva => recursion
print(factorial(5)) #prints 120
# 5*4*3*2*1 = 120
#In mathematics, the factorial of a non-negative integer n, denoted by n!,
#is the product of all positive integers less than or equal to n. For example,
# 5! = 5 × 4 × 3 × 2 × 1 = 120.
#we have REGULAR and TAIL recursion
#REGULAR recursion:
def summ(n):
if n == 1:
return 1 #pt a iesi din recursion cand ajunge la 1
else:
return n + summ(n-1)
print(summ(10))
# 10+9+8+7+6+5+4+3+2+1 = 55
#TAIL recursion:
def tail_sum(n, accumulator = 0):
if n==0:
return accumulator
else:
return tail_sum(n-1, accumulator+n)
print(tail_sum(10)) #prints 55
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment