Practical Daa
Practical Daa
Array Operations: Implement programs for 1-d arrays, Implement programs for 2-d arrays.
2. Accessing elements
print("\nAccessing elements:")
print(f"Element at index 0: {array_1d[0]}") # Output: 1
print(f"Element at index 2: {array_1d[2]}") # Output: 3
3. Modifying an element
array_1d[2] = 10 # Change the value at index 2 to 10
print("\nModified 1-D Array:", array_1d)
Output:-
2-D Array Operations
5. Row-wise sum
print("\nRow-wise sum of the 2-D Array:")
for i, row in enumerate(array_2d):
row_sum = sum(row)
print(f"Sum of row {i}: {row_sum}")
1. Class Stack:
The stack is represented by a list (self.stack).
The __init__() method initializes an empty stack.
2. Methods:
is_empty(): Checks if the stack is empty by comparing the length of the stack to zero.
push(item): Adds an element to the top of the stack using append().
pop(): Removes and returns the top element using pop(). If the stack is empty, it returns an
appropriate message.
peek(): Returns the top element without removing it. If the stack is empty, it returns a
message.
display(): Displays the current elements in the stack.
3. Driver Code:
Demonstrates various stack operations like push, pop, peek, and checks if the stack is empty
using the is_empty() method.
After each operation, the stack is displayed to show the changes.
Program:-
class Stack:
def __init__(self):
# Initialize the stack (empty list)
self.stack = []
def is_empty(self):
# Check if the stack is empty
return len(self.stack) == 0
def peek(self):
# Return the top element without removing it
if self.is_empty():
return "Stack is empty. Cannot peek."
return self.stack[-1]
def display(self):
# Display the current elements in the stack
if self.is_empty():
print("Stack is empty.")
else:
print("Current Stack:", self.stack)
Driver code
if __name__ == "__main__":
stack = Stack()
Output:-