[go: up one dir, main page]

0% found this document useful (0 votes)
35 views22 pages

12 Programs Reformatted

Uploaded by

chessaadil
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)
35 views22 pages

12 Programs Reformatted

Uploaded by

chessaadil
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/ 22

1.

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)

print("Sorted array:", 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

# Taking input from user


arr = list(map(int, input("Enter numbers separated by spaces: ").split()))

print("Original array:", arr)

insertion_sort(arr)

print("Sorted array:", 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]

# Taking input from user


s = input("Enter a string: ")

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

# Taking input from user


num = int(input("Enter a number: "))

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

# Taking input from user


num = int(input("Enter a non-negative integer: "))

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

while left <= right:


mid = left + (right - left) // 2 # Find the mid index
# Check if the target is present at mid
if arr[mid] == target:
return mid # Target found
# If target is greater, ignore left half
elif arr[mid] < target:
left = mid + 1
# If target is smaller, ignore right half
else:
right = mid - 1

return -1 # Target not found


# Taking input from user
arr = list(map(int, input("Enter sorted numbers separated by spaces: ").split()))
target = int(input("Enter the number to search for: "))

result = binary_search(arr, target)

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

# Taking input from user


arr = list(map(int, input("Enter numbers separated by spaces: ").split()))
target = int(input("Enter the number to search for: "))

result = linear_search(arr, target)

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

print("Traversing the list using different methods:\n")

# 1. Using a for loop


print("Using a for loop:")
for element in arr:
print(element, end=' ')
print() # Newline for better formatting

# 2. Using while loop


print("Using a while loop:")
index = 0
while index < len(arr):
print(arr[index], end=' ')
index += 1
print() # Newline for better formatting

# 3. Using list comprehension (to create a new list from existing)


print("Using list comprehension to create a new list (squared values):")
squared_list = [x ** 2 for x in arr]
print(squared_list)

# 4. Using the enumerate function to get both index and value


print("Using enumerate to get index and value:")
for index, value in enumerate(arr):
print(f'Index {index}: {value}')

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 push(self, item):


self.items.append(item) # Add an item to the top of the stack
print(f'Pushed {item} to the stack.')

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

print("Top element is:", stack.peek())


print("Stack size is:", stack.size())
popped_item = stack.pop()
print("Popped item:", popped_item)

stack.display()

output

10. Queue implementation


class Queue:
def __init__(self):
self.items = [] # Initialize an empty list to store queue items

def is_empty(self):
return len(self.items) == 0 # Return True if queue is empty

def enqueue(self, item):


self.items.append(item) # Add an item to the end of the queue
print(f'Enqueued {item} to the queue.')

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

print("Front element is:", queue.peek())


print("Queue size is:", queue.size())

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

2. Inverted Triangle Pattern

def print_inverted_triangle(n):

for i in range(n, 0, -1):

print('*' * i)

# Example usage

n = int(input("Enter the number of rows for the inverted triangle: "))

print_inverted_triangle(n)

output
3. Pyramid Pattern

def print_pyramid(n):

for i in range(n):

print(' ' * (n - i - 1) + '*' * (2 * i + 1))

# Example usage

n = int(input("Enter the number of rows for the pyramid: "))

print_pyramid(n)

output
4. Diamond Pattern

def print_diamond(n):

# Upper part

for i in range(n):

print(' ' * (n - i - 1) + '*' * (2 * i + 1))

# Lower part

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

print(' ' * (n - i - 1) + '*' * (2 * i + 1))

# Example usage

n = int(input("Enter the number of rows for the diamond: "))

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 push(self, mark):


self.stack.append(mark)
print(f"Pushed {mark} onto the stack.")

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

choice = input("Choose an option (1-5): ")


if choice == '1':
mark = float(input("Enter the student's mark: "))
marks_stack.push(mark)
elif choice == '2':
popped_mark = marks_stack.pop()
if popped_mark is not None:
print(f"Popped mark: {popped_mark}")
elif choice == '3':
top_mark = marks_stack.peek()
if top_mark is not None:
print(f"Top mark: {top_mark}")
elif choice == '4':
marks_stack.display()
elif choice == '5':
print("Exiting the program.")
break
else:
print("Invalid choice. Please select a valid option.")

if __name__ == "__main__":
main()
output

You might also like