PYTHON2
PYTHON2
Assignment – 2
Code:
print(‘Name:Subham patra’)
print(‘Regd. no.: 2241016294’)
result = power(3, 4)
print("3^4 =", result)
Output:
Name:Subham patra
Regd. no.: 22241016294
3^4 = 81
2. The greatest common divisor of integers x and y is the largest integer that evenly divides into both
x and y. Write and test a recursive function gcd that returns the greatest common divisor of x and
y. The gcd of x and y is defined recursively as follows: If y is equal to 0, then gcd(x, y) is x;
otherwise, gcd(x, y) is gcd(y, x%y).
Code:
print(‘Name:Subham patra’)
print(‘Regd. no.: 2241016294’)
Output:
Name:Subham patra
Regd. no.: 22241016294
3. Write a recursive function that takes a number n as an input parameter and prints n-digit strictly
increasing numbers.
Code:
print(‘Name:Subham patra’)
print(‘Regd. no.: 2241016294’)
n=3
print(f"{n}-digit strictly increasing numbers are:")
print_increasing_numbers(n)
Output:
Name:Subham patra
Regd. no.: 22241016294
.
.
.
.
468
469
478
479
489
567
568
569
578
579
589
678
679
689
789
4. Implement a recursive solution for computing the nth Fibonacci number. Then, analyze its time
complexity. Propose a more efficient solution and compare the two approaches.
Code:
print(‘Name:Subham patra’)
print(‘Regd. no.: 2241016294’)
def fibonacci(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fibonacci(n - 1) + fibonacci(n - 2)
n = 10
print(f"Fibonacci number at position {n} is {fibonacci(n)}")
Output:
Name:Subham patra
Regd. no.: 22241016294
5. Given an array of N elements, not necessarily in ascending order, devised an algorithm to find the
kth largest one. It should run in O(N) time on random inputs.
Code:
print(‘Name:Subham patra’)
print(‘Regd. no.: 2241016294’)
import random
Output:
Name:Subham patra
Regd. no.: 22241016294
6. For each of the following code snippets, determine the time complexity in terms of Big O. Explain
your answer.
Answer:
(a) Outer loop (line 2): The loop runs from i = 0 to i = n - 1, so it iterates n times.
Inner loop (line 3): For each iteration of the outer loop, the inner loop runs from j = 0 to j = n - 1, so it
also iterates n times.
Thus, for every iteration of the outer loop, the inner loop runs n times. Therefore, the total number of
iterations is n×n=n2n×n=n2. Each iteration involves a constant time operation (print(i, j)), so the overall
time complexity is O(n2)O(n2).
(b) Loop (line 1): The loop runs from i = 0 to i = n - 1, so it iterates n times.
Print statement (line 2): The print statement inside the loop is executed once for each iteration.
Thus, the total number of operations is nn, and since the print operation is constant time, the overall time
complexity is O(n)O(n).
(c) Base case (line 2): If n≤1n≤1, the function returns 1, which takes constant time O(1)O(1).
Recursive case (line 4): The function calls itself twice with the argument n - 1.
At each level of recursion, the function makes two recursive calls, which means the number of calls
grows exponentially. The depth of the recursion is O(n)O(n), and at each level, the number of calls
doubles. This leads to a total number of function calls of 2n2n.
7. Given N points on a circle, centered at the origin, design an algorithm that determines whether
there are two points that are antipodal, i.e., the line connecting the two points goes through the
origin. Your algorithm should run in time proportional to NlogN.
Code:
print(‘Name:Subham patra’)
print(‘Regd. no.: 2241016294’)
import bisect
import math
def has_antipodal_points(points):
angles = sorted([point[0] for point in points])
for angle in angles:
target_angle = (angle + math.pi) % (2 * math.pi)
idx = bisect.bisect_left(angles, target_angle)
if idx < len(angles) and angles[idx] == target_angle:
return True
return False
Output:-
Name:Subham patra
Regd. no.: 22241016294
False
8. The quicksort algorithm is a recursive sorting technique that follows these steps:
(i) Partition Step: Choose the first element of the array as the pivot and determine its final
position in the sorted array by ensuring all elements to its left are smaller and all elements
to its right are larger.
(ii) Recursive Step: Recursively repeat the partitioning process on the subarrays created on
either side of the pivot. As an example, consider the array [37, 2, 6, 4, 89, 8, 10, 12, 68, 45]
with 37 as the pivot. Using the partitioning logic, the pivot eventually moves to its correct
position, resulting in two subarrays: [12, 2, 6, 4, 10, 8] and [89, 68, 45]. The algorithm
continues recursively until the entire array is sorted. Write a Python function quick sort
that implements the quicksort algorithm. The function should include a helper function
quick sort helper to handle recursion. The helper function must take a starting and ending
index as arguments and sort the array in-place. Demonstrate the function by sorting the
given array and printing the sorted output.
Code:
print(‘Name:Subham patra’)
print(‘Regd. no.: 2241016294’)
def quick_sort(arr):
def quick_sort_helper(arr, low, high):
if low < high:
pivot_index = partition(arr, low, high)
quick_sort_helper(arr, low, pivot_index - 1)
quick_sort_helper(arr, pivot_index + 1, high)
while True:
while left <= right and arr[left] <= pivot:
left += 1
while left <= right and arr[right] >= pivot:
right -= 1
if left <= right:
arr[left], arr[right] = arr[right], arr[left]
else:
break
quick_sort_helper(arr, 0, len(arr) - 1)
Output:-
Name:Subham patra
Regd. no.: 22241016294
9. You are given the following list of famous personalities with their net worth:
• Elon Musk: $433.9 Billion
• Jeff Bezos: $239.4 Billion
• Mark Zuckerberg: $211.8 Billion
• Larry Ellison: $204.6 Billion
• Bernard Arnault & Family: $181.3 Billion
• Larry Page: $161.4 Billion
Develop a program to sort the aforementioned details on the basis of net worth using
a. Selection sort
b. Bubble sort
c. Insertion sort
The final sorted data should be the same for all cases. After you obtain the sorted data, present the
result in the form of the following dictionary: {’name1’:networth1, ’name2’:networth2,...}
Code:
print(‘Name:Subham patra’)
data = [
('Elon Musk', 433.9),
('Jeff Bezos', 239.4),
('Mark Zuckerberg', 211.8),
('Larry Ellison', 204.6),
('Bernard Arnault & Family', 181.3),
('Larry Page', 161.4)
]
def selection_sort(data):
for i in range(len(data)):
min_index = i
for j in range(i+1, len(data)):
if data[j][1] < data[min_index][1]:
min_index = j
data[i], data[min_index] = data[min_index], data[i]
return dict(data)
def bubble_sort(data):
n = len(data)
for i in range(n):
for j in range(0, n-i-1):
if data[j][1] > data[j+1][1]:
data[j], data[j+1] = data[j+1], data[j]
return dict(data)
def insertion_sort(data):
for i in range(1, len(data)):
key = data[i]
j=i-1
while j >= 0 and key[1] < data[j][1]:
data[j + 1] = data[j]
j -= 1
data[j + 1] = key
return dict(data)
sorted_data_selection = selection_sort(data.copy())
sorted_data_bubble = bubble_sort(data.copy())
sorted_data_insertion = insertion_sort(data.copy())
Output:-
Name:Subham patra
Regd. no.: 22241016294
Selection Sort: {'Larry Page': 161.4, 'Bernard Arnault & Family': 181.3, 'Larry Ellison': 204.6, 'Mark
Zuckerberg': 211.8, 'Jeff Bezos': 239.4, 'Elon Musk': 433.9}
Bubble Sort: {'Larry Page': 161.4, 'Bernard Arnault & Family': 181.3, 'Larry Ellison': 204.6, 'Mark
Zuckerberg': 211.8, 'Jeff Bezos': 239.4, 'Elon Musk': 433.9}
Insertion Sort: {'Larry Page': 161.4, 'Bernard Arnault & Family': 181.3, 'Larry Ellison': 204.6, 'Mark
Zuckerberg': 211.8, 'Jeff Bezos': 239.4, 'Elon Musk': 433.9}
def merge_sort(arr):
if len(arr) > 1:
mid = len(arr) // 2
left_half = arr[:mid]
right_half = arr[mid:]
merge_sort(left_half)
merge_sort(right_half)
i=j=k=0
arr[k] = right_half[j]
j += 1
k += 1
return arr
Output:-
Name:Subham patra
Regd. no.: 22241016294
11. Without using the built-in sorted() function, write a Python program to merge two pre-sorted
lists into a single sorted list using the logic of Merge Sort.
Example: Input: [1, 3, 5, 7] and [2, 4, 6, 8]
Output: [1, 2, 3, 4, 5, 6, 7, 8]
Code:
print(‘Name:Subham patra’)
print(‘Regd. no.: 2241016294’)
return merged_list
list1 = [1, 3, 5, 7]
list2 = [2, 4, 6, 8]
result = merge_sorted_lists(list1, list2)
print("Merged Sorted List:", result)
Output:
Name:Subham patra
Regd. no.: 2241016294