🚀 Mastering 2D Arrays & Essential Operations: A Versatile Template! 🚀
Python Code template for 2D Array, A Level tentative exam question.

🚀 Mastering 2D Arrays & Essential Operations: A Versatile Template! 🚀

import os

# Function to input initial 5 items into the 2D list
def input_items():
    items = []
    choice = input("Do you want to use predefined values? (yes/no): ").strip().lower()
    if choice == 'yes':
        items = [["Apple", 1.2, 10], ["Banana", 0.5, 20], ["Orange", 0.8, 15], ["Grapes", 2.5, 8], ["Mango", 1.8, 12]]
    else:
        for i in range(5):
            item = input(f"Enter name of item {i+1}: ")
            price = float(input(f"Enter price of {item}: "))
            stock = int(input(f"Enter stock for {item}: "))
            items.append([item, price, stock])
    return items

# Function to add a new record to the list
def add_record(items):
    item = input("Enter item name: ")
    price = float(input("Enter price: "))
    stock = int(input("Enter stock: "))
    items.append([item, price, stock])
    print("Record added successfully!")

# Function to edit an existing record
def edit_record(items):
    if not items:
        print("No records available to edit!")
        return
    item_name = input("Enter item name to edit: ")
    for item in items:
        if item[0] == item_name:
            item[1] = float(input("Enter new price: "))
            item[2] = int(input("Enter new stock: "))
            print("Record updated!")
            return
    print("Item not found!")

# Function to delete a record
def delete_record(items):
    if not items:
        print("No records available to delete!")
        return
    item_name = input("Enter item name to delete: ")
    for i in range(len(items)):
        if items[i][0] == item_name:
            del items[i]
            print("Record deleted!")
            return
    print("Item not found!")

# Function to list all items along with their values
def list_items(items):
    if not items:
        print("No records available!")
        return
    print("\nItem List:")
    print("Item\tPrice\tStock\tValue")
    for item in items:
        print(f"{item[0]}\t{item[1]}\t{item[2]}\t{item[1] * item[2]}")

# Function to perform linear search for an item
"""A searching algorithm that checks each element in a list one by 
one until the desired element is found or the list ends."""
def linear_search(items):
    if not items:
        print("No records available to search!")
        return
    item_name = input("Enter item name to search: ")
    for item in items:
        if item[0] == item_name:
            print(f"Found: {item}")
            return
    print("Item not found!")

# Recursive linear search
def recursive_linear_search(items, item_name, index=0):
    if index >= len(items):
        print("Item not found!")
        return
    if items[index][0] == item_name:
        print(f"Found: {items[index]}")
        return
    recursive_linear_search(items, item_name, index + 1)

# Function to sort the items based on price using bubble sort
"""A sorting algorithm that repeatedly swaps adjacent elements if they
 are in the wrong order. This process continues until the array is sorted."""
def bubble_sort(items):
    if not items:
        print("No records available to sort!")
        return
    order = input("Sort in ascending or descending order? (asc/desc): ").strip().lower()
    ascending = order == 'asc'
    n = len(items)
    for i in range(n):
        for j in range(0, n-i-1):
            if (items[j][1] > items[j+1][1] and ascending) or (items[j][1] < items[j+1][1] and not ascending):  # Sorting by price
                items[j], items[j+1] = items[j+1], items[j]
    print("Array sorted by price!")
    list_items(items)  # Display sorted array

# Recursive bubble sort
"""A recursive function is a function that calls itself in order
 to solve a smaller instance of the same problem. It continues 
 calling itself until a base condition is met, which stops the recursion."""
def recursive_bubble_sort(items, n=None):
    if n is None:
        n = len(items)
    if n == 1:
        return
    for i in range(n - 1):
        if items[i][1] > items[i + 1][1]:
            items[i], items[i + 1] = items[i + 1], items[i]
    recursive_bubble_sort(items, n - 1)

# Function to calculate total inventory value
def total_value(items):
    if not items:
        print("No records available!")
        return
    total = sum(item[1] * item[2] for item in items)
    print(f"Total Inventory Value: {total}")

# Function to find the item with the maximum price
def max_prize_item(items):
    if not items:
        print("No records available!")
        return
    max_item = max(items, key=lambda x: x[1])
    print(f"Item with max price: {max_item}")

# Function to write items to a file
def write_to_file(items):
    with open("items.txt", "w") as file:
        for item in items:
            file.write(f"{item[0]}, {item[1]}, {item[2]}\n")
    print("Data written to items.txt!")

# Main function to handle menu-driven execution
def main():
    items = []
    while True:
        print("\nMENU:")
        print("1. Input Items")
        print("2. Add Record")
        print("3. Edit Record")
        print("4. Delete Record")
        print("5. List Items")
        print("6. Search Item (Linear Search)")
        print("7. Sort Items (Bubble Sort by Price)")
        print("8. Calculate Total Value")
        print("9. Find Max Priced Item")
        print("10. Recursive Linear Search")
        print("11. Recursive Bubble Sort")
        print("12. Write to File")
        print("13. Exit")
        choice = input("Enter choice: ")

        if choice == '1':
            items = input_items()
        elif choice == '2':
            add_record(items)
        elif choice == '3':
            edit_record(items)
        elif choice == '4':
            delete_record(items)
        elif choice == '5':
            list_items(items)
        elif choice == '6':
            linear_search(items)
        elif choice == '7':
            bubble_sort(items)
        elif choice == '8':
            total_value(items)
        elif choice == '9':
            max_prize_item(items)
        elif choice == '10':
            item_name = input("Enter item name to search: ")
            recursive_linear_search(items, item_name)
        elif choice == '11':
            recursive_bubble_sort(items)
            list_items(items)
        elif choice == '12':
            write_to_file(items)
        elif choice == '13':
            print("Exiting program...")
            break
        else:
            print("Invalid choice, try again!")

if __name__ == "__main__":
    main()        

Also refer to my other posts..

Files in Python


To view or add a comment, sign in

More articles by Mohan Robert

Insights from the community

Others also viewed

Explore topics