Sunday, April 14, 2024

BCA PART A 10. Read and write into a file

 


def write_to_file(filename, data):
"""
Write data to a file.

Parameters:
filename (str): The name of the file to write to.
data (str): The data to write into the file.
"""
with open(filename, 'w') as file:
file.write(data)
print(f"Data written to file '{filename}' successfully.")

def read_from_file(filename):
"""
Read data from a file.

Parameters:
filename (str): The name of the file to read from.

Returns:
str: The data read from the file.
"""
with open(filename, 'r') as file:
data = file.read()
print(f"Data read from file '{filename}':")
return data


if __name__ == '__main__':
filename = input("Enter the name of the file: ")

# User choice for operation
print("\nChoose an operation:")
print("1. Write to the file")
print("2. Read from the file")
choice = input("Enter your choice (1/2): ")

if choice == '1':
# Writing to the file
data_to_write = input("Enter the data to write into the file: ")
write_to_file(filename, data_to_write)
elif choice == '2':
# Reading from the file
data = read_from_file(filename)
print(data)
else:
print("Invalid choice. Please enter 1 or 2.")

Output :

Enter the name of the file: test Choose an operation: 1. Write to the file 2. Read from the file Enter your choice (1/2): 1 Enter the data to write into the file: Good Morning. Welcome to Vidya Vikas Data written to file 'test' successfully.

Enter the name of the file: test Choose an operation: 1. Write to the file 2. Read from the file Enter your choice (1/2): 2 Data read from file 'test': Good Morning. Welcome to Vidya Vikas

Explanation :

In this program, two functions are defined:

  • write_to_file:

    • Takes a filename and data as input.
    • Opens the file in write mode ('w'), which either creates the file if it doesn't exist or truncates the file if it already exists.
    • Writes the data to the file.
    • Closes the file automatically when the with block exits.
  • read_from_file:

    • Takes a filename as input.
    • Opens the file in read mode ('r').
    • Reads the data from the file.
    • Closes the file automatically when the with block exits.
    • Returns the data read from the file.

In the example usage section of the program:

  • The user is prompted to enter the filename.
  • The user chooses to either write to the file or read from it.
  • Depending on the user's choice:
    • For the write operation, the program prompts the user to enter the data to write to the file and then calls the write_to_file function.
    • For the read operation, the program calls the read_from_file function and prints the data read from the file.

BCA PART A 9. Implement Stack

 


A stack is a data structure that follows the Last-In-First-Out (LIFO) principle. You can implement a stack in Python without using the stack module by using a list to store the stack elements. Below is a program that demonstrates how to create a stack class, implement its methods, and interact with the stack:


class Stack:
def __init__(self):
"""Initialize an empty stack using a list."""
self.stack = []

def is_empty(self):
"""Check if the stack is empty."""
return len(self.stack) == 0

def push(self, item):
"""Add an item to the top of the stack."""
self.stack.append(item)
print(f"Pushed {item} onto the stack.")

def pop(self):
"""Remove and return the item from the top of the stack.
If the stack is empty, return None and print a message."""
if self.is_empty():
print("Stack is empty. Cannot pop an item.")
return None
else:
item = self.stack.pop()
print(f"Popped {item} from the stack.")
return item

def peek(self):
"""Return the item from the top of the stack without removing it.
If the stack is empty, return None and print a message."""
if self.is_empty():
print("Stack is empty. Cannot peek an item.")
return None
else:
return self.stack[-1]

def display(self):
"""Display the current contents of the stack."""
if self.is_empty():
print("Stack is empty.")
else:
print("Stack contents:", self.stack)


# Example usage
if __name__ == "__main__":
# Create a stack instance
my_stack = Stack()

# Perform operations on the stack
while True:
print("\nStack Operations:")
print("1. Push an item onto the stack")
print("2. Pop an item from the stack")
print("3. Peek at the top item of the stack")
print("4. Display the contents of the stack")
print("5. Exit")
choice = input("Enter your choice (1-5): ")
if choice == '1':
item = input("Enter the item to push onto the stack: ")
my_stack.push(item)
elif choice == '2':
my_stack.pop()
elif choice == '3':
top_item = my_stack.peek()
if top_item is not None:
print(f"Top item: {top_item}")
elif choice == '4':
my_stack.display()
elif choice == '5':
print("Exiting the program.")
break
else:
print("Invalid choice. Please enter a number between 1 and 5.")

Output :

Enter your choice (1-5): 3 Stack is empty. Cannot peek an item. Stack Operations: 1. Push an item onto the stack 2. Pop an item from the stack 3. Peek at the top item of the stack 4. Display the contents of the stack 5. Exit Enter your choice (1-5): 4 Stack is empty. Stack Operations: 1. Push an item onto the stack 2. Pop an item from the stack 3. Peek at the top item of the stack 4. Display the contents of the stack 5. Exit Enter your choice (1-5): 1 Enter the item to push onto the stack: 34 Pushed 34 onto the stack. Stack Operations: 1. Push an item onto the stack 2. Pop an item from the stack 3. Peek at the top item of the stack 4. Display the contents of the stack 5. Exit Enter your choice (1-5): 1 Enter the item to push onto the stack: 5 Pushed 5 onto the stack. Stack Operations: 1. Push an item onto the stack 2. Pop an item from the stack 3. Peek at the top item of the stack 4. Display the contents of the stack 5. Exit Enter your choice (1-5): 4 Stack contents: ['34', '5'] Stack Operations: 1. Push an item onto the stack 2. Pop an item from the stack 3. Peek at the top item of the stack 4. Display the contents of the stack 5. Exit Enter your choice (1-5): 2 Popped 5 from the stack. Stack Operations: 1. Push an item onto the stack 2. Pop an item from the stack 3. Peek at the top item of the stack 4. Display the contents of the stack 5. Exit Enter your choice (1-5): 5 Exiting the program.

Explanation

The program provided implements a stack data structure in Python using a list to store stack elements. Let's go through each part of the program to understand how it works:

Stack Class

The Stack class defines the stack data structure and its methods.

  • __init__: This is the class constructor method. It initializes an empty list stack that will hold the stack elements.

  • is_empty: This method returns True if the stack is empty (i.e., the list has length zero) and False otherwise.

  • push: This method takes an item as an argument and adds it to the top of the stack using the append method of the list. It also prints a message indicating that the item was pushed onto the stack.

  • pop: This method removes and returns the item from the top of the stack. If the stack is empty, it prints a message indicating that the stack is empty and returns None. Otherwise, it uses the pop method of the list to remove the last element and prints a message showing which item was popped.

  • peek: This method returns the item from the top of the stack without removing it. If the stack is empty, it prints a message indicating that the stack is empty and returns None. Otherwise, it returns the last element in the list.

  • display: This method displays the current contents of the stack by printing the list.

Example Usage

The example usage section of the program demonstrates how to use the Stack class:

  • It first creates an instance of the Stack class called my_stack.

  • It then enters an infinite loop that provides a menu of stack operations that the user can perform: push, pop, peek, display, and exit.

  • Depending on the user's choice, the program performs the corresponding operation on the stack.

    • Push: The program prompts the user to enter an item and then pushes that item onto the stack using the push method.

    • Pop: The program calls the pop method to remove the top item from the stack and prints a message indicating which item was popped.

    • Peek: The program calls the peek method to view the top item of the stack and prints it.

    • Display: The program calls the display method to show the current contents of the stack.

    • Exit: The program breaks out of the loop and ends the program.

The program continues to loop, allowing the user to perform multiple operations on the stack, until the user chooses to exit the program.