실제 사용 사례
이제 Python 리스트에서 상위 N 개 요소를 찾는 다양한 기술을 배웠으므로 실제 사용 사례를 살펴보겠습니다. 이 단계에서는 이러한 개념을 실제 시나리오에 적용하는 보다 포괄적인 스크립트를 만들 것입니다.
프로젝트 디렉토리에 practical_applications.py라는 새 파일을 생성하고 다음 코드를 추가합니다.
## Real-world applications of finding top N elements
import heapq
from datetime import datetime
print("PRACTICAL APPLICATIONS OF FINDING TOP N ELEMENTS IN PYTHON LISTS\n")
## Application 1: E-commerce - Analyzing Product Sales
print("APPLICATION 1: E-COMMERCE - ANALYZING PRODUCT SALES")
print("==================================================")
## Sample product sales data (product_id, product_name, units_sold, price)
product_sales = [
(101, "Smartphone X", 1250, 899.99),
(102, "Wireless Earbuds", 2100, 129.99),
(103, "Laptop Pro", 890, 1299.99),
(104, "Smart Watch", 1450, 249.99),
(105, "Tablet Mini", 1050, 399.99),
(106, "Bluetooth Speaker", 1750, 79.99),
(107, "Gaming Console", 780, 499.99),
(108, "Digital Camera", 550, 349.99),
(109, "Power Bank", 1900, 49.99),
(110, "Fitness Tracker", 1350, 129.99)
]
## Find top 3 products by units sold
top_sold_products = heapq.nlargest(3, product_sales, key=lambda x: x[2])
print("\nTop 3 Best-Selling Products (by units sold):")
for product in top_sold_products:
print(f" {product[1]}: {product[2]} units sold at ${product[3]}")
## Find top 3 products by revenue (units_sold * price)
top_revenue_products = heapq.nlargest(3, product_sales, key=lambda x: x[2] * x[3])
print("\nTop 3 Products by Revenue:")
for product in top_revenue_products:
revenue = product[2] * product[3]
print(f" {product[1]}: ${revenue:,.2f} revenue ({product[2]} units at ${product[3]})")
## Application 2: Data Analysis - Temperature Monitoring
print("\n\nAPPLICATION 2: DATA ANALYSIS - TEMPERATURE MONITORING")
print("====================================================")
## Sample temperature data (date, city, temperature)
temperature_data = [
("2023-06-15", "New York", 32.5),
("2023-06-15", "Los Angeles", 28.3),
("2023-06-15", "Chicago", 30.1),
("2023-06-15", "Houston", 35.7),
("2023-06-15", "Phoenix", 40.2),
("2023-06-15", "Miami", 33.8),
("2023-06-15", "Denver", 29.6),
("2023-06-15", "Seattle", 22.4),
("2023-06-15", "Boston", 27.9),
("2023-06-15", "Atlanta", 31.5)
]
## Find cities with highest temperatures
hottest_cities = heapq.nlargest(3, temperature_data, key=lambda x: x[2])
print("\nTop 3 Hottest Cities:")
for city_data in hottest_cities:
print(f" {city_data[1]}: {city_data[2]}°C")
## Find cities with lowest temperatures
coldest_cities = heapq.nsmallest(3, temperature_data, key=lambda x: x[2])
print("\nTop 3 Coldest Cities:")
for city_data in coldest_cities:
print(f" {city_data[1]}: {city_data[2]}°C")
## Application 3: Social Media - User Engagement
print("\n\nAPPLICATION 3: SOCIAL MEDIA - USER ENGAGEMENT")
print("=============================================")
## Sample social media post data (post_id, title, likes, comments, shares, timestamp)
posts = [
(1001, "Breaking News: Major Announcement", 3500, 420, 1200, datetime(2023, 6, 10, 12, 30)),
(1002, "Product Review: Latest Gadget", 2200, 380, 900, datetime(2023, 6, 11, 15, 45)),
(1003, "Tutorial: Python Programming", 1800, 650, 750, datetime(2023, 6, 12, 9, 15)),
(1004, "Travel Tips for Summer Vacation", 2700, 320, 1100, datetime(2023, 6, 13, 18, 20)),
(1005, "Recipe: Delicious Desserts", 3100, 450, 1500, datetime(2023, 6, 14, 11, 10)),
(1006, "Interview with Celebrity", 4200, 580, 2200, datetime(2023, 6, 15, 14, 25)),
(1007, "Health and Fitness Guide", 1500, 280, 600, datetime(2023, 6, 16, 8, 40)),
(1008, "Movie Review: Latest Blockbuster", 2900, 410, 950, datetime(2023, 6, 17, 20, 30)),
(1009, "Tech News: Industry Updates", 2000, 300, 800, datetime(2023, 6, 18, 13, 15)),
(1010, "DIY Home Improvement Projects", 1700, 520, 700, datetime(2023, 6, 19, 16, 50))
]
## Define a function to calculate engagement score (weighted sum of likes, comments, shares)
def engagement_score(post):
return post[2] + (post[3] * 2) + (post[4] * 3) ## likes + (comments * 2) + (shares * 3)
## Find top 3 posts by engagement score
top_engaging_posts = heapq.nlargest(3, posts, key=engagement_score)
print("\nTop 3 Most Engaging Posts:")
for post in top_engaging_posts:
score = engagement_score(post)
print(f" Post ID: {post[0]}")
print(f" Title: {post[1]}")
print(f" Engagement Score: {score}")
print(f" (Likes: {post[2]}, Comments: {post[3]}, Shares: {post[4]})")
print(f" Posted on: {post[5].strftime('%Y-%m-%d %H:%M')}")
print()
## Find top 3 posts by likes
top_liked_posts = heapq.nlargest(3, posts, key=lambda x: x[2])
print("Top 3 Most Liked Posts:")
for post in top_liked_posts:
print(f" {post[1]}: {post[2]} likes")
## Find top 3 posts by comments
top_commented_posts = heapq.nlargest(3, posts, key=lambda x: x[3])
print("\nTop 3 Most Commented Posts:")
for post in top_commented_posts:
print(f" {post[1]}: {post[3]} comments")
스크립트를 실행하여 이러한 실제 사용 사례를 확인합니다.
python3 practical_applications.py
상위 N 개 요소를 찾는 방법을 실제 시나리오에 적용할 수 있는지 보여주는 자세한 출력이 표시되어야 합니다.
PRACTICAL APPLICATIONS OF FINDING TOP N ELEMENTS IN PYTHON LISTS
APPLICATION 1: E-COMMERCE - ANALYZING PRODUCT SALES
==================================================
Top 3 Best-Selling Products (by units sold):
Wireless Earbuds: 2100 units sold at $129.99
Power Bank: 1900 units sold at $49.99
Bluetooth Speaker: 1750 units sold at $79.99
Top 3 Products by Revenue:
Smartphone X: $1,124,987.50 revenue (1250 units at $899.99)
Laptop Pro: $1,156,991.10 revenue (890 units at $1299.99)
Wireless Earbuds: $272,979.00 revenue (2100 units at $129.99)
APPLICATION 2: DATA ANALYSIS - TEMPERATURE MONITORING
====================================================
Top 3 Hottest Cities:
Phoenix: 40.2°C
Houston: 35.7°C
Miami: 33.8°C
Top 3 Coldest Cities:
Seattle: 22.4°C
Boston: 27.9°C
Los Angeles: 28.3°C
APPLICATION 3: SOCIAL MEDIA - USER ENGAGEMENT
=============================================
Top 3 Most Engaging Posts:
Post ID: 1006
Title: Interview with Celebrity
Engagement Score: 11560
(Likes: 4200, Comments: 580, Shares: 2200)
Posted on: 2023-06-15 14:25
Post ID: 1005
Title: Recipe: Delicious Desserts
Engagement Score: 8450
(Likes: 3100, Comments: 450, Shares: 1500)
Posted on: 2023-06-14 11:10
Post ID: 1001
Title: Breaking News: Major Announcement
Engagement Score: 8060
(Likes: 3500, Comments: 420, Shares: 1200)
Posted on: 2023-06-10 12:30
Top 3 Most Liked Posts:
Interview with Celebrity: 4200 likes
Breaking News: Major Announcement: 3500 likes
Recipe: Delicious Desserts: 3100 likes
Top 3 Most Commented Posts:
Tutorial: Python Programming: 650 comments
Interview with Celebrity: 580 comments
DIY Home Improvement Projects: 520 comments
이러한 예는 전자 상거래 판매 분석, 날씨 데이터 분석 및 소셜 미디어 참여 지표와 같은 실제 시나리오에 배운 기술을 적용할 수 있는 방법을 보여줍니다. 각 경우에 상위 N 개 요소를 효율적으로 찾는 기능은 데이터에서 가치 있는 통찰력을 추출하는 데 매우 중요합니다.