0% found this document useful (0 votes)
9 views11 pages

2D Array and Stack Operations Guide

Uploaded by

sanketabhang0
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)
9 views11 pages

2D Array and Stack Operations Guide

Uploaded by

sanketabhang0
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

# Implement 2-D Array

array_2d = [

[1, 2, 3],

[4, 5, 6],

[7, 8, 9]

print("Original 2D Array:")

for row in array_2d:

print(row)

# Access element at row 1, column 2 (indexing starts from 0)

print("\nElement at row 1, column 2:", array_2d[1][2])

# Change element in row 2, column 1

array_2d[2][0] = 10

print("\nArray after modification:")

for row in array_2d:

print(row)

# Add new row

array_2d.append([10, 11, 12])

print("\nArray after adding a new row:")

for row in array_2d:

print(row)
# Iteration through all elements

print("\nIteration through all elements:")

for row in array_2d:

for element in row:

print(element, end=" ")

# Stack Operation
stack = []

def push(stack, element):

[Link](element)

print(f"Pushed element {element} to the stack. Current stack: {stack}")

def pop(stack):

if len(stack) == 0:

raise IndexError("Pop from empty stack")

removed_element = [Link]()

print(f"Popped and removed element {removed_element} from the stack. Current stack: {stack}")

return removed_element

def peek(stack):

if len(stack) == 0:

raise IndexError("Peek from empty stack")

top_element = stack[-1]

print(f"Top element is {top_element}")


return top_element

def is_empty(stack):

empty = len(stack) == 0

print(f"Is stack empty? {empty}")

return empty

def size(stack):

current_size = len(stack)

print(f"Size of stack: {current_size}")

return current_size

# Test the stack functions

push(stack, 1)

push(stack, 2)

push(stack, 3)

peek(stack)

pop(stack)

pop(stack)

is_empty(stack)

size(stack)
# Tower of honai
def tower_of_hanoi(n, source, auxiliary, target):

if n == 1:

print(f"Move disk 1 from {source} to {target}")

return

tower_of_hanoi(n - 1, source, target, auxiliary)

print(f"Move disk {n} from {source} to {target}")

tower_of_hanoi(n - 1, auxiliary, source, target)

# Number of disks

n=3

# Call the function

tower_of_hanoi(n, 'A', 'B', 'C')

# Bubble Sort
def bubble_sort(arr, n):

if n == 1:

return

for i in range(n - 1):

if arr[i] > arr[i + 1]:

arr[i], arr[i + 1] = arr[i + 1], arr[i]

# Recursive call for remaining unsorted part


bubble_sort(arr, n - 1)

arr = [64, 34, 25, 12, 22, 11, 90]

n = len(arr)

print("Original array:", arr)

bubble_sort(arr, n)

print("Sorted array:", arr)

# Fibonacci series

def fibonacci(n):

if n <= 1:

return n

else:

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

def fibonacci_series(n):

for i in range(n):

print(fibonacci(i), end=" ")

# Number of terms

n = 10

fibonacci_series(n)
# Merge Sorting

def merge_sort(arr):

if len(arr) <= 1:

return arr

mid = len(arr) // 2

left_half = arr[:mid]

right_half = arr[mid:]

left_sorted = merge_sort(left_half)

right_sorted = merge_sort(right_half)

return merge(left_sorted, right_sorted)

def merge(left, right):

sorted_arr = []

i=j=0

while i < len(left) and j < len(right):

if left[i] < right[j]:

sorted_arr.append(left[i])

i += 1

else:

sorted_arr.append(right[j])

j += 1
sorted_arr.extend(left[i:])

sorted_arr.extend(right[j:])

return sorted_arr

# Example usage

arr = [38, 27, 43, 3, 9, 82, 10]

print("Original array:", arr)

sorted_arr = merge_sort(arr)

print("Sorted array:", sorted_arr)

# Dynamic programing Fibonacci series

# Fibonacci Series using Dynamic Programming

def fibonacci(n):

# Base cases

if n <= 1:

return n

# Create an array to store Fibonacci numbers

Fib = [0] * (n + 1)

Fib[0] = 0

Fib[1] = 1

for i in range(2, n + 1):


Fib[i] = Fib[i - 1] + Fib[i - 2]

return Fib[n]

# Main program

if __name__ == "__main__":

n = 10 # Fibonacci term to find

print(f"The {n}th Fibonacci number is: {fibonacci(n)}")

# Coin Change

# Greedy Algorithm for Coin Change

def coin_change_greedy(coins, amount):

[Link](reverse=True) # Sort coins in descending order

coin_count = {}

remaining_amount = amount

total_coins = 0

for coin in coins:

if remaining_amount >= coin:

num_coins = remaining_amount // coin

coin_count[coin] = num_coins

total_coins += num_coins

remaining_amount -= num_coins * coin


if remaining_amount == 0:

break

if remaining_amount > 0:

return -1, {} # Change cannot be made

else:

return total_coins, coin_count

# Main program

if __name__ == "__main__":

coins = [1, 5, 10, 25]

amount = 63

result, coin_count = coin_change_greedy(coins, amount)

if result == -1:

print("Change cannot be made with the given denominations.")

else:

print(f"Minimum number of coins needed: {result}")

print("Coins used:")

for coin, count in coin_count.items():

print(f"Coin: {coin}, Count: {count}")

# Pattern Matching

def naive_pattern_matching(text, pattern):


n = len(text)

m = len(pattern)

result = []

for i in range(n - m + 1):

if text[i : i + m] == pattern:

[Link](i)

return result

# Example usage

text = "this is a simple, example is good"

pattern = "example"

indices = naive_pattern_matching(text, pattern)

if indices:

print(f"Pattern found at indices: {indices}")

else:

print("Pattern not found")

# Binary Search

# Binary Search

def binary_search(arr, target):


left = 0

right = len(arr) - 1

while left <= right:

mid = (left + right) // 2

if arr[mid] == target:

return mid

elif arr[mid] < target:

left = mid + 1

else:

right = mid - 1

return -1

# Example usage

arr = [1, 3, 5, 7, 9, 11]

target = 7

result = binary_search(arr, target)

if result != -1:

print(f"Element {target} found at index {result}")

else:

print(f"Element {target} not found in the list")

You might also like