Function Program

Find the factorial of n number

Method 1: Using Reduce

The reduce() function accepts a function and a sequence and returns a single value calculated as follows:

  1. Initially, the function is called with the first two items from the sequence and the result is returned.

  2. The function is then called again with the result obtained in step 1 and the next value in the sequence. This process keeps repeating until there are items in the sequence.

The syntax of the reduce() function is as follows:

Syntax: reduce(function, sequence[, initial]) -> value


def factorial(n):

if (n == 0):

return 1

else:

return reduce( lambda x,y:x*y , range(1,n+1))\

print(factorial(n))

Method 2: Using Reduce

n = int(input())

fact = reduce(lambda x, y: x*y, range(1, n + 1)) if n>0 else 0 if n == 0 else 'factorial not possible'

print(fact)

Method 3: Using Recursion

def fact(x):

r=1;

if (x==0):

return 1

else:

return(x*fact(x-1))

print(fact(5))


Method 4: Using Recursion

def fact(n):

return 1 if (n==1 or n==0) else n * fact(n - 1);

n = 5;

print("Factorial of "+str(n)+" =",

fact(n))

find the sum of square series

# find the sum of square series

Method 1

def sumofSquare(N):

sum=0

for i in range(1,N):

sum=sum+i**2

return sum

N=int(input('Enter the range'))

print(sumofSquare(N))

Method 2

def sum_of_squares_lambda(n):

return reduce(lambda x, y: x**2 + y**2, range(1, n))

N=int(input('Enter the range'))

print(sum_of_squares(N))

Method 3

def sum_of_squares(n):

return sum(x ** 2 for x in range(1, n))

N=int(input('Enter the range'))

print(sum_of_squares(N))