Function

What is a function?

Functions form the basis of procedural programming. 

What are the advantages of using functions in a program?
  • Modular Programming
    • When a program is divided into small parts then each part performs some specific task.we can write function for each task.

Reusability of Code
A function can be called many times in terms of Reusabiity.

Manageability
Dividing a bigger task into smaller functions makes the program manageable. It becomes easy to locate bugs and therefore make the program reliable. It also becomes easy to carry out local optimization in a function.

Easy Debugging
It becomes easy to effectively analyze smaller functions rather than the whole task.

Efficient
It is essential to make code efficient both in terms of time and memory.

What are the components of a function?

The keyword def introduces a function definition. It must be followed by the function name and the parenthesized list of formal parameters. The statements that form the body of the function start at the next line, and must be indented.

Name of a Function
A function can have any legal literal name. In a class we can have more than one function with the same name and different parameters.
This is known as overloading.

Arguments
The arguments of a function denote the input given to a function. A function can have any number of arguments.

Return Value
A function may or may not return a value.In Python a function can be made in the command prompt.

The definition of a function contains the following:

Name of a function: The name of a function is any valid identifier.

Parameter: The list of parameters (separated by commas) is given in the parentheses following the name of the function. The parameters are basically the input to the function. A function may have any parameters.

Body of the function: The body of the function contains the code that implements the task to be performed by the function.

def product(num1, num2):
   prod= num1*num2
   print('The product of the numbers is \t:'+str(prod))

num1=int(input('Enter the first number\t:'))
num2=int(input('Enter the second number\t:'))
product(num1, num2)

In this,Product function takes two arguments as input (num1 and num2) and displays the results.

IMPLEMENTING SEARCH

In the search ,if the element is present in a given list then its position should be displayed, otherwise a message “Not Found” should be displayed. Linear search and binary search are two solutions for search. In linear search, the elements are iterated one by one. If the required element is found, the position of the element is displayed.

Write a program to implement a linear search.

Solution:

def search(L, item):
    flag=0
    for i in L:
        if i==item:
            flag=1
            print('Position ',i)
    if flag==0:
        print('Not found')
L =[1, 2, 5, 9, 10]
search(L, 5)
search(L, 2)
Output

Position 5
Not found
>>>

In binary search, The algorithm checks whether the item to be searched is present at the first position, at the last position or at the middle position. If the requisite element is not present at any of these positions and it is less than the middle element, then the left part of the list becomes the input of the procedure; else the right part of the element becomes the input to the procedure.

The complexity of the binary search is O(logn).

What is recursion? Which data structure is used internally while implementing recursion?

When a function needs to be called within itself then it is referred as recursion. Many programming languages implement recursion by means of stacks. Generally, whenever a function (caller) calls another function (callee) or itself as callee, the caller function transfers execution control to the callee.

For example, consider the following series:

1, 1, 2, 3, 5, 8, 13, …
Note that each term is the sum of the previous two terms; the first and the second term being 1 and 1 respectively.
This series is referred to as the Fibonacci series.

The user to enter the value of n and find the nth Fibonacci term.

Solution:

def fib(n):
if n==1:
return 1
elif n==2:
return 1
else
return (fib(n-1) + fib(n-2))
n=input(‘Enter the number\t:’)
f=fib(n)
print(‘The nth fib term is ‘,str(f))
Output

Enter the number:5
The nth fib term is 5
The user to enter the value of n and calculate the factorial of n using recursion.

def fac(n):
   if n==1:
     return 1;
   else:
     return(n*fac(n-1))
n = int(input('Enter the number\t:'))
factorial = fac(n)
print('Factorial of ',n, ' is ', factorial)
Output

Enter the number 5
Factorial of 5 is 120
The user to enter the values of a and b and calculate a to the power of b, using recursion.


def power(a, b):
    if b==1:
    return a
    else:
   return (a*power(a, b-1))
a = int(input('Enter the first number\t:'))
b = int(input('Enter the second number\t:'))
p = power(a,b)
print(a, ' to the power of ',b,' is ', p)
Output

Enter the first number 3
Enter the second number 4
3 to the power of 4 is 81

What are the disadvantages of recursion?
  • Recursive functions are generally slower than non-recursive function.
  • It may require a lot of memory space to hold intermediate results on the system stacks.
  • Hard to analyze or understand the code.
  • It is not more efficient in terms of space and time complexity.
Objective Questions:

The values passed in a function are called

Ans: Arguments

A recursive function is one that calls

Ans: Itself

Which of the following should be present in a recursive function?

Ans: Initial values and Final values

Which of the following can be accomplished using recursion?

Binary search

Fibonacci series

Power

Which of the following control structures is allowed in a function?

If

Which types of functions are supported in Python?

Build in

User defined

Both

None of the above

Answer:(c)

Which of the following is true?

A function helps in dividing a program in small parts

A function can be called any number of times

Which of the following is true?

One can have a function that can be called any number of times

Nested functions incorporates the concept of

Stack

Queue

Linked List

None of the above

Answer:(d)

What would be output?
def fun1(n):
  if n==1:
     return 1
else:
    return (3*fun1(n-1)+2*fun1(n))
fun1(2)

Ans : maximum recursion depth exceeded in comparison

Which technique is implemented in the following code?

def search(L, item):
flag=0
for i in L:
if i==item:
flag=1
print(‘Position ‘,i)
if flag==0:
print(‘Not found’)
L =[1, 2, 5, 9, 10]
search(L, 5)
search(L, 3)
Linear search

Binary search

None of the above

The code does not execute

What is the complexity of the above?

O (n)

O (n2)

O (log n)

None of the above

Which is better – linear search or binary search?

Linear

Binary

Both are equally good

Depends on the input list.