Advanced Python Concepts: List Comprehension dan Generators

 List Comprehension dan Generators adalah fitur Python yang powerful untuk membuat dan memanipulasi sequence (urutan) data secara efisien dan ringkas.

  1. List Comprehension: List Comprehension adalah cara singkat untuk membuat list berdasarkan list yang sudah ada atau iterable lainnya. Ini sering kali lebih cepat dan lebih mudah dibaca daripada loop tradisional.

Sintaks dasar: 

[expression for item in iterable if condition]

Keuntungan dan penggunaan kasus:

  • Lebih mudah dibaca dan ringkas daripada loop tradisional
  • Seringkali lebih cepat dari setara untuk loop
  • Ideal untuk membuat daftar baru berdasarkan transformasi sederhana atau filter

  1. Generators: Generators adalah fungsi khusus yang mengembalikan iterator. Mereka menggunakan keyword 'yield' alih-alih 'return'. Generators sangat efisien dalam penggunaan memori karena mereka menghasilkan item satu per satu, bukan menyimpan seluruh sequence dalam memori.

Sintaks dasar:

def generator_function():

     for item in iterable:

         yield item

Keuntungan dan penggunaan kasus:

  • Memori efisien untuk data besar
  • Memungkinkan evaluasi data yang malas berguna untuk bekerja dengan urutan tak terbatas
  • Ideal untuk skenario di mana Anda tidak membutuhkan semua data sekaligus

contoh implementasi dalam berbagai industri:

  1. Inventory dan Warehouse:
python
# List Comprehension: Memfilter produk yang stoknya rendah low_stock_products = [product for product in inventory if product.stock < 10] # Generator: Memantau pergerakan stok def stock_movement_monitor(): while True: transaction = get_latest_transaction() if transaction.type == 'in': yield f"Restok: {transaction.product} (+{transaction.quantity})" elif transaction.type == 'out': yield f"Pengurangan: {transaction.product} (-{transaction.quantity})" for movement in stock_movement_monitor(): print(movement)
  1. Production dan Quality Management:
python
# List Comprehension: Mengidentifikasi produk cacat defective_products = [product for product in production_batch if not product.passes_quality_check()] # Generator: Memantau efisiensi produksi def production_efficiency_monitor(): while True: batch = get_latest_production_batch() efficiency = batch.output / batch.input yield f"Efisiensi Batch {batch.id}: {efficiency * 100:.2f}%" for efficiency_report in production_efficiency_monitor(): print(efficiency_report)
  1. Logistik:
python
# List Comprehension: Mengidentifikasi pengiriman yang terlambat late_deliveries = [delivery for delivery in active_deliveries if delivery.is_late()] # Generator: Memantau status pengiriman def delivery_status_tracker(): for delivery in active_deliveries: while not delivery.is_completed(): yield f"Pengiriman {delivery.id}: {delivery.current_status}" time.sleep(3600) # Cek setiap jam for status_update in delivery_status_tracker(): print(status_update)
  1. Fintech dan Perbankan:
python
# List Comprehension: Mengidentifikasi transaksi mencurigakan suspicious_transactions = [tx for tx in daily_transactions if tx.amount > 10000 and tx.country != 'Indonesia'] # Generator: Memantau fluktuasi mata uang def currency_fluctuation_monitor(): base_rate = get_current_exchange_rate('USD', 'IDR') while True: current_rate = get_current_exchange_rate('USD', 'IDR') change = (current_rate - base_rate) / base_rate * 100 yield f"Perubahan USD/IDR: {change:.2f}%" time.sleep(300) # Cek setiap 5 menit for rate_change in currency_fluctuation_monitor(): print(rate_change)
  1. E-commerce:
python
# List Comprehension: Membuat daftar rekomendasi produk recommended_products = [product for product in catalog if product.category in user.interests] # Generator: Memantau tren pencarian def search_trend_monitor(): while True: trending_searches = get_trending_searches(last_hour=1) yield f"Tren Pencarian Terkini: {', '.join(trending_searches)}" time.sleep(3600) # Update setiap jam for trend_update in search_trend_monitor(): print(trend_update)
  1. Asuransi:
python

# List Comprehension: Mengidentifikasi polis yang akan kedaluwarsa expiring_policies = [policy for policy in active_policies if (policy.expiry_date - datetime.now()).days < 30] # Generator: Menghitung premi berdasarkan profil risiko def premium_calculator(): for customer in new_customers: risk_score = calculate_risk_score(customer) premium = base_premium * risk_score yield f"Premi untuk {customer.name}: Rp{premium:,.2f}" for premium_quote in premium_calculator(): print(premium_quote)
  1. Maintenance:
python

# List Comprehension: Mengidentifikasi peralatan yang memerlukan perawatan maintenance_needed = [equipment for equipment in all_equipment if equipment.hours_since_last_maintenance > 1000] # Generator: Menjadwalkan perawatan rutin def maintenance_scheduler(): for equipment in all_equipment: next_maintenance = equipment.last_maintenance + timedelta(days=90) while True: yield f"Jadwal perawatan untuk {equipment.name}: {next_maintenance}" next_maintenance += timedelta(days=90) for maintenance_schedule in maintenance_scheduler(): print(maintenance_schedule)
  1. Project Management:
python

# List Comprehension: Mengidentifikasi tugas yang terlambat overdue_tasks = [task for task in project_tasks if task.deadline < datetime.now() and not task.is_completed] # Generator: Memantau kemajuan proyek def project_progress_monitor(): while project.status != 'Completed': completed_tasks = sum(1 for task in project_tasks if task.is_completed) progress = completed_tasks / len(project_tasks) * 100 yield f"Kemajuan Proyek: {progress:.2f}%" time.sleep(86400) # Update setiap hari for progress_update in project_progress_monitor(): print(progress_update)
  1. Administrasi:
python

# List Comprehension: Memfilter dokumen yang memerlukan persetujuan pending_approvals = [doc for doc in all_documents if doc.status == 'Pending Approval'] # Generator: Memantau alur kerja dokumen def document_workflow_tracker(): for document in new_documents: while document.status != 'Archived': yield f"Dokumen {document.id}: {document.status}" time.sleep(3600) # Cek setiap jam for doc_status in document_workflow_tracker(): print(doc_status)
  1. Travel:
python
# List Comprehension: Memfilter penerbangan dengan harga promo promo_flights = [flight for flight in available_flights if flight.has_promo_price()] # Generator: Memantau perubahan harga tiket def ticket_price_monitor(route, date): while date > datetime.now(): current_price = get_current_price(route, date) yield f"Harga terkini untuk {route} pada {date}: Rp{current_price:,.2f}" time.sleep(3600) # Cek setiap jam for price_update in ticket_price_monitor("Jakarta-Bali", datetime(2024, 12, 25)): print(price_update)

Contoh-contoh di atas menunjukkan bagaimana List Comprehension dan Generators dapat digunakan untuk membuat kode yang efisien dan mudah dibaca dalam berbagai skenario industri. List Comprehension sangat berguna untuk membuat list baru berdasarkan kondisi tertentu, sementara Generators sangat efektif untuk memproses data dalam jumlah besar atau untuk membuat sequence yang tak terbatas tanpa menghabiskan banyak memori.

Penggunaan fitur-fitur ini dapat meningkatkan performa dan keterbacaan kode, terutama ketika berurusan dengan dataset besar atau operasi yang memerlukan pemrosesan berurutan.


More Examples in Various Industries:

List 

. Inventory Management:

python
# Filter low-stock items low_stock_items = [item for item in inventory if item.quantity < item.reorder_point] # Calculate total value of inventory inventory_value = sum(item.quantity * item.price for item in inventory)

b. Production Planning:

python
# Identify products that need to be manufactured to_manufacture = [product for product in product_list if product.stock < product.min_stock] # Calculate required raw materials required_materials = {material: sum(product.bill_of_materials[material] for product in to_manufacture) for material in set.union(*(product.bill_of_materials.keys() for product in to_manufacture))}

c. Warehouse and Logistics:

python
# Find available storage locations for a new shipment available_locations = [loc for loc in storage_locations if loc.is_empty and loc.size >= shipment.size] # Calculate total weight of outgoing shipments total_outgoing_weight = sum(shipment.weight for shipment in outgoing_shipments)

d. FinTech:

python
# Filter transactions above a certain amount large_transactions = [tx for tx in transactions if tx.amount > 10000] # Calculate total fees for each transaction type fees_by_type = {tx_type: sum(tx.fee for tx in transactions if tx.type == tx_type) for tx_type in set(tx.type for tx in transactions)}

e. Banking:

python
# Identify high-value customers high_value_customers = [customer for customer in customers if customer.account_balance > 1000000] # Calculate total loans by type loans_by_type = {loan_type: sum(loan.amount for loan in loans if loan.type == loan_type) for loan_type in set(loan.type for loan in loans)}

f. E-commerce:

python
# Filter products on sale sale_products = [product for product in catalog if product.is_on_sale] # Calculate average rating for each product category avg_ratings = {category: sum(product.rating for product in catalog if product.category == category) / sum(1 for product in catalog if product.category == category) for category in set(product.category for product in catalog)}


Generators

 Insurance and Risk Management:

python
def risk_assessment_generator(policies): for policy in policies: risk_score = calculate_risk_score(policy) yield (policy.id, risk_score) # Usage for policy_id, risk_score in risk_assessment_generator(active_policies): update_policy_premium(policy_id, risk_score)

b. Maintenance and Asset Management:

python
def maintenance_schedule_generator(assets): while True: for asset in assets: next_maintenance = asset.last_maintenance + asset.maintenance_interval if next_maintenance <= datetime.now(): yield (asset, next_maintenance) yield None # Indicates end of cycle time.sleep(86400) # Wait for a day before next cycle # Usage for asset, maintenance_date in maintenance_schedule_generator(company_assets): if asset is None: print("Daily maintenance cycle completed") else: schedule_maintenance(asset, maintenance_date)

c. Project Management:

python
def task_deadline_monitor(projects): while True: for project in projects: for task in project.tasks: if task.deadline < datetime.now() and not task.is_completed: yield (project, task) time.sleep(3600) # Check every hour # Usage for project, overdue_task in task_deadline_monitor(active_projects): send_notification(project.manager, f"Overdue task in {project.name}: {overdue_task.name}")

d. Quality Management:

python
def quality_control_sample_generator(production_line): while production_line.is_active: batch = production_line.current_batch sample_size = calculate_sample_size(batch.size) for _ in range(sample_size): yield batch.get_random_item() yield None # Indicates end of batch time.sleep(batch.production_time) # Usage for item in quality_control_sample_generator(assembly_line_1): if item is None: print("Batch quality control completed") else: perform_quality_check(item)

e. Administrative and Office Automation:

python
def document_approval_workflow(documents): for document in documents: current_approver = document.first_approver while current_approver: yield (document, current_approver) if current_approver.approve(document): current_approver = current_approver.next_approver else: break if not current_approver: yield (document, 'Fully Approved') # Usage for document, status in document_approval_workflow(pending_documents): if status == 'Fully Approved': finalize_document(document) else: notify_approver(status, document)

f. Travel and Hospitality Management:

python
def room_availability_checker(hotel): while True: date = datetime.now().date() for _ in range(365): # Check for the next year available_rooms = [room for room in hotel.rooms if room.is_available(date)] yield (date, available_rooms) date += timedelta(days=1) time.sleep(86400) # Update daily # Usage for date, available_rooms in room_availability_checker(seaside_hotel): update_booking_system(date, available_rooms) if len(available_rooms) < 5: send_alert("Low room availability on " + str(date))


Implementation List in Various Industries

1. Inventory Management

Use Case: Extracting items with low stock

python

inventory = [
    {"item": "Apples", "quantity": 50},
    {"item": "Bananas", "quantity": 150},
    {"item": "Oranges", "quantity": 30}
]

low_stock_items = [item["item"] for item in inventory if item["quantity"] < 100]
print(low_stock_items)  # Output: ['Apples', 'Oranges']

2. Production Planning and Optimization

Use Case: Identifying overdue production tasks

python
tasks = [
    {"task": "Task 1", "due_date": "2023-06-01"},
    {"task": "Task 2", "due_date": "2023-05-15"},
    {"task": "Task 3", "due_date": "2023-06-10"}
]

from datetime import datetime

overdue_tasks = [task["task"] for task in tasks if datetime.strptime(task["due_date"], "%Y-%m-%d") < datetime.now()]
print(overdue_tasks)  # Output will depend on the current date

3. Warehouse and Logistics Management

Use Case: Filtering shipments delayed beyond a threshold

python
shipments = [
    {"id": "S1", "delay_days": 2},
    {"id": "S2", "delay_days": 5},
    {"id": "S3", "delay_days": 1}
]

delayed_shipments = [shipment["id"] for shipment in shipments if shipment["delay_days"] > 3]
print(delayed_shipments)  # Output: ['S2']

4. Financial Technology (FinTech) Solutions

Use Case: Adjusting interest rates for high-balance accounts

python
accounts = [
    {"account": "A1", "balance": 5000},
    {"account": "A2", "balance": 15000},
    {"account": "A3", "balance": 25000}
]

adjusted_balances = [account["balance"] * 1.02 for account in accounts if account["balance"] > 10000]
print(adjusted_balances)  # Output: [15300.0, 25500.0]


Implementation Generator dalam Various Industries

1. Inventory Management

Use Case: Streaming large inventory data

python
def inventory_generator(items):
    for item in items:
        yield item

large_inventory = ({"item": f"Item {i}", "quantity": i * 10} for i in range(10000))

for item in inventory_generator(large_inventory):
    if item["quantity"] < 500:
        print(item)

2. Production Planning and Optimization

Use Case: Real-time task status updates

python
import time

def task_status_generator(tasks):
    for task in tasks:
        time.sleep(1)  # Simulate delay
        yield task

tasks = [{"task": f"Task {i}", "status": "completed"} for i in range(5)]

for status in task_status_generator(tasks):
    print(status)

3. Warehouse and Logistics Management

Use Case: Generating shipment data for tracking

python
import random

def shipment_generator(num_shipments):
    for i in range(num_shipments):
        yield {"id": f"S{i}", "location": random.choice(["New York", "Los Angeles", "Chicago"])}

for shipment in shipment_generator(5):
    print(shipment)

4. Financial Technology (FinTech) Solutions

Use Case: Streaming transaction records for fraud detection

python
import random

def transaction_generator(num_transactions):
    for i in range(num_transactions):
        yield {"transaction_id": f"T{i}", "amount": random.uniform(10.0, 1000.0)}

for transaction in transaction_generator(10):
    if transaction["amount"] > 900:
        print(f"High value transaction detected: {transaction}")


Kedua pemahaman List dan Generator adalah alat yang kuat di Python untuk manipulasi data dan iterasi, menawarkan sintaks yang ringkas dan kinerja yang ditingkatkan. Dengan memanfaatkan konsep-konsep canggih ini, berbagai industri dapat meningkatkan efisiensi, produktivitas, dan kemampuan pengambilan keputusan aplikasi mereka. Alat-alat ini sangat berguna dalam skenario yang melibatkan set data besar dan pemrosesan data real-time, seperti manajemen inventori, perencanaan produksi, logistik, dan solusi FinTech.


Comments

Popular posts from this blog

create image slider using phyton in web

Tahukah kamu Algoritma Genetika dan Penerapannya dalam Industri

create animated futuristic profile card using html+css+js

CRUD SPRING REACTIVE WEBFLUX +Mongo DB

Top 7 Digital Transformation Companies

100 perusahaan perangkat lunak (software) populer dari Eropa dan Amerika yang memiliki kehadiran atau operasional di Indonesia.

TOP 8 Framework Populer menggunakan bahasa .NET

Python Date and Time Manipulation

TOP 5 Trends Programming 2024

Daftar Kata Kunci (Keyword) dalam Bahasa Pemrograman Python