12 Programs Reformatted
12 Programs Reformatted
Bubble sorting
def bubble_sort(arr):
n = len(arr)
# Traverse through all array elements
for i in range(n):
# Last i elements are already sorted
for j in range(0, n-i-1):
# Swap if the element found is greater
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
# Example usage
arr = [64, 34, 25, 12, 22, 11, 90]
print("Original array:", arr)
bubble_sort(arr)
output
2. Insertion sorting
def insertion_sort(arr):
# Traverse through 1 to len(arr)
for i in range(1, len(arr)):
key = arr[i]
# Move elements of arr[0...i-1], that are greater than key, to one position
ahead
j=i-1
while j >= 0 and key < arr[j]:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
insertion_sort(arr)
output
3. Palindrome
def is_palindrome(s):
# Converting to lowercase and removing spaces
s = s.replace(" ", "").lower()
# Check if string is equal to its reverse
return s == s[::-1]
if is_palindrome(s):
print(f'"{s}" is a palindrome.')
else:
print(f'"{s}" is not a palindrome.')
output
4. Armstrong number
def is_armstrong(num):
# Convert the number to a string to calculate the number of digits
num_str = str(num)
n = len(num_str)
# Calculate the sum of each digit raised to the power of the number of digits
sum_of_powers = sum(int(digit) ** n for digit in num_str)
return sum_of_powers == num
if is_armstrong(num):
print(f'{num} is an Armstrong number.')
else:
print(f'{num} is not an Armstrong number.')
output
5. Factorial
def factorial_iterative(n):
result = 1
for i in range(1, n + 1):
result *= i
return result
if num < 0:
print("Factorial is not defined for negative numbers.")
else:
print(f'The factorial of {num} is {factorial_iterative(num)}.')
Output
6. Binary search
def binary_search(arr, target):
left, right = 0, len(arr) - 1
if result != -1:
print(f'The number {target} is found at index {result}.')
else:
print(f'The number {target} is not found in the list.')
output
7. Linear search
def linear_search(arr, target):
# Traverse through all elements in the list
for index, value in enumerate(arr):
# Check if the current element is equal to the target
if value == target:
return index # Return the index if found
return -1 # Return -1 if the target is not found
if result != -1:
print(f'The number {target} is found at index {result}.')
else:
print(f'The number {target} is not found in the list.')
output
8. Traversing a list
# Taking input from user
arr = list(map(int, input("Enter numbers separated by spaces: ").split()))
output
9. Ctack implementation
class Stack:
def __init__(self):
self.items = [] # Initialize an empty list to store stack items
def is_empty(self):
return len(self.items) == 0 # Return True if stack is empty
def pop(self):
if not self.is_empty():
return self.items.pop() # Remove and return the top item from the stack
else:
print("Stack is empty! Cannot pop.")
def peek(self):
if not self.is_empty():
return self.items[-1] # Return the top item without removing it
else:
print("Stack is empty! Cannot peek.")
def size(self):
return len(self.items) # Return the number of items in the stack
def display(self):
if not self.is_empty():
print("Stack elements (top to bottom):", self.items[::-1]) # Print elements
from top to bottom
else:
print("Stack is empty!")
# Example usage
stack = Stack()
# Operations
stack.push(10)
stack.push(20)
stack.push(30)
stack.display()
stack.display()
output
def is_empty(self):
return len(self.items) == 0 # Return True if queue is empty
def dequeue(self):
if not self.is_empty():
return self.items.pop(0) # Remove and return the front item of the queue
else:
print("Queue is empty! Cannot dequeue.")
def peek(self):
if not self.is_empty():
return self.items[0] # Return the front item without removing it
else:
print("Queue is empty! Cannot peek.")
def size(self):
return len(self.items) # Return the number of items in the queue
def display(self):
if not self.is_empty():
print("Queue elements (front to back):", self.items) # Print elements from
front to back
else:
print("Queue is empty!")
# Example usage
queue = Queue()
# Operations
queue.enqueue(10)
queue.enqueue(20)
queue.enqueue(30)
queue.display()
dequeued_item = queue.dequeue()
print("Dequeued item:", dequeued_item)
queue.display()
output
11. Function to print given pattern
1. Triangle Pattern
def print_triangle(n):
for i in range(1, n + 1):
print('*' * i)
# Example usage
n = int(input("Enter the number of rows for the triangle: "))
print_triangle(n)
output
def print_inverted_triangle(n):
print('*' * i)
# Example usage
print_inverted_triangle(n)
output
3. Pyramid Pattern
def print_pyramid(n):
for i in range(n):
# Example usage
print_pyramid(n)
output
4. Diamond Pattern
def print_diamond(n):
# Upper part
for i in range(n):
# Lower part
# Example usage
print_diamond(n)
output
12. Create a python program to create a
stack of student’s mark.
. write function push to add marks in to the stack and
. write function pop to remove the marks from stack and display the same.
class Stack:
def __init__(self):
self.stack = []
def is_empty(self):
return len(self.stack) == 0
def pop(self):
if self.is_empty():
print("Stack is empty. Cannot pop.")
return None
return self.stack.pop()
def peek(self):
if self.is_empty():
print("Stack is empty. Cannot peek.")
return None
return self.stack[-1]
def display(self):
if self.is_empty():
print("Stack is empty.")
else:
print("Current marks in the stack:", self.stack)
def main():
marks_stack = Stack()
while True:
print("\nOptions:")
print("1. Push mark")
print("2. Pop mark")
print("3. Peek at top mark")
print("4. Display marks")
print("5. Exit")
if __name__ == "__main__":
main()
output