Skip to main content

[Python] Important Algorithms

Factorial function

def factorial(n):   #Task 1: Factorial function 
    if n==0:    #Case 1: 0!
        return 1
    
    else:   #Case 2: <positive_integer>!
        return n*factorial(n-1) #multiply with factorial of n-1

 

Recursive arithmetic sum 

def arithmetic_sum_2(term1,com_dif,n):   #Task 2(alternative): Arithmetic Sum Function – Recursive method
    if n==1:    #Case 1: last term to add(=the first term of the sequence)
        return term1
    else:   #Case 2: add <positive integer>th term
        return arithmetic_sum_2(term1,com_dif,(n-1))+(n-1)*com_dif+term1

 

Iterative arithmetic sum

def arithmetic_sum_1(term1,com_dif,n):   #Task 2: Arithmetic Sum function – Formula method
    return (n/2)*(2*term1+(n-1)*com_dif)

 

Recursive arithmetic sum

def geometric_sum_2(term1,com_rat,n):   #Task 3: Geometric Sum function – Recursive method
    if n==1:    #Case 1: last term to add(=the first term of the sequence)
        return float(term1)
    else:   #Case 2: add <positive integer>th term
        return float(geometric_sum_2(term1,com_rat,(n-1))+term1*(com_rat**(n-1)))  #perform nth term addition