it

โจทย์เขียนโปรแกรมพร้อมเฉลย — ฝึกเขียน Code Python ฉบับสมบูรณ์

โจทย์เขียนโปรแกรมพร้อมเฉลย — ฝึกเขียน Code Python ฉบับสมบูรณ์

โจทย์เขียนโปรแกรม

โจทย์เขียนโปรแกรมพร้อมเฉลย — ฝึกเขียน Code Python ฉบับสมบูรณ์

โจทย์เขียนโปรแกรม Python เฉลย FizzBuzz Fibonacci Palindrome Sorting Searching Two Sum LeetCode Interview Algorithm OOP

ระดับโจทย์ตัวอย่างConceptLeetCode
EasyFizzBuzz Two Sum PalindromeLoop Condition HashMap#1 #9 #412
EasyValid Parentheses Reverse StringStack String Manipulation#20 #344
MediumLongest Substring 3SumSliding Window Two Pointers#3 #15
MediumBinary Tree Level OrderBFS Queue Tree#102
HardMerge k Sorted ListsHeap Divide and Conquer#23
HardTrapping Rain WaterTwo Pointers Stack#42

โจทย์พื้นฐาน + เฉลย

# === Basic Programming Problems ===





# 1. FizzBuzz


def fizzbuzz(n):


 for i in range(1, n + 1):


 if i % 15 == 0:


 print("FizzBuzz")


 elif i % 3 == 0:


 print("Fizz")


 elif i % 5 == 0:


 print("Buzz")


 else:


 print(i)





# 2. Factorial (Recursive)


def factorial(n):


 if n <= 1:


 return 1


 return n * factorial(n - 1)





# 3. Fibonacci


def fibonacci(n):


 fib = [0, 1]


 for i in range(2, n):


 fib.append(fib[i-1] + fib[i-2])


 return fib[:n]





# 4. Palindrome Check


def is_palindrome(s):


 s = s.lower().replace(" ", "")


 return s == s[::-1]





# 5. Prime Number Check


def is_prime(n):


 if n < 2:


 return False


 for i in range(2, int(n**0.5) + 1):


 if n % i == 0:


 return False


 return True





# 6. Binary Search


def binary_search(arr, target):


 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





# 7. GCD (Euclidean Algorithm)


def gcd(a, b):


 while b:


 a, b = b, a % b


 return a





# Test


print("FizzBuzz(15):")


fizzbuzz(15)


print(f"\nFactorial(5) = {factorial(5)}")


print(f"Fibonacci(10) = {fibonacci(10)}")


print(f"Palindrome('racecar') = {is_palindrome('racecar')}")


print(f"Prime(17) = {is_prime(17)}")


print(f"BinarySearch([1,3,5,7,9], 7) = {binary_search([1,3,5,7,9], 7)}")


print(f"GCD(12, 8) = {gcd(12, 8)}")

โจทย์ String + Algorithm

# === String & Algorithm Problems ===





# 1. Two Sum (LeetCode #1)


def two_sum(nums, target):


 seen = {}


 for i, num in enumerate(nums):


 complement = target - num


 if complement in seen:


 return [seen[complement], i]


 seen[num] = i


 return []





# 2. Valid Parentheses (LeetCode #20)


def is_valid_parentheses(s):


 stack = []


 mapping = {')': '(', ']': '[', '}': '{'}


 for char in s:


 if char in mapping:


 if not stack or stack[-1] != mapping[char]:


 return False


 stack.pop()


 else:


 stack.append(char)


 return len(stack) == 0





# 3. Anagram Check


def is_anagram(s1, s2):


 return sorted(s1.lower()) == sorted(s2.lower())





# 4. Caesar Cipher


def caesar_cipher(text, shift):


 result = []


 for char in text:


 if char.isalpha():


 base = ord('A') if char.isupper() else ord('a')


 result.append(chr((ord(char) - base + shift) % 26 + base))


 else:


 result.append(char)


 return ''.join(result)





# 5. Maximum Subarray (Kadane's Algorithm)


def max_subarray(nums):


 max_sum = current = nums[0]


 for num in nums[1:]:


 current = max(num, current + num)


 max_sum = max(max_sum, current)


 return max_sum





# 6. String Compression


def compress_string(s):


 if not s:


 return s


 result = []


 count = 1


 for i in range(1, len(s)):


 if s[i] == s[i-1]:


 count += 1


 else:


 result.append(s[i-1] + str(count))


 count = 1


 result.append(s[-1] + str(count))


 compressed = ''.join(result)


 return compressed if len(compressed) < len(s) else s





# Test


print(f"TwoSum([2,7,11,15], 9) = {two_sum([2,7,11,15], 9)}")


print(f"ValidParentheses('()[]{{}}') = {is_valid_parentheses('()[]{}')}")


print(f"Anagram('listen','silent') = {is_anagram('listen','silent')}")


print(f"Caesar('Hello', 3) = {caesar_cipher('Hello', 3)}")


print(f"MaxSubarray([-2,1,-3,4,-1,2,1,-5,4]) = {max_subarray([-2,1,-3,4,-1,2,1,-5,4])}")


print(f"Compress('aabbbcc') = {compress_string('aabbbcc')}")

โจทย์ OOP + Interview

# === OOP & Interview Problems ===





from dataclasses import dataclass





# 1. Stack Implementation


class Stack:


 def __init__(self):


 self.items = []


 


 def push(self, item):


 self.items.append(item)


 


 def pop(self):


 if self.is_empty():


 raise IndexError("Stack is empty")


 return self.items.pop()


 


 def peek(self):


 if self.is_empty():


 raise IndexError("Stack is empty")


 return self.items[-1]


 


 def is_empty(self):


 return len(self.items) == 0


 


 def size(self):


 return len(self.items)





# 2. Linked List


class ListNode:


 def __init__(self, val=0, next=None):


 self.val = val


 self.next = next





def reverse_linked_list(head):


 prev = None


 current = head


 while current:


 next_node = current.next


 current.next = prev


 prev = current


 current = next_node


 return prev





# 3. Interview Problem Tracker


@dataclass


class Problem:


 name: str


 difficulty: str


 category: str


 time_complexity: str


 key_concept: str





problems = [


 Problem("Two Sum", "Easy", "Array + HashMap",


 "O(n)", "HashMap Complement Lookup"),


 Problem("Valid Parentheses", "Easy", "Stack",


 "O(n)", "Stack LIFO Matching Pairs"),


 Problem("Merge Two Sorted Lists", "Easy", "Linked List",


 "O(n+m)", "Two Pointer Merge"),


 Problem("Maximum Subarray", "Medium", "Dynamic Programming",


 "O(n)", "Kadane's Algorithm Local/Global Max"),


 Problem("3Sum", "Medium", "Two Pointers",


 "O(n²)", "Sort + Two Pointer Skip Duplicates"),


 Problem("Longest Substring No Repeat", "Medium", "Sliding Window",


 "O(n)", "HashMap + Sliding Window"),


 Problem("Merge k Sorted Lists", "Hard", "Heap",


 "O(N log k)", "Min Heap Priority Queue"),


]





print("=== Interview Problems ===")


for p in problems:


 print(f" [{p.name}] {p.difficulty} | {p.category}")


 print(f" Time: {p.time_complexity} | Key: {p.key_concept}")





# Stack Test


s = Stack()


s.push(1); s.push(2); s.push(3)


print(f"\nStack: push 1,2,3 → peek={s.peek()} pop={s.pop()} size={s.size()}")

เคล็ดลับ

  • ฝึกทุกวัน: วันละ 1-2 ข้อ LeetCode สม่ำเสมอ
  • Pattern: เรียนรู้ Pattern Two Pointers Sliding Window BFS DFS DP
  • Brute Force: เริ่มจาก Brute Force ก่อน แล้ว Optimize
  • Edge Cases: ทดสอบ Empty Array Single Element Negative
  • Explain: พูดอธิบาย Thought Process ขณะ Code

Best Practices สำหรับนักพัฒนา

โจทย์เขียนโปรแกรมพร้อมเฉลย — ฝึกเขียน Code Python ฉบับสมบูรณ์

การเขียนโค้ดที่ดีไม่ใช่แค่ทำให้โปรแกรมทำงานได้ แต่ต้องเขียนให้อ่านง่าย ดูแลรักษาง่าย และ Scale ได้ หลัก SOLID Principles เป็นพื้นฐานสำคัญที่นักพัฒนาทุกคนควรเข้าใจ ได้แก่ Single Responsibility ที่แต่ละ Class ทำหน้าที่เดียว Open-Closed ที่เปิดให้ขยายแต่ปิดการแก้ไข Liskov Substitution ที่ Subclass ต้องใช้แทน Parent ได้ Interface Segregation ที่แยก Interface ให้เล็ก และ Dependency Inversion ที่พึ่งพา Abstraction ไม่ใช่ Implementation

อ่านเพิ่ม: Weights Biases Citizen Developer — ทุกสิ่งที่ต้องรู้ในปี 202 · อ่านเพิ่ม: กรุงศรี swift code — วิธีตั้งค่าและใช้งานจริงพร้อมตัวอย่าง · อ่านเพิ่ม: Whisper Speech Internal Developer Platform | SiamCafe Blog

เนื้อหาเกี่ยวข้อง — บทความที่เกี่ยวข้อง: Hugo Module Hybrid Cloud Setup

เรื่อง Testing ก็ขาดไม่ได้ ควรเขียน Unit Test ครอบคลุมอย่างน้อย 80% ของ Code Base ใช้ Integration Test ทดสอบการทำงานร่วมกันของ Module ต่างๆ และ E2E Test สำหรับ Critical User Flow เครื่องมือยอดนิยมเช่น Jest, Pytest, JUnit ช่วยให้การเขียน Test เป็นเรื่องง่าย

แนะนำเพิ่มเติม — บทวิเคราะห์จาก XM Signal

เรื่อง Version Control ด้วย Git ใช้ Branch Strategy ที่เหมาะกับทีม เช่น Git Flow สำหรับโปรเจคใหญ่ หรือ Trunk-Based Development สำหรับทีมที่ Deploy บ่อย ทำ Code Review ทุก Pull Request และใช้ CI/CD Pipeline ทำ Automated Testing และ Deployment

เนื้อหาเกี่ยวข้อง — แนะนำให้อ่าน Cloud-init Log Management ELK

โจทย์พื้นฐานมีอะไร

FizzBuzz Factorial Fibonacci Palindrome Prime Binary Search GCD Reverse String Sum Digits Temperature Loop Condition Function

โจทย์ String มีอะไร

Anagram Vowels Duplicates Caesar Cipher Longest Prefix Word Count Title Case Valid Parentheses Compress Palindrome Substring

แนะนำเพิ่มเติม — แหล่งความรู้ Forex iCafeForex

เนื้อหาเกี่ยวข้อง — แนะนำให้อ่าน Payload CMS Agile Scrum Kanban — จัดการ Content

โจทย์ Algorithm มีอะไร

Sorting Bubble Merge Quick Searching Binary Hash Two Sum Kadane Linked List Stack Queue Tree BFS DFS DP Sliding Window Two Pointers

โจทย์สัมภาษณ์งานเป็นอย่างไร

LeetCode Easy 100+ Medium 50+ Blind 75 NeetCode 150 STAR Method Clarification Brute Force Optimize Edge Cases Clean Code ฝึกทุกวัน

เนื้อหาเกี่ยวข้อง — ทำความเข้าใจ CSS Subgrid Monitoring และ Alerting — คู่มือฉบับสมบูรณ์ 2026

สรุป

โจทย์เขียนโปรแกรม Python FizzBuzz Two Sum Palindrome Sorting BFS DFS DP LeetCode Interview OOP Stack Linked List Algorithm

XM Legend · เทรดเดอร์ & ผู้สอน Forex 13 ปี

ผู้ก่อตั้ง SiamCafe ตั้งแต่ปี 1997 · เทรดเดอร์สาย Forex มากกว่า 13 ปี ได้รับการยกย่องเป็น XM Legend · แบ่งปันความรู้ Forex, ไอที, AI และการเทรด จากประสบการณ์จริงในตลาดจริง