File Size Calculation
import os
def calculate_directory_size(directory_path):
total_size = 0
dir_stack = [directory_path]
while dir_stack:
current_path = dir_stack.pop()
for item in os.listdir(current_path):
full_path = os.path.join(current_path, item)
if os.path.isfile(full_path):
total_size += os.path.getsize(full_path)
else:
dir_stack.append(full_path)
return total_size
print(calculate_directory_size('/path/to/directory'))
Multi-level Menu Navigation
menu = {
'main': {'sub1': {}, 'sub2': {}},
'sub1': {'option1': {}, 'option2': {}}
}
current_menu = ['main']
while current_menu:
for option in current_menu[-1]:
print(option)
selection = input('>>> ').upper()
if selection == 'B':
current_menu.pop()
elif selection == 'Q':
current_menu.clear()
elif selection in current_menu[-1]:
current_menu.append(current_menu[-1][selection])
File Monitoring
def monitor_file_changes(file_path):
with open(file_path, 'r', encoding='utf-8') as f:
while True:
line = f.readline()
if line:
yield line
for change in monitor_file_changes('log.txt'):
print(change)
Red Packet Distribution
import random
def distribute_money(total_amount, recipients):
divisions = random.sample(range(1, total_amount*100), recipients-1)
divisions.sort()
divisions = [0] + divisions + [total_amount*100]
for i in range(len(divisions)-1):
yield (divisions[i+1] - divisions[i]) / 100
for amount in distribute_money(200, 5):
print(f"Received: {amount}")
Recursvie Path Finding
people = ['Alice', 'Bob', 'Charlie', 'David', 'Eve']
def ask_for_directions(contacts):
if not contacts:
return "No directions found"
person = contacts[0]
if person == 'Eve':
return f"{person} says: The destination is near the central park"
print(f"Asking {person} for directions")
return ask_for_directions(contacts[1:])
print(ask_for_directions(people))
Shopipng Cart Implementation
products = [
{'name': 'Laptop', 'price': 999},
{'name': 'Phone', 'price': 699},
{'name': 'Tablet', 'price': 399}
]
cart = {}
budget = float(input("Enter your budget: "))
while True:
for idx, product in enumerate(products, 1):
print(f"{idx}. {product['name']} - ${product['price']}")
choice = input("Select product (Q to quit): ")
if choice.upper() == 'Q':
break
elif choice.isdigit() and 0 < int(choice) <= len(products):
selected = products[int(choice)-1]
cart[selected['name']] = cart.get(selected['name'], 0) + 1
print("Your cart:")
for item, quantity in cart.items():
print(f"{item}: {quantity}")