ปัญหาพื้นฐานสำหรับปัญหายุ่งยากหลายอย่าง: หาจำนวนตัวเลขที่มากกว่าค่าที่กำหนดในลิสต์ พบได้บ่อยใน Python
ตัวอย่างโค้ด
1. ใช้ For Loop (เข้าใจง่าย)
test_list = [1, 7, 5, 6, 3, 8]
k = 4
print("The list :", str(test_list))
count = 0
for i in test_list:
if i > k:
count = count + 1
print("The numbers greater than 4 :", str(count))
2. ใช้ List Comprehension + len() (Pythonic)
test_list = [1, 7, 5, 6, 3, 8]
k = 4
print("The list :", str(test_list))
count = len([i for i in test_list if i > k])
print("The numbers greater than 4 :", str(count))
3. ใช้ sum() กับ Generator Expression (แนะนำ - Memory Efficient)
test_list = [1, 7, 5, 6, 3, 8]
k = 4
print("The list :", str(test_list))
# True = 1, False = 0 ใน Python
count = sum(i > k for i in test_list)
print("The numbers greater than 4 :", str(count))
ผลลัพธ์
The list : [1, 7, 5, 6, 3, 8]
The numbers greater than 4 : 4
สรุปและเปรียบเทียบ
| วิธี | Memory | Speed | Readability | แนะนำ |
|---|---|---|---|---|
| For loop | O(1) | ปานกลาง | สูงมาก | มือใหม่ |
| List comprehension + len() | O(n) | เร็ว | สูง | ทั่วไป |
| sum() + generator | O(1) | เร็วที่สุด | สูง | ✅ Best |
| filter() + len() | O(n) | ปานกลาง | ปานกลาง | - |
| numpy (array > k).sum() | O(n) | เร็วมาก (vectorized) | สูง | Data Science |
วิธีเพิ่มเติม
4. ใช้ filter()
count = len(list(filter(lambda x: x > k, test_list)))
5. ใช้ NumPy (สำหรับอาร์เรย์ใหญ่)
import numpy as np
arr = np.array([1, 7, 5, 6, 3, 8])
count = np.sum(arr > k) # หรือ (arr > k).sum()
6. ใช้ bisect (ถ้าลิสต์เรียงลำดับแล้ว - O(log n))
import bisect
sorted_list = sorted(test_list) # [1, 3, 5, 6, 7, 8]
# หาตำแหน่งแรกที่ > k
idx = bisect.bisect_right(sorted_list, k)
count = len(sorted_list) - idx
การขยาย: นับเงื่อนไขอื่นๆ
# น้อยกว่า k
sum(i < k for i in test_list)
# เท่ากับ k
sum(i == k for i in test_list)
# อยู่ในช่วง [a, b]
sum(a <= i <= b for i in test_list)
# เลขคู่/คี่
sum(i % 2 == 0 for i in test_list)