0% found this document useful (0 votes)
8 views8 pages

Practical Daa

The document outlines operations for 1-D and 2-D arrays in Python, detailing creation, access, modification, traversal, and mathematical operations for both types. It also describes a list-based stack implementation, including methods for checking if the stack is empty, pushing and popping elements, peeking at the top element, and displaying the stack's contents. The document includes example code for each operation, demonstrating their functionality.

Uploaded by

Soham Ghadge
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)
8 views8 pages

Practical Daa

The document outlines operations for 1-D and 2-D arrays in Python, detailing creation, access, modification, traversal, and mathematical operations for both types. It also describes a list-based stack implementation, including methods for checking if the stack is empty, pushing and popping elements, peeking at the top element, and displaying the stack's contents. The document includes example code for each operation, demonstrating their functionality.

Uploaded by

Soham Ghadge
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/ 8

Practical 1

Array Operations: Implement programs for 1-d arrays, Implement programs for 2-d arrays.

1-D Array Operation

1-D Array Operations:


 Creating the Array: The array is simply a Python list, and we initialize it with values.
 Accessing Elements: We access elements using their indices, which start from 0 in Python.
 Modifying Elements: You can change values by directly referencing their index.
 Traversing: A for loop is used to print each element.
 Mathematical Operations: We calculate the sum and average of the elements. We also find
the minimum and maximum values of the array.

1. Create a 1-D Array (List)


array_1d = [1, 2, 3, 4, 5]
print("1-D Array:", array_1d)

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)

4. Traversing the array


print("\nTraversing the 1-D Array:")
for element in array_1d:
print(element, end=" ") # Output: 1 2 10 4 5
print()
5. Mathematical operations (Sum and Average)
array_sum = sum(array_1d)
array_average = array_sum / len(array_1d)
print("\nMathematical Operations:")
print(f"Sum of elements: {array_sum}")
print(f"Average of elements: {array_average}")

6. Find minimum and maximum values


array_min = min(array_1d)
array_max = max(array_1d)
print(f"\nMinimum value: {array_min}")
print(f"Maximum value: {array_max}")

Output:-
2-D Array Operations

2-D Array Operations:


 Creating a 2-D Array: This is achieved using a list of lists. Each inner list represents a row
of the 2-D array.
 Accessing Elements: We access elements using two indices: one for the row and another for
the column.
 Modifying Elements: Similar to 1-D arrays, elements can be modified by indexing into the
array.
 Traversing the Array: We use nested for loops to iterate over the rows and then each element
in the row.
 Row-wise and Column-wise Operations: We calculate the sum for each row and for each
column by using enumerate () and sum () functions.

1. Create a 2-D Array (List of lists)


array_2d = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print("2-D Array:")
for row in array_2d:
print(row)

2. Accessing elements in a 2-D array


print("\nAccessing elements in the 2-D Array:")
print(f"Element at position (0, 1): {array_2d[0][1]}") # Output: 2
print(f"Element at position (2, 2): {array_2d[2][2]}") # Output: 9

3. Modifying an element in the 2-D array


array_2d[1][2] = 10 # Modify the element at row 1, column 2
print("\nModified 2-D Array:")
for row in array_2d:
print(row)
4. Traversing the 2-D array (Nested loop)
print("\nTraversing the 2-D Array:")
for row in array_2d:
for element in row:
print(element, end=" ")
print()

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

6. Transposing the 2-D array (Swapping rows with columns)


transpose_2d = [[array_2d[j][i] for j in range(len(array_2d))] for i in range(len(array_2d[0]))]
print("\nTransposed 2-D Array:")
for row in transpose_2d:
print(row)

7. Column-wise sum (Requires iterating over columns)


print("\nColumn-wise sum of the 2-D Array:")
for col_index in range(len(array_2d[0])):
col_sum = sum(array_2d[row_index][col_index] for row_index in range(len(array_2d)))
print(f"Sum of column {col_index}: {col_sum}")
Output:-
Practical No. 2
List-Based Stack Operations: Create a list-based stack and perform stack operations.

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


# Add an element to the top of the stack
self.stack.append(item)
print(f"'{item}' pushed to stack")
def pop(self):
# Remove and return the top element of the stack
if self.is_empty():
return "Stack is empty. Cannot pop."
return self.stack.pop()

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

# Push elements to the stack


stack.push(10)
stack.push(20)
stack.push(30)
stack.push(40)

# Display current stack


stack.display()

# Peek at the top element


print("Top element (peek):", stack.peek())
# Pop elements from the stack
print("Popped element:", stack.pop())
print("Popped element:", stack.pop())

# Display the current stack after popping


stack.display()

# Check if stack is empty


print("Is the stack empty?", stack.is_empty())

# Pop remaining elements


print("Popped element:", stack.pop())
print("Popped element:", stack.pop())

# Display current stack (empty)


stack.display()

# Try popping from an empty stack


print("Popped element from empty stack:", stack.pop())

Output:-

You might also like