Job Saarnee

JOB SAARNEE

Top Most Platform for Job Updates O Level Results Answer keys AKTU MCQs

2 marks Important Question of Python Programming of Unit 5

Unit 5 

2 marks Important Question of Python Programming  

Q1 Explain
the use of “with” construct in python with an example program. [2020-2021]

Solution: In Python, the with statement is used to wrap
the execution of a block of code with methods defined by a context manager. It
simplifies the management of resources like files, sockets, and database connections by taking care of closing the resource after the code execution is
completed, even if an error occurs.

The general syntax of the with statement is as follows:

with context_manager_expression [as variable]:
    with-block

Here, context_manager_expression is an
expression that returns a context manager object, which is an object with the
__enter__() and __exit__() methods defined. The as variable part is optional
and can be used to bind the context manager object to a variable name.

Let’s take an example to understand how to use
the with construct in Python. Suppose we have a file called
“example.txt” containing some text that we want to read:

with open(“example.txt”,
“r”) as f:

    text
= f.read()

   
print(text)

In this example, we are using the open()
function to open the “example.txt” file in read mode. We are then
using the with statement to automatically close the file when the block of code
inside the with statement is executed. The contents of the file are read into
the text variable and printed to the console.

Without the with statement, we would have to
manually close the file using the close() method after reading its contents:

f = open(“example.txt”,
“r”)

text = f.read()
print(text)
f.close()

The with statement makes it easier to manage
resources by automatically closing them after use, even if an error occurs. It
is a best practice to always use the with statement when working with resources
that need to be cleaned up after use.

Q2 What
are properties of recursive functions?

Solution:

Recursive functions are functions that call themselves in order to solve a problem. The main properties of recursive functions are:

  • Base case: Recursive functions must have a base case or stopping condition, which is the condition that terminates the recursive calls. Without a base case, the function will keep calling itself indefinitely and cause a stack overflow.
  • Recursive case: Recursive functions must have a recursive case, which is the condition that calls the function again with a different set of arguments. The recursive case must eventually lead to the base case, or else the function will keep calling itself indefinitely.
  • Call stack: Recursive functions use a call stack to keep track of the function calls. Each time the function calls itself, a new stack frame is added to the call stack. When the base case is reached, the function returns its result and the call stack is unwound, with each stack frame being removed until the original function call is reached.
  • Time and space complexity: Recursive functions can have a high time and space complexity due to the use of the call stack. Each function call adds a new stack frame to the call stack, which takes up memory. In addition, recursive functions can lead to many repeated calculations, which can increase the time complexity.
  • Debugging: Debugging recursive functions can be challenging because of the nested function calls. It can be helpful to use print statements to track the function calls and the values of variables at each step.

It is important to use recursion judiciously and understand its properties in order to write efficient and bug-free code.

Q3 What are the advantages of
recursion?

Solution: 

Recursion is a powerful technique in programming that has several advantages, including:

  • Clarity and readability: Recursion can often make code more readable and easier to understand, especially when dealing with problems that have a recursive structure.
  • Simplification of code: Recursion can simplify code by reducing complex problems into smaller sub-problems that are easier to solve. This can make the code more modular and easier to maintain.
  • Elegance: Recursive solutions can be elegant and concise, allowing you to express complex algorithms in a few lines of code.
  • Flexibility: Recursion can be used in a variety of programming languages and can be applied to a wide range of problems. This makes it a versatile tool for programmers.
  • Tail recursion optimization: In some programming languages, tail recursion optimization can be applied to optimize tail-recursive functions, making them more efficient and reducing the risk of stack overflow.

While recursion has many advantages, it is important to use it judiciously and understand its limitations. Recursive functions can have a high time and space complexity, and it can be challenging to debug them. It is also important to ensure that the recursive function has a base case to avoid infinite loops.

Q4 What are the applications
of Tower of Hanoi problem?

Solution:

The Tower of Hanoi problem is a classic example of a problem that can be solved recursively. It is a mathematical puzzle that consists of three rods and a set of disks of different sizes, which can slide onto any rod. The goal of the puzzle is to move the entire stack to another rod, obeying the following simple rules:

  • Only one disk can be moved at a time.
  • Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack or on an empty rod.
  • No disk may be placed on top of a smaller disk.

The Tower of Hanoi problem has several practical applications, including:

  • Computer algorithms: The Tower of Hanoi problem is often used as an example in computer science courses to teach recursion and algorithm design.
  • Disk storage systems: The Tower of Hanoi problem is used as a model for disk storage systems, where data is stored on multiple disks and needs to be rearranged for optimization or backup purposes.
  • Robotics: The problem is used in robotics for designing and testing the movement of robotic arms that need to move objects from one place to another.
  • Education: The problem is used as a teaching aid for developing critical thinking skills and problem-solving strategies in students.
  • Psychology: The problem is used as a tool for studying human problem-solving behavior and cognitive processes.

Overall, the Tower of Hanoi problem is a simple but interesting puzzle that has practical applications in various fields. Its recursive solution also provides a good example of the power and elegance of recursive functions in programming.

Q5 Write algorithm of simple
linear search?

Solution

The linear search algorithm is a simple algorithm that searches for a specific value in a list or array by checking each element in order until the desired value is found. Here’s the algorithm:

1. Set a variable i to 0
2. Loop over each element in the list/array
   a. If the current element equals the desired value, return its index
   b. Otherwise, increment i by 1 and continue to the next element
3. If the desired value is not found in the list/array, return -1

Here’s the same algorithm written in Python:

def linear_search(lst, value):

    for i in range(len(lst)):

        if lst[i] == value:

            return i

    return -1

In this implementation, the linear_search function takes in a list lst and a value value to search for. It loops over each element in the list using the range function, and checks if the current element equals the desired value. If the value is found, it returns the index of the element. If the loop completes without finding the value, it returns -1.

Q6 Give the algorithm for
binary search?

Solution:

Binary search is an efficient algorithm for finding a specific element in a sorted list or array. The algorithm works by repeatedly dividing the search interval in half until the desired element is found. Here’s the algorithm:

1. Set a variable low to 0 and a variable high to the length of the list/array – 1
2. While low is less than or equal to high:
   a. Set a variable mid to the floor division of (low + high) / 2
   b. If the element at index mid equals the desired value, return mid
   c. If the element at index mid is greater than the desired value, set high to mid – 1
   d. Otherwise, set low to mid + 1
3. If the desired value is not found in the list/array, return -1

Here’s the same algorithm written in Python:

def binary_search(lst, value):
    low = 0
    high = len(lst) – 1
    while low <= high:
        mid = (low + high) // 2
        if lst[mid] == value:
            return mid
        elif lst[mid] > value:
            high = mid – 1
        else:
            low = mid + 1
    return -1

In this implementation, the binary_search function takes in a sorted list lst and a value value to search for. It sets the variables low and high to the beginning and end of the list, respectively. It then enters a while loop that continues as long as low is less than or equal to high. Within the loop, it calculates the middle index mid of the current search interval and compares the element at that index to the desired value. If the value is found, it returns the index of the element. If not, it adjusts the search interval by setting either low or high to mid + 1 or mid – 1, respectively. If the loop completes without finding the value, it returns -1.

Q7 Which method is used to sort a list?

or

List some sorting
algorithm? Also mention their complexity

Solution:

There are many methods that can be used to sort a list, and the best one to use depends on the specific requirements of your program. Here are a few common methods:

  1. Bubble Sort: This is a simple sorting algorithm that repeatedly steps through the list, compares adjacent elements and swaps them if they are in the wrong order. It has a time complexity of O(n^2), which makes it suitable for small lists, but not efficient for large ones.
  2. Selection Sort: This algorithm sorts the list by repeatedly finding the minimum element from the unsorted part of the list and moving it to the beginning. It has a time complexity of O(n^2) and is also suitable for small lists.
  3. Insertion Sort: This algorithm works by building up a sorted list, one item at a time. It scans each item and inserts it into its correct position in the sorted list. It has a time complexity of O(n^2) and is also suitable for small lists.
  4. Quick Sort: This is a fast and efficient sorting algorithm that uses a divide-and-conquer strategy to sort the list. It works by partitioning the list into two smaller sub-lists around a pivot element, and recursively sorting each sub-list. It has a time complexity of O(n log n) and is suitable for larger lists.
  5. Merge Sort: This is another divide-and-conquer sorting algorithm that works by recursively dividing the list into halves, sorting each half, and then merging the two sorted halves. It has a time complexity of O(n log n) and is also suitable for larger lists.
  6. Heap Sort: This algorithm uses a heap data structure to sort the list. It first converts the list into a binary heap, and then repeatedly removes the largest element and places it at the end of the list. It has a time complexity of O(n log n) and is suitable for larger lists.

These are just a few examples of sorting algorithms, and there are many more to choose from depending on your specific needs.

Leave a Comment

Your email address will not be published. Required fields are marked *

Shopping Cart

You cannot copy content of this page