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

Python Algorithms and Data Structures

The document contains multiple Python code examples demonstrating various algorithms and data structures. Key topics include prime factorization, power of two checks, longest subarray with a given sum, trailing zeros in factorials, stack implementation, largest rectangle area in a histogram, generating subsets, finding the k-th smallest and largest elements, peak element finding, minimum platform calculation for train schedules, and counting ways to make change with coins. Each example includes input handling and output statements for demonstration.

Uploaded by

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

Python Algorithms and Data Structures

The document contains multiple Python code examples demonstrating various algorithms and data structures. Key topics include prime factorization, power of two checks, longest subarray with a given sum, trailing zeros in factorials, stack implementation, largest rectangle area in a histogram, generating subsets, finding the k-th smallest and largest elements, peak element finding, minimum platform calculation for train schedules, and counting ways to make change with coins. Each example includes input handling and output statements for demonstration.

Uploaded by

harshithsai2410
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Exp 1

def is_prime(n):
if n <= 1:
return False
if n == 2:
return True
if n % 2 == 0:
return False
for i in range(3, int(n**0.5) + 1, 2):
if n % i == 0:
return False
return True

def largest_prime_factor(n):
if is_prime(n):
return n
i=2
max_prime = -1
while i * i < n:
while n % i == 0:
max_prime = i
n //= i
i += 1
if n > 1:
max_prime = n
return max_prime

Exp 2

def is_power_of_two(n):
if n <= 0:
return False
return (n & (n-1)) == 0

number = 32
if is_power_of_two(number):
print(f"{number} is a power of two")
else:
print(f"{number} is not a power of two")

Exp 3
def longest_subarray_with_sum(arr, k):
prefix_sum = 0
prefix_map = {}
max_length = 0

for i, num in enumerate(arr):


prefix_sum += num
if prefix_sum == k:
max_length = i + 1
if (prefix_sum - k) in prefix_map:
max_length = max(max_length, i - prefix_map[prefix_sum - k])
if prefix_sum not in prefix_map:
prefix_map[prefix_sum] = i
return max_length

n = int(input("Enter array length: "))


arr = []
for i in range(n):
element = int(input())
[Link](element)
k = int(input("Enter target sum: "))

result = longest_subarray_with_sum(arr, k)
print("Longest subarray with sum", k, "is", result)

Exp 4

def count_trailing_zeros(n):
count = 0
i=5
while n // i >= 1:
count += n // i
i *= 5
return count

n1 = 5
print(f"case 1: zeros in {n1}: {count_trailing_zeros(n1)}")
n2 = 100
print(f"case 2: zeros in {n2}: {count_trailing_zeros(n2)}")
n3 = 1000
print(f"case 3: zeros in {n3}: {count_trailing_zeros(n3)}")
Exp 5

class stack:
def __init__(self):
[Link] = []

def push(self, x):


[Link](x)

def pop(self):
if not self.is_empty():
return [Link]()

def top(self):
if not self.is_empty():
return [Link][-1]

def is_empty(self):
return len([Link]) == 0

def display(self):
print("Current stack:", [Link])

print("case 1:")
s1 = stack()
[Link](1)
[Link](2)
[Link]()
print("Top element after operations:", [Link]())
[Link]()
print("
" + "-"*30)
print("case 2:")

s2 = stack()
[Link](5)
[Link](10)
[Link](20)
[Link]()
print("Top element after operations:", [Link]())
[Link]()
Exp 6

def largest_rectangle_area(heights):
stack = []
max_area = 0
[Link](0)
for i in range(len(heights)):
while stack and heights[i] < heights[stack[-1]]:
height = heights[[Link]()]
width = i if not stack else (i - stack[-1] - 1)
area = height * width
max_area = max(max_area, area)
[Link](i)
return max_area

# Input and usage


heights = list(map(int, input("Enter histogram bar heights: ").split()))
result = largest_rectangle_area(heights)
print("Largest rectangle area is:", result)

Exp 7
def subsets(nums):
result = []
path = []

def dfs(i):
if i == len(nums):
[Link]([Link]())
return
# Choice 1: EXCLUDE nums[i]
dfs(i + 1)
# Choice 2: INCLUDE nums[i]
[Link](nums[i])
dfs(i + 1)
[Link]()

dfs(0)
return result

# Demo with three cases


print("Case 1 input:", [1, 2, 3])
print("Case 1 subsets:", subsets([1, 2, 3]))
print("
Case 2 input:", [0, 1])
print("Case 2 subsets:", subsets([0, 1]))

print("
Case 3 input:", [1, 2, 3, 4])
print("Case 3 subsets:", subsets([1, 2, 3, 4]))

Exp 8

thod 1: Using Sortingdef find_kth_element(arr, k):


[Link]()
n = len(arr)
kth_smallest = arr[k-1]
kth_largest = arr[n-k]
return kth_smallest, kth_largest

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


k=3
smallest, largest = find_kth_element(arr, k)
print("Original Array:", [7, 10, 4, 3, 20, 15])
print("Sorted Array:", sorted([7, 10, 4, 3, 20, 15]))
print(f"{k}rd smallest element:", smallest)
print(f"{k}rd largest element:", largest)Method 2: Using Heapimport heapq

def kth_smallest_largest(arr, k):


smallest = [Link](k, arr)[-1]
largest = [Link](k, arr)[-1]
return smallest, largest

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


k=3
print(kth_smallest_largest(arr, k))

Exp 9

def find_peak_element(nums):
low, high = 0, len(nums) - 1
while low < high:
mid = (low + high) // 2
if nums[mid] < nums[mid + 1]:
low = mid + 1
else:
high = mid
return low

nums1 = [1, 2, 3, 4, 5]
nums2 = [5, 4, 3, 2, 1]
print("Case 1: Peak index:", find_peak_element(nums1),
"Value:", nums1[find_peak_element(nums1)])
print("Case 2: Peak index:", find_peak_element(nums2),
"Value:", nums2[find_peak_element(nums2)])

Exp 10

def find_min_platforms(arrivals, departures):


[Link]()
[Link]()
n = len(arrivals)
i=j=0
platforms_needed = 0
max_platforms = 0
while i < n and j < n:
if arrivals[i] < departures[j]:
platforms_needed += 1
max_platforms = max(max_platforms, platforms_needed)
i += 1
else:
platforms_needed -= 1
j += 1
return max_platforms

arrivals = [1000, 1015, 1025, 1040, 1050]


departures = [1030, 1045, 1050, 1100, 1110]
result = find_min_platforms(arrivals, departures)
print("Minimum no of platforms required:", result)

Exp 11

def countWays(coins, amount):


dp = [0] * (amount + 1)
dp[0] = 1
for coin in coins:
for i in range(coin, amount + 1):
dp[i] += dp[i - coin]
return dp[amount]

coins = [1, 2, 5]
amount = 10
print("No. of ways:", countWays(coins, amount))

You might also like