How to structure and print a categorized restaurant-style menu with aligned prices in Python?

Summary

The problem at hand is to create a well-structured and readable restaurant-style menu in Python, with aligned prices and clear categorization. The current implementation uses a dictionary to store menu items, but it has issues with price alignment and code organization.

Root Cause

The root cause of the problem is the lack of a standardized formatting approach and the use of a dictionary to store menu items, which can lead to inconsistent formatting and tight coupling between data and presentation logic. The main causes are:

  • Inconsistent item name lengths causing price misalignment
  • Mixed formatting logic and data structure
  • Unclear categorization and separation of menu items

Why This Happens in Real Systems

This problem occurs in real systems due to:

  • Insufficient planning and design of the data structure and formatting approach
  • Lack of separation of concerns between data and presentation logic
  • Inadequate use of formatting tools and libraries

Real-World Impact

The impact of this problem is:

  • Poor user experience due to difficult-to-read menus
  • Increased maintenance costs due to tightly coupled code
  • Limited scalability and flexibility in menu design and formatting

Example or Code

from tabulate import tabulate

menu = {
    "Drinks": [
        {"name": "Cold Brew Coffee", "price": 4.50},
        {"name": "Vanilla Latte", "price": 5.00},
        {"name": "Caramel Mocha", "price": 5.25}
    ],
    "Seasonal": [
        {"name": "Peppermint Mocha", "price": 5.75},
        {"name": "Sugar Cookie Latte", "price": 5.75}
    ]
}

item_number = 1
item_map = {}

for category, items in menu.items():
    print(category)
    print("-" * len(category))
    table = [[item_number, item['name'], f"${item['price']:.2f}"] for item in items]
    print(tabulate(table, headers=["#", "Item", "Price"], tablefmt="grid"))
    for item in items:
        item_map[item_number] = item
        item_number += 1
    print()

How Senior Engineers Fix It

Senior engineers fix this problem by:

  • Separating concerns between data and presentation logic
  • Using standardized formatting approaches and libraries (e.g., tabulate)
  • Designing flexible and scalable data structures (e.g., using classes or dataclasses)
  • Implementing automated testing to ensure consistent formatting and functionality

Why Juniors Miss It

Juniors may miss this solution due to:

  • Lack of experience with large-scale systems and complex data structures
  • Insufficient knowledge of formatting libraries and tools
  • Tendency to focus on quick fixes rather than long-term design and scalability
  • Limited understanding of the importance of separation of concerns and standardized formatting approaches

Leave a Comment