Logic พื้นฐานสำหรับการเขียนโปรแกรม
Logic เป็นพื้นฐานที่สำคัญที่สุดของการเขียนโปรแกรม ไม่ว่าจะเขียนภาษาอะไร Python, JavaScript, Java, C++ ทุกภาษาใช้ Logic เหมือนกัน Boolean Logic, Conditional, Loop, Function
การฝึก Logic ต้องฝึกคิดเป็นขั้นตอน แบ่งปัญหาใหญ่เป็นปัญหาย่อย เขียน Pseudocode ก่อนเขียน Code จริง ฝึกแก้ปัญหาทุกวันบน LeetCode หรือ HackerRank
| หัวข้อ | คำอธิบาย | ตัวอย่าง |
|---|---|---|
| Boolean | True/False | is_logged_in = True |
| Comparison | เปรียบเทียบค่า | age >= 18 |
| Logical AND | ทั้งสองจริง | age >= 18 and has_id |
| Logical OR | อย่างน้อยหนึ่งจริง | is_admin or is_owner |
| Logical NOT | กลับค่า | not is_banned |
| If/Else | เงื่อนไข | if score >= 50: pass |
| Loop | ทำซ้ำ | for i in range(10) |
ตัวอย่าง Logic พื้นฐาน
# logic_basics.py — ตัวอย่าง Logic พื้นฐาน
# === 1. Boolean Logic ===
age = 25
has_id = True
is_student = False
# AND — ทั้งสองต้องจริง
can_enter = age >= 18 and has_id
print(f"Can enter: {can_enter}") # True
# OR — อย่างน้อยหนึ่งจริง
gets_discount = is_student or age >= 60
print(f"Gets discount: {gets_discount}") # False
# NOT — กลับค่า
is_adult = not (age < 18)
print(f"Is adult: {is_adult}") # True
# === 2. Conditional (if/elif/else) ===
def grade_calculator(score):
"""คำนวณเกรดจากคะแนน"""
if score >= 80:
return "A"
elif score >= 70:
return "B"
elif score >= 60:
return "C"
elif score >= 50:
return "D"
else:
return "F"
scores = [95, 72, 55, 48, 83]
for s in scores:
print(f" Score {s}: Grade {grade_calculator(s)}")
# === 3. Loops ===
# For Loop — นับจำนวนเลขคู่
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_count = 0
for num in numbers:
if num % 2 == 0:
even_count += 1
print(f"\nEven numbers: {even_count}")
# While Loop — หาค่า Factorial
def factorial(n):
result = 1
while n > 1:
result *= n
n -= 1
return result
print(f"5! = {factorial(5)}") # 120
# === 4. FizzBuzz (Classic Logic Problem) ===
print("\nFizzBuzz:")
for i in range(1, 21):
if i % 3 == 0 and i % 5 == 0:
print(f" {i}: FizzBuzz")
elif i % 3 == 0:
print(f" {i}: Fizz")
elif i % 5 == 0:
print(f" {i}: Buzz")
else:
print(f" {i}: {i}")
# === 5. Pattern Matching ===
def is_palindrome(text):
"""ตรวจสอบ Palindrome"""
clean = text.lower().replace(" ", "")
return clean == clean[::-1]
words = ["racecar", "hello", "madam", "python", "level"]
for w in words:
print(f" '{w}' is palindrome: {is_palindrome(w)}")
# === 6. Recursion ===
def fibonacci(n):
"""Fibonacci ด้วย Recursion"""
if n <= 1:
return n
return fibonacci(n - 1) + fibonacci(n - 2)
print(f"\nFibonacci: {[fibonacci(i) for i in range(10)]}")
Algorithms และ Data Structures
# algorithms.py — Algorithms พื้นฐาน
# === 1. Binary Search ===
def binary_search(arr, target):
"""ค้นหาใน Sorted Array — O(log n)"""
left, right = 0, len(arr) - 1
while left <= right:
mid = (left + right) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1 # ไม่พบ
sorted_list = [2, 5, 8, 12, 16, 23, 38, 56, 72, 91]
print(f"Search 23: index {binary_search(sorted_list, 23)}") # 5
print(f"Search 50: index {binary_search(sorted_list, 50)}") # -1
# === 2. Sorting Algorithms ===
def bubble_sort(arr):
"""Bubble Sort — O(n^2)"""
n = len(arr)
for i in range(n):
swapped = False
for j in range(0, n - i - 1):
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
swapped = True
if not swapped:
break
return arr
def quick_sort(arr):
"""Quick Sort — O(n log n) average"""
if len(arr) <= 1:
return arr
pivot = arr[len(arr) // 2]
left = [x for x in arr if x < pivot]
middle = [x for x in arr if x == pivot]
right = [x for x in arr if x > pivot]
return quick_sort(left) + middle + quick_sort(right)
data = [64, 34, 25, 12, 22, 11, 90]
print(f"\nOriginal: {data}")
print(f"Bubble Sort: {bubble_sort(data.copy())}")
print(f"Quick Sort: {quick_sort(data.copy())}")
# === 3. Stack และ Queue ===
class Stack:
"""Stack — LIFO (Last In First Out)"""
def __init__(self):
self.items = []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop() if self.items else None
def peek(self):
return self.items[-1] if self.items else None
def is_empty(self):
return len(self.items) == 0
def size(self):
return len(self.items)
# ตัวอย่าง: ตรวจสอบ Balanced Brackets
def is_balanced(expression):
"""ตรวจสอบวงเล็บสมดุล"""
stack = Stack()
pairs = {')': '(', ']': '[', '}': '{'}
for char in expression:
if char in '([{':
stack.push(char)
elif char in ')]}':
if stack.is_empty() or stack.pop() != pairs[char]:
return False
return stack.is_empty()
expressions = ["(())", "([{}])", "(()", "({[}])", "()[]{}"]
for expr in expressions:
print(f" '{expr}' balanced: {is_balanced(expr)}")
# === 4. Hash Map (Dictionary) ===
def two_sum(nums, target):
"""หา 2 ตัวเลขที่รวมกันได้ target — O(n)"""
seen = {}
for i, num in enumerate(nums):
complement = target - num
if complement in seen:
return [seen[complement], i]
seen[num] = i
return []
print(f"\nTwo Sum [2,7,11,15] target=9: {two_sum([2, 7, 11, 15], 9)}")
print(f"Two Sum [3,2,4] target=6: {two_sum([3, 2, 4], 6)}")
Flowchart และ Pseudocode
# flowchart_pseudocode.py — Flowchart และ Pseudocode
# === Pseudocode สำหรับ ATM System ===
"""
PSEUDOCODE: ATM Withdrawal
1. START
2. INPUT pin
3. IF pin is correct THEN
4. DISPLAY balance
5. INPUT withdrawal_amount
6. IF withdrawal_amount <= balance THEN
7. IF withdrawal_amount % 100 == 0 THEN
8. balance = balance - withdrawal_amount
9. DISPENSE cash
10. DISPLAY "Transaction successful"
11. DISPLAY new balance
12. ELSE
13. DISPLAY "Amount must be multiple of 100"
14. ENDIF
15. ELSE
16. DISPLAY "Insufficient balance"
17. ENDIF
18. ELSE
19. attempts = attempts + 1
20. IF attempts >= 3 THEN
21. LOCK card
22. DISPLAY "Card locked"
23. ELSE
24. DISPLAY "Wrong PIN, try again"
25. ENDIF
26. ENDIF
27. END
"""
class ATM:
"""ATM System ตาม Pseudocode"""
def __init__(self):
self.accounts = {
"1234": {"pin": "0000", "balance": 50000},
"5678": {"pin": "1111", "balance": 120000},
}
self.attempts = {}
def authenticate(self, card_number, pin):
if card_number not in self.accounts:
return False, "Card not found"
if self.attempts.get(card_number, 0) >= 3:
return False, "Card locked"
if self.accounts[card_number]["pin"] != pin:
self.attempts[card_number] = self.attempts.get(card_number, 0) + 1
remaining = 3 - self.attempts[card_number]
if remaining <= 0:
return False, "Card locked after 3 attempts"
return False, f"Wrong PIN ({remaining} attempts left)"
self.attempts[card_number] = 0
return True, "Authenticated"
def check_balance(self, card_number):
return self.accounts[card_number]["balance"]
def withdraw(self, card_number, amount):
if amount % 100 != 0:
return False, "Amount must be multiple of 100"
balance = self.accounts[card_number]["balance"]
if amount > balance:
return False, f"Insufficient balance ({balance})"
self.accounts[card_number]["balance"] -= amount
new_balance = self.accounts[card_number]["balance"]
return True, f"Withdrew {amount}. New balance: {new_balance}"
# ทดสอบ
atm = ATM()
# Login สำเร็จ
ok, msg = atm.authenticate("1234", "0000")
print(f"Login: {msg}")
if ok:
balance = atm.check_balance("1234")
print(f"Balance: {balance}")
ok, msg = atm.withdraw("1234", 5000)
print(f"Withdraw: {msg}")
ok, msg = atm.withdraw("1234", 100000)
print(f"Withdraw: {msg}")
# Login ผิด
print()
for i in range(4):
ok, msg = atm.authenticate("5678", "9999")
print(f"Attempt {i+1}: {msg}")
# === Practice Problems ===
problems = [
"FizzBuzz — พิมพ์ 1-100, หาร 3 ลงตัว=Fizz, 5=Buzz, ทั้งสอง=FizzBuzz",
"Palindrome Check — ตรวจสอบคำอ่านกลับได้",
"Two Sum — หา 2 ตัวเลขรวมเท่ากับ Target",
"Balanced Brackets — ตรวจวงเล็บสมดุล",
"Fibonacci — หาลำดับ Fibonacci ตัวที่ N",
"Binary Search — ค้นหาใน Sorted Array",
"Reverse String — กลับข้อความ",
"Count Vowels — นับสระในข้อความ",
"Find Max/Min — หาค่ามากสุดน้อยสุดใน Array",
"Remove Duplicates — ลบค่าซ้ำใน Array",
]
print("\nPractice Problems:")
for i, p in enumerate(problems, 1):
print(f" {i}. {p}")
เคล็ดลับ
- คิดก่อนเขียน: เขียน Pseudocode หรือวาด Flowchart ก่อนเขียน Code จริง
- แบ่งปัญหา: แบ่งปัญหาใหญ่เป็นปัญหาย่อยๆ แก้ทีละขั้นตอน
- ฝึกทุกวัน: แก้ปัญหาบน LeetCode, HackerRank อย่างน้อยวันละ 1 ข้อ
- Debug ด้วย Print: ใช้ print() ดูค่าตัวแปรแต่ละขั้นตอน หาจุดที่ผิด
- เรียนรู้ Pattern: จำ Pattern เช่น Two Pointers, Sliding Window, BFS/DFS
- อ่าน Code คนอื่น: ดู Solution ของคนอื่นเรียนรู้วิธีคิดที่ต่างกัน
Best Practices สำหรับนักพัฒนา
การเขียนโค้ดที่ดีไม่ใช่แค่ทำให้โปรแกรมทำงานได้ แต่ต้องเขียนให้อ่านง่าย ดูแลรักษาง่าย และ Scale ได้ หลัก SOLID Principles เป็นพื้นฐานสำคัญที่นักพัฒนาทุกู้คืนควรเข้าใจ ได้แก่ Single Responsibility ที่แต่ละ Class ทำหน้าที่เดียว Open-Closed ที่เปิดให้ขยายแต่ปิดการแก้ไข Liskov Substitution ที่ Subclass ต้องใช้แทน Parent ได้ Interface Segregation ที่แยก Interface ให้เล็ก และ Dependency Inversion ที่พึ่งพา Abstraction ไม่ใช่ Implementation
เรื่อง Testing ก็ขาดไม่ได้ ควรเขียน Unit Test ครอบคลุมอย่างน้อย 80% ของ Code Base ใช้ Integration Test ทดสอบการทำงานร่วมกันของ Module ต่างๆ และ E2E Test สำหรับ Critical User Flow เครื่องมือยอดนิยมเช่น Jest, Pytest, JUnit ช่วยให้การเขียน Test เป็นเรื่องง่าย
เรื่อง Version Control ด้วย Git ใช้ Branch Strategy ที่เหมาะกับทีม เช่น Git Flow สำหรับโปรเจคใหญ่ หรือ Trunk-Based Development สำหรับทีมที่ Deploy บ่อย ทำ Code Review ทุก Pull Request และใช้ CI/CD Pipeline ทำ Automated Testing และ Deployment
Logic ในการเขียนโปรแกรมคืออะไร
กระบวนการคิดอย่างเป็นระบบแก้ปัญหา ใช้ Boolean Logic Conditional Loops Functions แบ่งปัญหาใหญ่เป็นย่อย คิดเป็นขั้นตอน Algorithm ทำซ้ำได้ตรวจสอบได้
Boolean Logic คืออะไร
ระบบตรรกะมี 2 ค่า True False ใช้ AND (ทั้งสองจริง) OR (อย่างน้อยหนึ่งจริง) NOT (กลับค่า) พื้นฐาน Computer Science ตั้งแต่ Circuit Design ถึง Database Queries
Algorithm คืออะไร
ชุดขั้นตอนชัดเจนแก้ปัญหา มี Input Output ขั้นตอนกำหนดไว้ จบการทำงานได้ เช่น Binary Search หาข้อมูล Bubble Sort เรียงลำดับ BFS/DFS ค้นหา Graph
เริ่มต้นฝึก Logic เขียนโปรแกรมอย่างไร
เริ่มจากปัญหาง่าย FizzBuzz Fibonacci Palindrome ฝึกบน LeetCode HackerRank Codewars เรียน Flowchart Pseudocode แก้ปัญหาทุกวัน Logic ดีขึ้นเอง
สรุป
Logic เป็นพื้นฐานสำคัญของการเขียนโปรแกรม ฝึก Boolean Logic Conditional Loop Function Algorithm Data Structures เริ่มจากปัญหาง่ายๆ เขียน Pseudocode ก่อน Code จริง ฝึกทุกวันบน LeetCode Debug ด้วย Print เรียนรู้ Pattern จำ Solution
