0% found this document useful (0 votes)
2 views47 pages

PYTHON2

The document outlines a series of programming assignments for a computer science course, focusing on recursive functions, algorithms, and sorting techniques. It includes code examples for calculating powers, finding GCD, generating increasing numbers, Fibonacci sequence, and sorting methods like quicksort and merge sort. Each section provides code snippets, expected outputs, and explanations of time complexity for various algorithms.

Uploaded by

starkramizsk
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views47 pages

PYTHON2

The document outlines a series of programming assignments for a computer science course, focusing on recursive functions, algorithms, and sorting techniques. It includes code examples for calculating powers, finding GCD, generating increasing numbers, Fibonacci sequence, and sorting methods like quicksort and merge sort. Each section provides code snippets, expected outputs, and explanations of time complexity for various algorithms.

Uploaded by

starkramizsk
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 47

Department of Computer Science & Engineering Faculty of

Engineering and Technology (ITER)

Assignment – 2

1. Write a recursive function power(base, exponent) that, when called, returns

Code:
print(‘Name:Subham patra’)
print(‘Regd. no.: 2241016294’)

def power(base, exponent):


if exponent == 1:
return base
else:
return base * power(base, exponent - 1)

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’)

def gcd(x, y):


if y == 0:
return x
else:
return gcd(y, x % y)

result = gcd(56, 98)


print("GCD of 56 and 98 is:", result)

Output:
Name:Subham patra
Regd. no.: 22241016294

Name: __________________________ Regd. no.:___________________


Department of Computer Science & Engineering Faculty of
Engineering and Technology (ITER)

GCD of 56 and 98 is: 14

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’)

def print_increasing_numbers(n, current_number='', last_digit=0):


if len(current_number) == n:
print(current_number)
return
for digit in range(last_digit + 1, 10):
print_increasing_numbers(n, current_number + str(digit), digit)

n=3
print(f"{n}-digit strictly increasing numbers are:")
print_increasing_numbers(n)

Output:
Name:Subham patra
Regd. no.: 22241016294

3-digit strictly increasing numbers are:


123
124
125
126
127
128
129
134
135
136
137
138
139
145
146
147
148
149
.
.

Name: __________________________ Regd. no.:___________________


Department of Computer Science & Engineering Faculty of
Engineering and Technology (ITER)

.
.
.
.
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

Fibonacci number at position 10 is 55

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:

Name: __________________________ Regd. no.:___________________


Department of Computer Science & Engineering Faculty of
Engineering and Technology (ITER)

print(‘Name:Subham patra’)
print(‘Regd. no.: 2241016294’)

import random

def quickselect(arr, low, high, k):


if low == high:
return arr[low]
pivot_index = random.randint(low, high)
pivot_index = partition(arr, low, high, pivot_index)
if k == pivot_index:
return arr[k]
elif k < pivot_index:
return quickselect(arr, low, pivot_index - 1, k)
else:
return quickselect(arr, pivot_index + 1, high, k)

def partition(arr, low, high, pivot_index):


pivot_value = arr[pivot_index]
arr[pivot_index], arr[high] = arr[high], arr[pivot_index]
store_index = low
for i in range(low, high):
if arr[i] > pivot_value:
arr[store_index], arr[i] = arr[i], arr[store_index]
store_index += 1
arr[store_index], arr[high] = arr[high], arr[store_index]
return store_index

def find_kth_largest(arr, k):


n = len(arr)
return quickselect(arr, 0, n - 1, k - 1)

arr = [7, 10, 4, 3, 20, 15]


k=3
print(f"The {k}-th largest element is {find_kth_largest(arr, k)}")

Output:
Name:Subham patra
Regd. no.: 22241016294

The 3-th largest element is 10

6. For each of the following code snippets, determine the time complexity in terms of Big O. Explain
your answer.

Name: __________________________ Regd. no.:___________________


Department of Computer Science & Engineering Faculty of
Engineering and Technology (ITER)

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.

Thus, the time complexity of this recursive function is O(2n)O(2n).


(a) O(n2)O(n2)
(b) O(n)O(n)
(c) O(2n)O(2n)

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’)

Name: __________________________ Regd. no.:___________________


Department of Computer Science & Engineering Faculty of
Engineering and Technology (ITER)

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

points = [(0, 0), (1, math.pi/2), (2, math.pi), (3, 3*math.pi/2)]


print(has_antipodal_points(points))

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)

Name: __________________________ Regd. no.:___________________


Department of Computer Science & Engineering Faculty of
Engineering and Technology (ITER)

def partition(arr, low, high):


pivot = arr[low]
left = low + 1
right = 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

arr[low], arr[right] = arr[right], arr[low]


return right

quick_sort_helper(arr, 0, len(arr) - 1)

arr = [37, 2, 6, 4, 89, 8, 10, 12, 68, 45]


quick_sort(arr)
print("Sorted Array:", arr)

Output:-
Name:Subham patra
Regd. no.: 22241016294

Sorted Array: [2, 4, 6, 8, 10, 12, 37, 45, 68, 89]

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’)

Name: __________________________ Regd. no.:___________________


Department of Computer Science & Engineering Faculty of
Engineering and Technology (ITER)

print(‘Regd. no.: 2241016294’)

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())

print("Selection Sort:", sorted_data_selection)


print("Bubble Sort:", sorted_data_bubble)
print("Insertion Sort:", sorted_data_insertion)

Name: __________________________ Regd. no.:___________________


Department of Computer Science & Engineering Faculty of
Engineering and Technology (ITER)

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}

10. Use Merge Sort to sort a list of strings alphabetically.


Example: Input: [’apple’, ’orange’, ’banana’, ’grape’]
Output: [’apple’, ’banana’, ’grape’, ’orange’]
Code:
print(‘Name:Subham patra’)
print(‘Regd. no.: 2241016294’)

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

while i < len(left_half) and j < len(right_half):


if left_half[i] < right_half[j]:
arr[k] = left_half[i]
i += 1
else:
arr[k] = right_half[j]
j += 1
k += 1

while i < len(left_half):


arr[k] = left_half[i]
i += 1
k += 1

while j < len(right_half):

Name: __________________________ Regd. no.:___________________


Department of Computer Science & Engineering Faculty of
Engineering and Technology (ITER)

arr[k] = right_half[j]
j += 1
k += 1

return arr

input_list = ['apple', 'orange', 'banana', 'grape']


output_list = merge_sort(input_list)
print(output_list)

Output:-
Name:Subham patra
Regd. no.: 22241016294

['apple', 'banana', 'grape', 'orange']

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’)

def merge_sorted_lists(list1, list2):


merged_list = []
i, j = 0, 0

while i < len(list1) and j < len(list2):


if list1[i] < list2[j]:
merged_list.append(list1[i])
i += 1
else:
merged_list.append(list2[j])
j += 1

while i < len(list1):


merged_list.append(list1[i])
i += 1

while j < len(list2):


merged_list.append(list2[j])
j += 1

return merged_list

Name: __________________________ Regd. no.:___________________


Department of Computer Science & Engineering Faculty of
Engineering and Technology (ITER)

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

Merged Sorted List: [1, 2, 3, 4, 5, 6, 7, 8]

Name: __________________________ Regd. no.:___________________


Department of Computer Science & Engineering Faculty of
Engineering and Technology (ITER)

Name: __________________________ Regd. no.:___________________


Department of Computer Science & Engineering Faculty of
Engineering and Technology (ITER)

Name: __________________________ Regd. no.:___________________


Department of Computer Science & Engineering Faculty of
Engineering and Technology (ITER)

Name: __________________________ Regd. no.:___________________


Department of Computer Science & Engineering Faculty of
Engineering and Technology (ITER)

Name: __________________________ Regd. no.:___________________


Department of Computer Science & Engineering Faculty of
Engineering and Technology (ITER)

Name: __________________________ Regd. no.:___________________


Department of Computer Science & Engineering Faculty of
Engineering and Technology (ITER)

Name: __________________________ Regd. no.:___________________


Department of Computer Science & Engineering Faculty of
Engineering and Technology (ITER)

Name: __________________________ Regd. no.:___________________


Department of Computer Science & Engineering Faculty of
Engineering and Technology (ITER)

Name: __________________________ Regd. no.:___________________


Department of Computer Science & Engineering Faculty of
Engineering and Technology (ITER)

Name: __________________________ Regd. no.:___________________


Department of Computer Science & Engineering Faculty of
Engineering and Technology (ITER)

Name: __________________________ Regd. no.:___________________


Department of Computer Science & Engineering Faculty of
Engineering and Technology (ITER)

Name: __________________________ Regd. no.:___________________


Department of Computer Science & Engineering Faculty of
Engineering and Technology (ITER)

Name: __________________________ Regd. no.:___________________


Department of Computer Science & Engineering Faculty of
Engineering and Technology (ITER)

Name: __________________________ Regd. no.:___________________


Department of Computer Science & Engineering Faculty of
Engineering and Technology (ITER)

Name: __________________________ Regd. no.:___________________


Department of Computer Science & Engineering Faculty of
Engineering and Technology (ITER)

Name: __________________________ Regd. no.:___________________


Department of Computer Science & Engineering Faculty of
Engineering and Technology (ITER)

Name: __________________________ Regd. no.:___________________


Department of Computer Science & Engineering Faculty of
Engineering and Technology (ITER)

Name: __________________________ Regd. no.:___________________


Department of Computer Science & Engineering Faculty of
Engineering and Technology (ITER)

Name: __________________________ Regd. no.:___________________


Department of Computer Science & Engineering Faculty of
Engineering and Technology (ITER)

Name: __________________________ Regd. no.:___________________


Department of Computer Science & Engineering Faculty of
Engineering and Technology (ITER)

Name: __________________________ Regd. no.:___________________


Department of Computer Science & Engineering Faculty of
Engineering and Technology (ITER)

Name: __________________________ Regd. no.:___________________


Department of Computer Science & Engineering Faculty of
Engineering and Technology (ITER)

Name: __________________________ Regd. no.:___________________


Department of Computer Science & Engineering Faculty of
Engineering and Technology (ITER)

Name: __________________________ Regd. no.:___________________


Department of Computer Science & Engineering Faculty of
Engineering and Technology (ITER)

Name: __________________________ Regd. no.:___________________


Department of Computer Science & Engineering Faculty of
Engineering and Technology (ITER)

Name: __________________________ Regd. no.:___________________


Department of Computer Science & Engineering Faculty of
Engineering and Technology (ITER)

Name: __________________________ Regd. no.:___________________


Department of Computer Science & Engineering Faculty of
Engineering and Technology (ITER)

Name: __________________________ Regd. no.:___________________


Department of Computer Science & Engineering Faculty of
Engineering and Technology (ITER)

Name: __________________________ Regd. no.:___________________


Department of Computer Science & Engineering Faculty of
Engineering and Technology (ITER)

Name: __________________________ Regd. no.:___________________


Department of Computer Science & Engineering Faculty of
Engineering and Technology (ITER)

Name: __________________________ Regd. no.:___________________


Department of Computer Science & Engineering Faculty of
Engineering and Technology (ITER)

Name: __________________________ Regd. no.:___________________


Department of Computer Science & Engineering Faculty of
Engineering and Technology (ITER)

Name: __________________________ Regd. no.:___________________


Department of Computer Science & Engineering Faculty of
Engineering and Technology (ITER)

Name: __________________________ Regd. no.:___________________


Department of Computer Science & Engineering Faculty of
Engineering and Technology (ITER)

Name: __________________________ Regd. no.:___________________


Department of Computer Science & Engineering Faculty of
Engineering and Technology (ITER)

Name: __________________________ Regd. no.:___________________


Department of Computer Science & Engineering Faculty of
Engineering and Technology (ITER)

Name: __________________________ Regd. no.:___________________

You might also like