Automatically translated.View original post

🐍 Daily Python Problem: Frequency Count

Today's problem is to write a count _ frequency function that converts a list into a Dictionary to summarize how many times each item appears (frequency count)!

📝 Problem & Task:

Get the list and return the Dictionary. Key is the list and Value is the number of times it appears.

💡 3 different ways to count frequencies in Python!

1.Basic (Use Loop + If / Else) - Practice Logic! 🧱

• Create a blank judgment

• Loop, see if that item has ever been in the judgment.

• If ever (if item in map): Add + 1

• If never (else): Create a new Key and default to 1

• This method helps to understand the workings of the judgment.

2.Pythonic (use .get () method) - Shorter code! ✨

• Use the .get method (key, default _ value)

• frequency _ map [item] = frequency _ map.get (item, 0) + 1

• If the item exists, the original value is added 1. If it does not exist, the default value 0 is added 1 (the key is created). If / else is not required.

3.Pro model (use collections Counter) - the fastest! ⭐

• Use standard modules, collections and Counter classes

• Just return Counter (items) is done!

• This method is the shortest, easiest to read, and fastest in practical use!

💖 Knowing how to solve a problem will make us choose the tool that best suits the situation! Keep going!

# python # Programming # data # ai # learnonlemon8

2025/11/5 Edited to

... Read moreนอกจากวิธีการนับความถี่ที่ได้แนะนำไปแล้ว การเลือกวิธีที่เหมาะสมกับบริบทโปรแกรมก็สำคัญมากครับ สำหรับโปรเจกต์หรือสคริปท์ขนาดเล็กที่เราอยากฝึกทักษะพื้นฐาน การใช้ Loop กับ if/else จะช่วยให้เข้าใจการทำงานภายในของ Dictionary อย่างลึกซึ้ง ส่วนถ้าต้องการโค้ดที่กระชับและอ่านง่ายขึ้น การใช้เมธอด .get() ก็ทำให้งานเขียนสะดวกกว่า โดยลดจำนวนบรรทัดและไม่ต้องเช็กเงื่อนไขมาก แต่ถ้าต้องทำงานกับข้อมูลขนาดใหญ่หรือเน้นประสิทธิภาพ Collections.Counter เป็นคำตอบ เพราะมันถูกออกแบบมาสำหรับงานนี้โดยเฉพาะและเร็วที่สุด ผมเองเคยลองใช้วิธี Pro กับข้อมูลที่มีรายการหลักพันขึ้นไป พบว่ามันช่วยประหยัดเวลาและทำโค้ดดูดีขึ้นมาก นอกจากนี้ การเข้าใจโจทย์และการเลือกเครื่องมือให้เหมาะสมก็ช่วยพัฒนาโค้ดให้มีประสิทธิภาพและทำงานได้ตรงตามความต้องการมากขึ้นครับ สุดท้าย อย่าลืมทดสอบฟังก์ชันของเรากับเคสต่าง ๆ ไม่ว่าจะเป็น List ว่าง, รายการซ้ำ หรือชนิดข้อมูลที่ไม่คาดคิด เพื่อให้มั่นใจว่าโปรแกรมทำงานได้อย่างถูกต้องและมีคุณภาพครับ