0% found this document useful (0 votes)
3 views7 pages

Assignment 3

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 7

Assignment3.

md 2024-10-20

Assignment 3
Question 1
def smallestFactor(n):
for i in range(2,n):
if(n%i==0):
return i

number = int(input("Please enter number"))


print(smallestFactor(number))

• The smallestFactor(n) function finds the smallest factor of a given


number n, starting from 2.
• It loops from 2 to n-1, checking if n is divisible by each number.
• Once it finds the first number that divides n evenly, it returns that
as the smallest factor.
• The user inputs a number, and the smallest factor is printed.

Please enter number: 15


3

Question 2
def highestCommonFactor(a,b):
if(a==0):
return b

return highestCommonFactor(b%a,a)

number1 = int(input("Please enter number"))


number2 = int(input("Please enter another number"))
print(highestCommonFactor(number1,number2))

• The highestCommonFactor(a, b) function finds the highest common factor


(HCF) of two numbers using the Euclidean algorithm.
• If a equals 0, it returns b as the HCF.
• Otherwise, it recursively calls the function with arguments b % a and
a until a becomes 0, at which point the value of b is the HCF.
• The user inputs two numbers, and the HCF of the two is printed.

1/7
Assignment3.md 2024-10-20

Please enter number: 54


Please enter another number: 24
6

Question 3
def power(base, exp):
result = 1
while exp > 0:
if exp % 2 == 1:
result *= base

base *= base
exp //= 2

return result

base = int(input("Enter the base: "))


exp = int(input("Enter the exponent: "))
print(power(base, exp))

• The power(base, exp) function computes the value of base raised to the
power of exp using exponentiation by squaring.
• It initializes result as 1 and iteratively squares the base while
halving the exp.
• If the exp is odd at any point, the current base is multiplied by the
result.
• The process continues until exp becomes 0, at which point the final
result is returned.

Enter the base: 2


Enter the exponent: 5
32

Question 4
def fibRecursion(n):
if(n==0):
return 0
if(n==1):
return 1

2/7
Assignment3.md 2024-10-20

return fibRecursion(n-1)+fibRecursion(n-2)

def fibTwo(n):
a = 0
b = 1
for i in range(2,n+1):
c = a+b
a = b
b = c
return b

Recursion:

• The fibRecursion(n) function computes the Fibonacci sequence using


recursion.
• Base Cases:
• If n == 0, it returns 0.
• If n == 1, it returns 1.
• For values of n > 1, the function recursively calls itself with n-1
and n-2, summing their results.
• This approach is straightforward but inefficient for large n due to
repeated calculations.

Iteration:

• The fibTwo(n) function calculates the Fibonacci sequence


iteratively.
• It initializes two variables a (the 0th Fibonacci number) and b
(the 1st Fibonacci number).
• Starting from i = 2, it calculates each Fibonacci number by summing
a and b, then updates a and b for the next iteration.
• This approach is much more efficient and runs in linear time.

Question 5
import matplotlib.pyplot as plt

def find_longest_monotone_substring(arr):
n = len(arr)
max_len = 1
start_idx = 0

curr_len = 1
curr_start = 0

for i in range(1, n):

3/7
Assignment3.md 2024-10-20

if arr[i] >= arr[i - 1]:


curr_len += 1
else:
if curr_len > max_len:
max_len = curr_len
start_idx = curr_start
curr_len = 1
curr_start = i

if curr_len > max_len:


max_len = curr_len
start_idx = curr_start

curr_len = 1
curr_start = 0

for i in range(1, n):


if arr[i] <= arr[i - 1]:
curr_len += 1
else:
if curr_len > max_len:
max_len = curr_len
start_idx = curr_start
curr_len = 1
curr_start = i

if curr_len > max_len:


max_len = curr_len
start_idx = curr_start

longest_substring = arr[start_idx:start_idx + max_len]


return longest_substring, start_idx

def plot_with_substring(arr, substring, start_idx):


plt.figure(figsize=(12, 7))

plt.plot(arr, label="Original Sequence", color='blue')

substring_indices = list(range(start_idx, start_idx + len(substring)))

plt.plot(substring_indices, substring, label="Longest Monotone


Substring", color='orange', linewidth=2)

plt.xlabel("Index")
plt.ylabel("Value")
plt.title("Longest Monotone Substring in a List")
plt.legend()
plt.grid(True)
plt.show()

4/7
Assignment3.md 2024-10-20

. To solve the problem of finding the longest monotone substring (as opposed to a subsequence) and
plotting it, we need to:
. Identify the longest contiguous segment of the list where the values are either non-increasing or non-
decreasing.
. Plot the original list.
. Plot the longest monotone substring on the same figure in a different color, aligning with the correct
indices.
. Finding Longest Monotone Substring:
find_longest_monotone_substring() function :
Input: List of integers arr.
Output: Longest monotone substring and its starting index.
Uses two passes to find both the longest increasing and longest decreasing contiguous substrings.
Tracks the length of the current substring and updates max_ len and start_idx when longer substring
is found.
Extracts the longest substring using the start_idx and max_len.
. Plotting the Original List and Substring:
plot_with_substring() function:
Input: Original list arr, substring, and start_idx.
Plots the original list using plt.plot().
Calculates the x-values for the substring to ensure it is plotted at the correct indices.
Plots the substring on the same graph with a different color (orange).
Adds labels, title, legend, and grid for better visualization.

# Example usage:
arr = [13, 2, 12, 10, 5, 6, 19, 2, 13, 17, 17, 2, 15, 2, 5, 6, 13, 3, 17,
3]
longest_substring, start_idx = find_longest_monotone_substring(arr)
print("Longest Monotone Substring:", longest_substring)
plot_with_substring(arr, longest_substring, start_idx)

5/7
Assignment3.md 2024-10-20

Question 6
def merge(arr1,arr2):
arr = []
i = 0
j = 0
while(i<len(arr1) and j<len(arr2)):
if(arr1[i]<arr2[j]):
arr.append(arr1[i])
i+=1
else:
arr.append(arr2[j])
j+=1
while(i<len(arr1)):
arr.append(arr1[i])
i+=1
while(j<len(arr2)):
arr.append(arr2[j])
j+=1
return arr

def mergeSort(arr):
if(len(arr)<=1):
return arr
mid = len(arr)//2
left = mergeSort(arr[:mid])
right = mergeSort(arr[mid:])
return merge(left,right)

6/7
Assignment3.md 2024-10-20

• The merge(arr1, arr2) function merges two sorted arrays (arr1 and
arr2) into a single sorted array.
• It uses two pointers i and j to traverse both arrays.
• If the current element in arr1 is smaller than the current element in
arr2, it appends that element to the result (arr) and increments i.
• Otherwise, it appends the element from arr2 and increments j.
• After one array is fully traversed, any remaining elements from the
other array are appended to the result.
• The mergeSort(arr) function sorts an unsorted array using the merge
sort algorithm.
• Base Case: If the array has 1 or fewer elements, it is already sorted,
so it returns the array.
• Otherwise, it divides the array into two halves:
• Recursively sorts both halves using mergeSort.
• Merges the two sorted halves using the merge function.

This process is repeated recursively until the entire array is sorted.

merge([1, 3, 5], [2, 4, 6]) = [1, 2, 3, 4, 5, 6]


mergeSort([4, 3, 5, 1, 2]) = [1, 2, 3, 4, 5]

7/7

You might also like