เส้นโค้งการเรียนรู้ของ Python: จาก Python Newbie ถึง Pro
การแนะนำ:
Python เป็นหนึ่งในภาษาโปรแกรมที่หลากหลายและใช้กันอย่างแพร่หลายมากที่สุดในโลก เป็นที่รู้จักในด้านความเรียบง่าย อ่านง่าย และมีความสามารถรอบด้าน ในบทความนี้ เราจะสำรวจชุดตัวอย่างสถานการณ์ที่โค้ดถูกพัฒนาโดยโปรแกรมเมอร์ที่มีความเชี่ยวชาญสามระดับที่แตกต่างกัน ได้แก่ ระดับเริ่มต้น ระดับกลาง และระดับผู้เชี่ยวชาญ
โดยทั่วไปแล้วระดับกลางและผู้เชี่ยวชาญจะใช้สิ่งต่อไปนี้:
- ความเข้าใจในรายการ:วิธีที่กระชับในการสร้างรายการด้วยโค้ดบรรทัดเดียว
squares = [x**2 for x in range(1, 6)]
print(squares)
# Output: [1, 4, 9, 16, 25]
squares_dict = {x: x**2 for x in range(1, 6)}
print(squares_dict)
# Output: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
nums = [1, 2, 3, 4, 5]
doubles = list(map(lambda x: x * 2, nums))
print(doubles) # Output: [2, 4, 6, 8, 10]
def greet_decorator(func):
def wrapper():
print("Hello!")
func()
print("Welcome!")
return wrapper
@greet_decorator
def greet_name():
print("John")
greet_name()
# Output:
# Hello!
# John
# Welcome!
with open("file.txt", "r") as file:
content = file.read()
print(content)
from typing import List
def sum_elements(elements: List[int]) -> int:
return sum(elements)
result = sum_elements([1, 2, 3, 4, 5])
print(result) # Output: 15
def fibonacci_gen(n: int):
a, b = 0, 1
for _ in range(n):
yield a
a, b = b, a + b
for num in fibonacci_gen(5):
print(num, end=" ")
# Output: 0 1 1 2 3
import re
text = "The email addresses are [email protected] and [email protected]"
pattern = r"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b"
emails = re.findall(pattern, text)
print(emails) # Output: ['[email protected]', '[email protected]']
try:
result = 10 / 0
except ZeroDivisionError as e:
print(f"An error occurred: {e}")
# Output: An error occurred: division by zero
# Importing the 'math' module and using its 'sqrt' function
import math
sqrt_result = math.sqrt(25)
print(sqrt_result) # Output: 5.0
import threading
def print_square(num):
print(f"Square: {num * num}")
def print_cube(num):
print(f"Cube: {num * num * num}")
thread1 = threading.Thread(target=print_square, args=(4,))
thread2 = threading.Thread(target=print_cube, args=(4,))
thread1.start()
thread2.start()
thread1.join()
thread2.join()
# Output:
# Square: 16
# Cube: 64
# Built-in functions
numbers = [2, 4, 1, 6, 3, 8, 5, 7]
max_num = max(numbers) # Find the maximum number in the list
min_num = min(numbers) # Find the minimum number in the list
sorted_nums = sorted(numbers) # Sort the list in ascending order
reversed_nums = list(reversed(numbers)) # Reverse the list
print("Maximum number:", max_num)
print("Minimum number:", min_num)
print("Sorted numbers:", sorted_nums)
print("Reversed numbers:", reversed_nums)
# Standard library modules
from collections import Counter
from itertools import combinations
# Counter (from collections module)
word = "mississippi"
counter = Counter(word) # Count the occurrences of each character
print("Character count:", counter)
# Combinations (from itertools module)
combos = list(combinations(numbers, 2)) # Find all combinations of size 2
print("Combinations of size 2:", combos)
# PEP 8 compliant code snippet
def calculate_area(radius):
"""Calculate the area of a circle given its radius.
Args:
radius (float): The radius of the circle.
Returns:
float: The area of the circle.
"""
pi = 3.14159
return pi * radius**2
def main():
# Collect user input for the radius
radius = float(input("Enter the radius of the circle: "))
# Calculate the area using the defined function
area = calculate_area(radius)
# Display the result with appropriate formatting
print(f"The area of the circle with radius {radius} is {area:.2f}")
if __name__ == "__main__":
main()
import unittest
def add_numbers(a, b):
return a + b
class TestAddition(unittest.TestCase):
def test_addition(self):
self.assertEqual(add_numbers(2, 3), 5)
if __name__ == '__main__':
unittest.main(argv=['first-arg-is-ignored'], exit=False)
# Output: .
# ----------------------------------------------------------------------
# Ran 1 test in 0.002s
#
# OK
เริ่มต้น:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
even_sum = 0
for num in numbers:
if num % 2 == 0:
even_sum += num
print("The sum of even numbers is:", even_sum)
- ตรวจสอบว่าตัวเลขกำลังใช้ตัวดำเนินการโมดูลัสหรือไม่
- บวกเลขคู่ให้กับตัวแปรผลรวม
def is_even(num):
return num % 2 == 0
def even_sum(numbers):
result = 0
for num in numbers:
if is_even(num):
result += num
return result
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
result = even_sum(numbers)
print("The sum of even numbers is:", result)
- สร้างฟังก์ชัน
even_sumคำนวณผลรวมของเลขคู่ - รหัสเป็นแบบแยกส่วนและง่ายต่อการบำรุงรักษา
def even_sum(numbers):
return sum(filter(lambda num: num % 2 == 0, numbers))
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
result = even_sum(numbers)
print("The sum of even numbers is:", result)
- ใช้ฟังก์ชันแลมบ์ดาเพื่อการกรองเลขคู่ที่รัดกุมและมีประสิทธิภาพ
- โค้ดมีขนาดกะทัดรัดมากขึ้น โดยใช้ประโยชน์จากความสามารถในการตั้งโปรแกรมเชิงฟังก์ชันของ Python
เริ่มต้น:
text = "hello world"
char_count = {}
for char in text:
if char in char_count:
char_count[char] += 1
else:
char_count[char] = 1
print("Character counts:", char_count)
#Character counts: {'h': 1, 'e': 1, 'l': 3, 'o': 2, ' ': 1, 'w': 1, 'r': 1, 'd': 1}
- ตรวจสอบว่ามีอักขระอยู่ในพจนานุกรมหรือไม่ และอัปเดตการนับตามนั้น
def count_characters(text):
char_count = {}
for char in text:
char_count[char] = char_count.get(char, 0) + 1
return char_count
text = "hello world"
result = count_characters(text)
print("Character counts:", result)
- ใช้
dict.get()วิธีการทำให้โค้ดง่ายขึ้น
from collections import Counter
def count_characters(text):
return Counter(text)
text = "hello world"
result = count_characters(text)
print("Character counts:", result)
- ใช้ประโยชน์จากในตัว
Counterเพื่อนับจำนวนอักขระที่เกิดขึ้นอย่างมีประสิทธิภาพ
เริ่มต้น:
numbers = [1, 2, 3, 4, 5]
total = 0
for num in numbers:
total += num
average = total / len(numbers)
print("The average is:", average)
- หารผลรวมตามความยาวของรายการเพื่อคำนวณค่าเฉลี่ย
def calculate_average(numbers):
return sum(numbers) / len(numbers)
numbers = [1, 2, 3, 4, 5]
average = calculate_average(numbers)
print("The average is:", average)
- ใช้ฟังก์ชันในตัว
sumเพื่อลดความซับซ้อนของโค้ด
from statistics import mean
def calculate_average(numbers):
return mean(numbers)
numbers = [1, 2, 3, 4, 5]
average = calculate_average(numbers)
print("The average is:", average)
- ใช้ประโยชน์จากฟังก์ชันในตัว
meanเพื่อคำนวณค่าเฉลี่ย
เริ่มต้น:
text = "hello"
reversed_text = ""
for char in text:
reversed_text = char + reversed_text
print("Reversed text:", reversed_text)
#text = "Hello"
#Reversed text: olleH
- เชื่อมต่ออักขระในลำดับที่ย้อนกลับเพื่อสร้างสตริงที่ย้อนกลับ
def reverse_string(text):
return "".join(reversed(text))
text = "hello"
reversed_text = reverse_string(text)
print("Reversed text:", reversed_text)
- ใช้
reversedฟังก์ชันและjoinเมธอดเพื่อย้อนกลับสตริง
def reverse_string(text):
return text[::-1]
text = "hello"
reversed_text = reverse_string(text)
print("Reversed text:", reversed_text)
5. การค้นหาจำนวนมากที่สุดในรายการ:
เริ่มต้น:
numbers = [1, 3, 7, 2, 5]
max_number = numbers[0]
for num in numbers:
if num > max_number:
max_number = num
print("The largest number is:", max_number)
#The largest number is: 7
- เปรียบเทียบแต่ละหมายเลขกับค่าสูงสุดปัจจุบันและอัปเดตค่าสูงสุดตามลำดับ
def find_max(numbers):
return max(numbers)
numbers = [1, 3, 7, 2, 5]
max_number = find_max(numbers)
print("The largest number is:", max_number)
- ใช้ฟังก์ชันในตัว
maxเพื่อค้นหาจำนวนสูงสุด
from functools import reduce
def find_max(numbers):
return reduce(lambda x, y: x if x > y else y, numbers)
numbers = [1, 3, 7, 2, 5]
max_number = find_max(numbers)
print("The largest number is:", max_number)
- ใช้ประโยชน์จาก
reduceฟังก์ชันด้วยฟังก์ชันแลมบ์ดาเพื่อค้นหาจำนวนสูงสุด
เริ่มต้น:
original_list = [1, 2, 3, 1, 2, 3, 4, 5]
unique_list = []
for item in original_list:
if item not in unique_list:
unique_list.append(item)
print("Unique list:", unique_list)
- ตรวจสอบว่ารายการใดไม่ได้อยู่ในรายการเฉพาะและต่อท้ายหากไม่มี
def remove_duplicates(items):
return list(set(items))
original_list = [1, 2, 3, 1, 2, 3, 4, 5]
unique_list = remove_duplicates(original_list)
print("Unique list:", unique_list)
- ใช้โครงสร้างข้อมูลในตัว
setเพื่อลบรายการที่ซ้ำกันและแปลงกลับเป็นรายการ
def remove_duplicates(items):
return list(dict.fromkeys(items))
original_list = [1, 2, 3, 1, 2, 3, 4, 5]
unique_list = remove_duplicates(original_list)
print("Unique list:", unique_list)
7. กำลังสองตัวเลขทั้งหมดในรายการ:
เริ่มต้น:
numbers = [1, 2, 3, 4, 5]
squared_numbers = []
for num in numbers:
squared_numbers.append(num ** 2)
print("Squared numbers:", squared_numbers)
#Squared numbers: [1, 4, 9, 16, 25]
- ผนวกกำลังสองของแต่ละตัวเลขเข้ากับรายการเลขยกกำลังสอง
def square_numbers(numbers):
return [num ** 2 for num in numbers]
numbers = [1, 2, 3, 4, 5]
squared_numbers = square_numbers(numbers)
print("Squared numbers:", squared_numbers)
- ใช้ความเข้าใจในรายการเพื่อสร้างรายการตัวเลขกำลังสอง
def square_numbers(numbers):
return list(map(lambda x: pow(x, 2), numbers))
numbers = [1, 2, 3, 4, 5]
squared_numbers = square_numbers(numbers)
print("Squared numbers:", squared_numbers)
Image by the Author
เริ่มต้น:
numbers = [1, 2, 3, 4, 5]
positions = 2
rotated_list = numbers[-positions:] + numbers[:-positions]
print("Rotated list:", rotated_list)
#Rotated list: [4, 5, 1, 2, 3]
ระดับกลาง:
def rotate_list(numbers, positions):
return numbers[-positions:] + numbers[:-positions]
numbers = [1, 2, 3, 4, 5]
positions = 2
rotated_list = rotate_list(numbers, positions)
print("Rotated list:", rotated_list)
- ใช้ไวยากรณ์การแบ่งส่วนของ Python เพื่อหมุนรายการตามจำนวนตำแหน่งที่ระบุ
from collections import deque
def rotate_list(numbers, positions):
rotated_numbers = deque(numbers)
rotated_numbers.rotate(positions)
return list(rotated_numbers)
numbers = [1, 2, 3, 4, 5]
positions = 2
rotated_list = rotate_list(numbers, positions)
print("Rotated list:", rotated_list)
- ใช้ประโยชน์จาก
dequeคลาสและrotateวิธีการในการหมุนเวียนรายการอย่างมีประสิทธิภาพตามจำนวนตำแหน่งที่ระบุ
เริ่มต้น:
list1 = [1, 2, 3, 4, 5]
list2 = [4, 5, 6, 7, 8]
common_elements = []
for num in list1:
if num in list2:
common_elements.append(num)
print("Common elements:", common_elements)
#Common elements: [4, 5]
- ตรวจสอบว่ามีองค์ประกอบอยู่ในรายการที่สองหรือไม่ และผนวกเข้ากับรายการองค์ประกอบทั่วไปหากพบ
def find_common_elements(list1, list2):
return [num for num in list1 if num in list2]
list1 = [1, 2, 3, 4, 5]
list2 = [4, 5, 6, 7, 8]
common_elements = find_common_elements(list1, list2)
print("Common elements:", common_elements)
- ใช้รายการความเข้าใจเพื่อสร้างรายการขององค์ประกอบทั่วไป
def find_common_elements(list1, list2):
return list(set(list1) & set(list2))
list1 = [1, 2, 3, 4, 5]
list2 = [4, 5, 6, 7, 8]
common_elements = find_common_elements(list1, list2)
print("Common elements:", common_elements)
- แปลงผลลัพธ์กลับเป็นรายการ
เริ่มต้น:
matrix = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
transposed_matrix = []
for i in range(len(matrix[0])):
transposed_row = []
for row in matrix:
transposed_row.append(row[i])
transposed_matrix.append(transposed_row)
print("Transposed matrix:", transposed_matrix)
- ต่อท้ายองค์ประกอบจากแต่ละแถวในเมทริกซ์เดิมเพื่อสร้างเมทริกซ์ที่ย้ายตำแหน่ง
def transpose_matrix(matrix):
return [[row[i] for row in matrix] for i in range(len(matrix[0]))]
matrix = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
transposed_matrix = transpose_matrix(matrix)
print("Transposed matrix:", transposed_matrix)
- ใช้ความเข้าใจในรายการที่ซ้อนกันเพื่อสร้างเมทริกซ์ทรานสโพส
def transpose_matrix(matrix):
return list(zip(*matrix))
matrix = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
transposed_matrix = transpose_matrix(matrix)
print("Transposed matrix:", transposed_matrix)
11. การตรวจสอบว่าสตริงเป็นพาลินโดรมหรือไม่:
เริ่มต้น:
string = "madam"
is_palindrome = True
for i in range(len(string) // 2):
if string[i] != string[-(i + 1)]:
is_palindrome = False
break
print(f"Is '{string}' a palindrome?:", is_palindrome)
#Is 'madam' a palindrome?: True
- เปรียบเทียบอักขระแต่ละตัวกับอักขระที่สอดคล้องกันจากส่วนท้ายของสตริง และตั้งค่า
is_palindromeเป็น False หากไม่ตรงกัน
def is_palindrome(string):
return string == string[::-1]
string = "madam"
result = is_palindrome(string)
print(f"Is '{string}' a palindrome?:", result)
- ใช้ไวยากรณ์การแบ่งส่วนของ Python เพื่อย้อนกลับสตริงและเปรียบเทียบกับสตริงดั้งเดิม
เริ่มต้น:
num = 60
prime_factors = []
for i in range(2, num + 1):
while num % i == 0:
prime_factors.append(i)
num = num // i
print("Prime factors:", prime_factors)
#Prime factors: [2, 2, 3, 5]
- ใช้ลูป while เพื่อหารจำนวนซ้ำด้วยตัวประกอบในขณะที่หารลงตัว
- ผนวกปัจจัยหลักเข้ากับรายการ
def prime_factors(num):
factors = []
for i in range(2, num + 1):
while num % i == 0:
factors.append(i)
num = num // i
return factors
num = 60
result = prime_factors(num)
print("Prime factors:", result)
- ใช้การวนซ้ำที่ซ้อนกันเพื่อระบุปัจจัยหลักและผนวกเข้ากับรายการ
def prime_factors(num):
factors = []
i = 2
while i * i <= num:
if num % i:
i += 1
else:
num //= i
factors.append(i)
if num > 1:
factors.append(num)
return factors
num = 60
result = prime_factors(num)
print("Prime factors:", result)
- ใช้การวนซ้ำแบบ while เพื่อหารจำนวนซ้ำด้วยตัวหารที่น้อยที่สุด
- ต่อท้ายปัจจัยเฉพาะในรายการและตรวจสอบว่าจำนวนที่เหลือมากกว่า 1 เพื่อพิจารณาปัจจัยสำคัญสุดท้ายหรือไม่
เริ่มต้น:
nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flat_list = []
for sublist in nested_list:
for item in sublist:
flat_list.append(item)
print("Flat list:", flat_list)
#Flat list: [1, 2, 3, 4, 5, 6, 7, 8, 9]
- ผนวกแต่ละรายการเข้ากับรายการแฟลตใหม่
def flatten_list(nested_list):
return [item for sublist in nested_list for item in sublist]
nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flat_list = flatten_list(nested_list)
print("Flat list:", flat_list)
- ใช้ความเข้าใจในรายการที่ซ้อนกันเพื่อสร้างรายการแบบแบน
from itertools import chain
def flatten_list(nested_list):
return list(chain.from_iterable(nested_list))
nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flat_list = flatten_list(nested_list)
print("Flat list:", flat_list)
- กำหนดฟังก์ชัน
flatten_listที่ใช้chain.from_iterableฟังก์ชันเพื่อแผ่รายการที่ซ้อนกัน
เริ่มต้น:
sentence = "apple banana apple kiwi banana apple"
word_count = {}
for word in sentence.split():
if word in word_count:
word_count[word] += 1
else:
word_count[word] = 1
print("Word count:", word_count)
- ใช้พื้นฐานสำหรับการวนซ้ำเพื่อวนซ้ำคำและนับจำนวนการเกิดขึ้นในพจนานุกรม
from collections import Counter
def count_words(sentence):
return Counter(sentence.split())
sentence = "apple banana apple kiwi banana apple"
word_count = count_words(sentence)
print("Word count:", word_count)
- กำหนดฟังก์ชัน
count_wordsที่ใช้Counterคลาสเพื่อนับความถี่ของคำในประโยค
from collections import defaultdict
def count_words(sentence):
word_count = defaultdict(int)
for word in sentence.split():
word_count[word] += 1
return word_count
sentence = "apple banana apple kiwi banana apple"
word_count = count_words(sentence)
print("Word count:", word_count)
- กำหนดฟังก์ชัน
count_wordsที่ใช้ defaultdict ด้วยค่าจำนวนเต็มเพื่อนับความถี่ของคำ - ใช้
splitวิธี tokenize ประโยคและ for วนซ้ำเพื่อเพิ่มจำนวนคำ
เริ่มต้น:
def merge_dicts(d1, d2):
merged_dict = d1.copy()
merged_dict.update(d2)
return merged_dict
dict1 = {'a': 1, 'b': 2, 'c': 3}
dict2 = {'d': 4, 'e': 5}
result = merge_dicts(dict1, dict2)
print("Merged dictionary:", result)
#Merged dictionary: {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
- ใช้
copyวิธีสร้างสำเนาของพจนานุกรมฉบับแรกและupdateวิธีปรับปรุงพจนานุกรมด้วยคู่คีย์-ค่าจากพจนานุกรมฉบับที่สอง
def merge_dicts(d1, d2):
return {**d1, **d2}
dict1 = {'a': 1, 'b': 2, 'c': 3}
dict2 = {'d': 4, 'e': 5}
result = merge_dicts(dict1, dict2)
print("Merged dictionary:", result)
- ใช้การเปิดพจนานุกรม (
**d1, **d2) เพื่อรวมพจนานุกรม
from collections import ChainMap
def merge_dicts(d1, d2):
return dict(ChainMap(d1, d2))
dict1 = {'a': 1, 'b': 2, 'c': 3}
dict2 = {'d': 4, 'e': 5}
result = merge_dicts(dict1, dict2)
print("Merged dictionary:", result)
- กำหนดฟังก์ชัน
merge_dictsเพื่อรวมสองพจนานุกรม - ใช้
ChainMapคลาสเพื่อสร้างมุมมองรวมของพจนานุกรมสองเล่มและแปลงผลลัพธ์เป็นพจนานุกรม
เริ่มต้น:
def list_difference(lst1, lst2):
difference = []
for item in lst1:
if item not in lst2:
difference.append(item)
return difference
lst1 = [1, 2, 3, 4, 5]
lst2 = [4, 5, 6, 7, 8]
result = list_difference(lst1, lst2)
print("List difference:", result)
#List difference: [1, 2, 3]
- ใช้พื้นฐานสำหรับการวนซ้ำเพื่อวนซ้ำองค์ประกอบในรายการแรก และตรวจสอบว่าแต่ละองค์ประกอบไม่มีอยู่ในรายการที่สองหรือไม่
- ผนวกองค์ประกอบเฉพาะเข้ากับรายการความแตกต่าง
def list_difference(lst1, lst2):
return list(set(lst1) - set(lst2))
lst1 = [1, 2, 3, 4, 5]
lst2 = [4, 5, 6, 7, 8]
result = list_difference(lst1, lst2)
print("List difference:", result)
- แปลงรายการเป็นชุดและใช้ตัวดำเนินการความแตกต่างของชุด(
-)เพื่อค้นหาองค์ประกอบที่ไม่ซ้ำกัน - แปลงผลลัพธ์กลับเป็นรายการ
def list_difference(lst1, lst2):
return [item for item in lst1 if item not in set(lst2)]
lst1 = [1, 2, 3, 4, 5]
lst2 = [4, 5, 6, 7, 8]
result = list_difference(lst1, lst2)
print("List difference:", result)
- ใช้ความเข้าใจในรายการกับเงื่อนไขเพื่อสร้างรายการขององค์ประกอบที่ไม่ซ้ำกัน
- แปลงรายการที่สองเป็นชุดเพื่อเพิ่มประสิทธิภาพการทดสอบการเป็นสมาชิก
เริ่มต้น:
def create_dict(keys, values):
result = {}
for key, value in zip(keys, values):
result[key] = value
return result
keys = ['name', 'age', 'gender']
values = ['Alice', 25, 'Female']
result = create_dict(keys, values)
print("Dictionary:", result)
#Dictionary: {'name': 'Alice', 'age': 25, 'gender': 'Female'}
- ใช้ for วนซ้ำกับ
zipฟังก์ชันเพื่อวนซ้ำคีย์และค่าต่างๆ พร้อมกัน - สร้างพจนานุกรมโดยกำหนดแต่ละค่าให้กับคีย์ที่เกี่ยวข้อง
def create_dict(keys, values):
return dict(zip(keys, values))
keys = ['name', 'age', 'gender']
values = ['Alice', 25, 'Female']
result = create_dict(keys, values)
print("Dictionary:", result)
- ใช้
zipฟังก์ชันเพื่อจับคู่คีย์และค่า จากนั้นใช้dictตัวสร้างเพื่อสร้างพจนานุกรม
def create_dict(keys, values):
return {key: value for key, value in zip(keys, values)}
keys = ['name', 'age', 'gender']
values = ['Alice', 25, 'Female']
result = create_dict(keys, values)
print("Dictionary:", result)
- ใช้ความเข้าใจในพจนานุกรมกับ
zipฟังก์ชันเพื่อสร้างพจนานุกรม
เริ่มต้น:
def replace_word(sentence, old_word, new_word):
return sentence.replace(old_word, new_word)
sentence = "I like apples. Apples are tasty."
old_word = "apples"
new_word = "oranges"
print(replace_word(sentence, old_word, new_word))
#I like oranges. Apples are tasty.
import re
def replace_word(sentence, old_word, new_word):
return re.sub(r'\b' + old_word + r'\b', new_word, sentence, flags=re.IGNORECASE)
sentence = "I like apples. Apples are tasty."
old_word = "apples"
new_word = "oranges"
print(replace_word(sentence, old_word, new_word))
Image by the Author
เริ่มต้น:
def mean(numbers):
return sum(numbers) / len(numbers)
def standard_deviation(numbers):
avg = mean(numbers)
return (sum((x - avg) ** 2 for x in numbers) / len(numbers)) ** 0.5
numbers = [1, 2, 3, 4, 5]
print(standard_deviation(numbers))
#1.4142135623730951
import numpy as np
numbers = [1, 2, 3, 4, 5]
print(np.std(numbers))
Image by the Author
เริ่มต้น:
from sklearn.preprocessing import OneHotEncoder
data = [['apple'], ['banana'], ['orange'], ['apple'], ['banana']]
encoder = OneHotEncoder()
one_hot_encoded = encoder.fit_transform(data).toarray()
print(one_hot_encoded)
import pandas as pd
data = pd.DataFrame({'fruit': ['apple', 'banana', 'orange', 'apple', 'banana']})
one_hot_encoded = pd.get_dummies(data, columns=['fruit'])
print(one_hot_encoded)
Image by the Author
เริ่มต้น:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
even_numbers = []
odd_numbers = []
for num in numbers:
if num % 2 == 0:
even_numbers.append(num)
else:
odd_numbers.append(num)
grouped_numbers = {'even': even_numbers, 'odd': odd_numbers}
print("Grouped numbers:", grouped_numbers)
#Grouped numbers: {'even': [2, 4, 6, 8], 'odd': [1, 3, 5, 7, 9]}
- ต่อท้ายเลขคู่ใน
even_numbersรายการและเลขคี่ต่อท้ายodd_numbersรายการ - จัดกลุ่มตัวเลขลงในพจนานุกรม
def group_by_parity(numbers):
return {
'even': [num for num in numbers if num % 2 == 0],
'odd': [num for num in numbers if num % 2 != 0],
}
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
grouped_numbers = group_by_parity(numbers)
print("Grouped numbers:", grouped_numbers)
- ใช้ความเข้าใจในพจนานุกรมและความเข้าใจในรายการเพื่อสร้างพจนานุกรมที่จัดกลุ่ม
from collections import defaultdict
def group_by_parity(numbers):
grouped_numbers = defaultdict(list)
for num in numbers:
key = 'even' if num % 2 == 0 else 'odd'
grouped_numbers[key].append(num)
return grouped_numbers
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
grouped_numbers = group_by_parity(numbers)
print("Grouped numbers:", grouped_numbers)
- กำหนดฟังก์ชัน
group_by_parityที่ใช้ defaultdict เพื่อจัดกลุ่มหมายเลขตามความเท่าเทียมกัน - วนซ้ำตัวเลขและผนวกเข้ากับคีย์ที่เหมาะสม ('คู่' หรือ 'คี่') ในพจนานุกรมที่จัดกลุ่ม
เริ่มต้น:
numbers = [1, 2, 2, 3, 4, 4, 4, 5, 5]
element_count = {}
for num in numbers:
if num in element_count:
element_count[num] += 1
else:
element_count[num] = 1
most_common_element = max(element_count, key=element_count.get)
print("Most common element:", most_common_element)
#Most common element: 4
- ใช้
maxฟังก์ชันที่มีkeyอาร์กิวเมนต์เพื่อค้นหาองค์ประกอบที่พบมากที่สุด
from collections import Counter
def most_common_element(lst):
return Counter(lst).most_common(1)[0][0]
numbers = [1, 2, 2, 3, 4, 4, 4, 5, 5]
result = most_common_element(numbers)
print("Most common element:", result)
- กำหนดฟังก์ชัน `most_common_element` ที่ใช้คลาส `Counter` เพื่อนับการเกิดขึ้นขององค์ประกอบในรายการ
from statistics import mode
def most_common_element(lst):
return mode(lst)
numbers = [1, 2, 2, 3, 4, 4, 4, 5, 5]
result = most_common_element(numbers)
print("Most common element:", result)
- กำหนดฟังก์ชัน
most_common_elementที่ใช้modeฟังก์ชันเพื่อค้นหาองค์ประกอบทั่วไปในรายการ - ฟังก์ชัน
modeจะส่งคืนองค์ประกอบที่พบมากที่สุดในรายการ
เริ่มต้น:
def dict_to_tuples(d):
return [(key, value) for key, value in d.items()]
dictionary = {'a': 1, 'b': 2, 'c': 3}
result = dict_to_tuples(dictionary)
print("List of tuples:", result)
# List of tuples: [('a', 1), ('b', 2), ('c', 3)]
- ใช้ความเข้าใจในรายการด้วย
itemsวิธีการของพจนานุกรมเพื่อสร้างรายการสิ่งอันดับ
def dict_to_tuples(d):
return list(d.items())
dictionary = {'a': 1, 'b': 2, 'c': 3}
result = dict_to_tuples(dictionary)
print("List of tuples:", result)
- ใช้
itemsวิธีการของพจนานุกรมเพื่อรับคู่คีย์-ค่าเป็นทูเพิลและแปลงผลลัพธ์เป็นรายการ
from operator import itemgetter
def dict_to_tuples(d):
return sorted(d.items(), key=itemgetter(0))
dictionary = {'a': 1, 'b': 2, 'c': 3}
result = dict_to_tuples(dictionary)
print("List of tuples:", result)
- กำหนดฟังก์ชัน
dict_to_tuplesเพื่อแปลงพจนานุกรมเป็นรายการทูเพิล - ใช้
itemsวิธีการของพจนานุกรมเพื่อรับคู่คีย์-ค่าเป็นทูเพิลและจัดเรียงผลลัพธ์ตามคีย์
เริ่มต้น:
def find_max_min(numbers):
max_value = max(numbers)
min_value = min(numbers)
return max_value, min_value
numbers = [1, 2, 3, 4, 5]
max_value, min_value = find_max_min(numbers)
print("Maximum value:", max_value)
print("Minimum value:", min_value)
# Maximum value: 5
# Minimum value: 1
- ใช้ในตัว
maxและminฟังก์ชันเพื่อค้นหาค่าสูงสุดและต่ำสุด
def find_max_min(numbers):
return max(numbers), min(numbers)
numbers = [1, 2, 3, 4, 5]
max_value, min_value = find_max_min(numbers)
print("Maximum value:", max_value)
print("Minimum value:", min_value)
- ใช้บิวด์อิน
maxและminฟังก์ชันเพื่อค้นหาค่าสูงสุดและค่าต่ำสุดและส่งกลับเป็นทูเพิล
from functools import reduce
def find_max_min(numbers):
return reduce(lambda acc, x: (max(acc[0], x), min(acc[1], x)), numbers, (float('-inf'), float('inf')))
numbers = [1, 2, 3, 4, 5]
max_value, min_value = find_max_min(numbers)
print("Maximum value:", max_value)
print("Minimum value:", min_value)
- กำหนดฟังก์ชัน
find_max_minเพื่อค้นหาค่าสูงสุดและค่าต่ำสุดในรายการตัวเลข - ใช้
reduceฟังก์ชันที่มีฟังก์ชันแลมบ์ดาเพื่อคำนวณค่าสูงสุดและค่าต่ำสุดโดยการเปรียบเทียบแต่ละองค์ประกอบกับค่าสะสม - เริ่มต้นตัวสะสมด้วยค่าอินฟินิตี้ที่เป็นลบและบวกเพื่อจัดการกับกรณีขอบ
เริ่มต้น:
def calculate_mean(numbers):
return sum(numbers) / len(numbers)
def calculate_median(numbers):
numbers.sort()
n = len(numbers)
if n % 2 == 0:
return (numbers[n // 2 - 1] + numbers[n // 2]) / 2
else:
return numbers[n // 2]
def calculate_mode(numbers):
counts = {}
for num in numbers:
if num in counts:
counts[num] += 1
else:
counts[num] = 1
return max(counts, key=counts.get)
numbers = [4, 6, 4, 7, 4, 5, 6, 4, 7, 8, 5, 4]
mean = calculate_mean(numbers)
median = calculate_median(numbers)
mode = calculate_mode(numbers)
print(f"Mean: {mean}, Median: {median}, Mode: {mode}")
#Mean: 5.333333333333333, Median: 5.0, Mode: 4
- ฟังก์ชัน
calculate_meanหาค่าเฉลี่ยโดยการหารผลรวมของตัวเลขด้วยความยาวของรายการ - ฟังก์ชัน
calculate_medianจัดเรียงรายการและค้นหาองค์ประกอบตรงกลางเพื่อคำนวณค่ามัธยฐาน - ฟังก์ชัน นี้
calculate_modeใช้พจนานุกรมเพื่อนับจำนวนที่เกิดขึ้นของแต่ละหมายเลขและค้นหาจำนวนที่มีจำนวนสูงสุด
from statistics import mean, median, mode
def calculate_mean_median_mode(numbers):
return mean(numbers), median(numbers), mode(numbers)
numbers = [4, 6, 4, 7, 4, 5, 6, 4, 7, 8, 5, 4]
mean, median, mode = calculate_mean_median_mode(numbers)
print(f"Mean: {mean}, Median: {median}, Mode: {mode}")
- ฟังก์ชัน
calculate_mean_median_modeจะส่งกลับค่าเฉลี่ย ค่ามัธยฐาน และฐานนิยมเป็นทูเพิล
from statistics import mean, median, mode
from typing import List, Tuple
def calculate_mean_median_mode(numbers: List[float]) -> Tuple[float, float, float]:
return mean(numbers), median(numbers), mode(numbers)
def main():
numbers = [4, 6, 4, 7, 4, 5, 6, 4, 7, 8, 5, 4]
mean_val, median_val, mode_val = calculate_mean_median_mode(numbers)
print(f"Mean: {mean_val}, Median: {median_val}, Mode: {mode_val}")
if __name__ == "__main__":
main()
- ฟังก์ชันใช้
statisticsโมดูลเพื่อคำนวณค่าเฉลี่ย ค่ามัธยฐาน และฐานนิยม - โค้ดถูกจัดระเบียบเป็น
mainฟังก์ชัน ซึ่งจะเรียกใช้เมื่อเรียกใช้สคริปต์
เริ่มต้น:
def merge_sorted_lists(list1, list2):
result = []
i = j = 0
while i < len(list1) and j < len(list2):
if list1[i] < list2[j]:
result.append(list1[i])
i += 1
else:
result.append(list2[j])
j += 1
result.extend(list1[i:])
result.extend(list2[j:])
return result
list1 = [1, 3, 5, 7]
list2 = [2, 4, 6, 8]
merged_list = merge_sorted_lists(list1, list2)
print(merged_list)
- ฟังก์ชันนี้ใช้พอยน์เตอร์สองตัว (i และ j) เพื่อวนซ้ำผ่านรายการอินพุตสองรายการและเปรียบเทียบองค์ประกอบต่างๆ เพื่อสร้างรายการที่ผสาน
- องค์ประกอบที่เหลือจากรายการใดรายการหนึ่งจะถูกผนวกเข้ากับผลลัพธ์
from heapq import merge
from typing import List
def merge_sorted_lists(list1: List[int], list2: List[int]) -> List[int]:
return list(merge(list1, list2))
def main():
list1 = [1, 3, 5, 7]
list2 = [2, 4, 6, 8]
merged_list = merge_sorted_lists(list1, list2)
print(merged_list)
if __name__ == "__main__":
main()
- คำอธิบายประกอบประเภทรวมอยู่ในพารามิเตอร์อินพุตและประเภทการส่งคืน
- โค้ดถูกจัดระเบียบเป็น
mainฟังก์ชัน ซึ่งจะเรียกใช้เมื่อเรียกใช้สคริปต์
เริ่มต้น:
def factorial(n):
if n == 0:
return 1
return n * factorial(n - 1)
number = 5
result = factorial(number)
print(f"The factorial of {number} is {result}.")
#The factorial of 5 is 120.
- ฟังก์ชันประกอบด้วยตัวพิมพ์ฐานสำหรับเมื่อ
nเป็นศูนย์ ส่งคืน 1 - กรณีเรียกซ้ำจะคำนวณแฟกทอเรียลโดยการคูณ
nกับแฟกทอเรียลn - 1ของ
from functools import lru_cache
from typing import Optional
@lru_cache(maxsize=None)
def factorial(n: int) -> Optional[int]:
if n < 0:
print("Error: Factorial is not defined for negative numbers.")
return None
if n == 0:
return 1
return n * factorial(n - 1)
def main():
number = 5
result = factorial(number)
if result is not None:
print(f"The factorial of {number} is {result}.")
else:
print("Could not calculate factorial.")
if __name__ == "__main__":
main()
- มัณฑนา
@lru_cacheกรใช้เพื่อจดจำฟังก์ชันแฟกทอเรียล แคชผลลัพธ์ระดับกลางเพื่อประสิทธิภาพที่ดีขึ้น - ฟังก์ชันจะตรวจสอบค่าอินพุตที่เป็นลบและแสดงข้อความแสดงข้อผิดพลาดสำหรับอินพุตที่ไม่ถูกต้อง
- รหัสใช้
mainฟังก์ชันสำหรับการจัดระเบียบรหัสและเพื่อจัดการกับกรณีที่เป็นไปได้ที่ไม่สามารถคำนวณแฟกทอเรียลได้
เริ่มต้น:
import pandas as pd
def load_csv(file_path):
return pd.read_csv(file_path)
file_path = "data.csv"
df = load_csv(file_path)
print(df.head())
- กำหนดฟังก์ชัน
load_csvเพื่อโหลดไฟล์ CSV ลงใน DataFrame โดยใช้read_csvวิธีจากpandas - พิมพ์สองสามแถวแรกของ DataFrame โดยใช้
headวิธี
import pandas as pd
def load_csv(file_path, use_cols=None, parse_dates=None):
return pd.read_csv(file_path, usecols=use_cols, parse_dates=parse_dates)
file_path = "data.csv"
selected_columns = ['column1', 'column3']
date_columns = ['date_column']
df = load_csv(file_path, use_cols=selected_columns, parse_dates=date_columns)
print(df.head())
- กำหนดฟังก์ชัน
load_csvด้วยพารามิเตอร์ทางเลือกuse_colsและparse_datesสำหรับการเลือกคอลัมน์และการแยกวิเคราะห์คอลัมน์วันที่ ตามลำดับ - โหลดคอลัมน์ที่ระบุจากไฟล์ CSV โดยแยกวิเคราะห์คอลัมน์วันที่เป็นออบเจกต์วันที่และเวลา
- พิมพ์สองสามแถวแรกของ DataFrame
def max_product(arr):
max_product = float('-inf')
for i in range(len(arr)):
for j in range(i + 1, len(arr)):
product = arr[i] * arr[j]
if product > max_product:
max_product = product
return max_product
arr = [1, 3, 5, 2, 6, 4]
max_product_result = max_product(arr)
print("Maximum product of two integers:", max_product_result)
#30
- ฟังก์ชันนี้ใช้ลูปที่ซ้อนกันเพื่อพิจารณาจำนวนเต็มที่เป็นไปได้ทั้งหมดในอาร์เรย์
- สำหรับแต่ละคู่ สินค้าจะถูกคำนวณ และมูลค่าสินค้าสูงสุดจะถูกอัพเดตตามนั้น
from typing import List
def max_product(arr: List[int]) -> int:
arr.sort(reverse=True)
return arr[0] * arr[1]
def main():
arr = [1, 3, 5, 2, 6, 4]
max_product_result = max_product(arr)
print("Maximum product of two integers:", max_product_result)
if __name__ == "__main__":
main()
- ฟังก์ชันจะจัดเรียงอาร์เรย์จากมากไปน้อยและส่งคืนผลคูณของสององค์ประกอบแรกซึ่งมีขนาดใหญ่ที่สุด
- โค้ดถูกจัดระเบียบด้วย
mainฟังก์ชันเพื่อโครงสร้างและการอ่านที่ดีขึ้น
from typing import List
from heapq import nlargest
def max_product(arr: List[int]) -> int:
largest_nums = nlargest(2, arr)
return largest_nums[0] * largest_nums[1]
def main():
arr = [1, 3, 5, 2, 6, 4]
max_product_result = max_product(arr)
print("Maximum product of two integers:", max_product_result)
if __name__ == "__main__":
main()
- ฟังก์ชันส่งคืนผลคูณของจำนวนเต็มที่มากที่สุดสองตัว
- โค้ดถูกจัดระเบียบเป็น
mainฟังก์ชัน ซึ่งจะเรียกใช้เมื่อเรียกใช้สคริปต์
เริ่มต้น:
def binary_search(arr, target):
low, high = 0, len(arr) - 1
while low <= high:
mid = (low + high) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
low = mid + 1
else:
high = mid - 1
return -1
arr = [1, 2, 4, 5, 6, 7, 9, 10]
target = 7
index = binary_search(arr, target)
print(f"Index of {target}:", index)
- ฟังก์ชันใช้
whileการวนซ้ำเพื่อจำกัดช่วงการค้นหาให้แคบลงซ้ำๆ ตามค่าขององค์ประกอบตรงกลาง - หากพบค่าเป้าหมาย ฟังก์ชันจะส่งคืนดัชนีขององค์ประกอบตรงกลาง มิฉะนั้นจะส่งกลับ -1
from typing import List
from bisect import bisect_left
def binary_search(arr: List[int], target: int) -> int:
index = bisect_left(arr, target)
return index if index != len(arr) and arr[index] == target else -1
def main():
arr = [1, 2, 4, 5, 6, 7, 9, 10]
target = 7
index = binary_search(arr, target)
print(f"Index of {target}:", index)
if __name__ == "__main__":
main()
- ฟังก์ชันตรวจสอบว่ามีค่าเป้าหมายอยู่ที่ดัชนีที่พบหรือไม่ และส่งคืนดัชนีหากตรงกับเป้าหมาย มิฉะนั้นจะส่งกลับ -1
- โค้ดถูกจัดระเบียบเป็น
mainฟังก์ชัน ซึ่งจะเรียกใช้เมื่อเรียกใช้สคริปต์
โปรแกรมเมอร์ระดับเริ่มต้นจะมุ่งเน้นไปที่ไวยากรณ์พื้นฐานและแนวคิดพื้นฐาน โปรแกรมเมอร์ระดับกลางจะแนะนำการเพิ่มประสิทธิภาพและโค้ดโมดูลาร์ ในขณะที่โปรแกรมเมอร์ผู้เชี่ยวชาญจะใช้ประโยชน์จากเทคนิคขั้นสูง การจัดการข้อผิดพลาด การจัดระเบียบโค้ด และความทนทานโดยรวม หากต้องการเรียนรู้เพิ่มเติม โปรดตรวจสอบข้อมูลอ้างอิง
อ้างอิง:
- Python.org เอกสารอย่างเป็นทางการ:
ลิงค์:https://docs.python.org/3/tutorial/index.html - หลักสูตร Python ของ Codecademy:
ลิงค์:https://www.codecademy.com/learn/learn-python-3 - Python ของ Coursera สำหรับทุกคน:
ลิงค์:https://www.coursera.org/specializations/python - คลาส Python ของ Google:
ลิงก์:https://developers.google.com/edu/python - LeetCode:
ลิงค์:https://leetcode.com - อันดับแฮ็กเกอร์:
ลิงก์:https://www.hackerrank.com/domains/tutorials/10-days-of-python - Codewars:
ลิงค์:https://www.codewars.com - Stack Overflow:
ลิงก์:https://stackoverflow.com/questions/tagged/python - Python Reddit Community (r/Python):
ลิงก์:https://www.reddit.com/r/Python/ - Python Discord ชุมชน:
ลิงค์:https://pythondiscord.com
ขอบคุณที่เป็นส่วนหนึ่งของชุมชนของเรา! ก่อนที่คุณจะไป:
- ปรบมือให้กับเรื่องราวและติดตามผู้เขียน
- ดูเนื้อหาเพิ่มเติมในสิ่งพิมพ์ Level Up Coding
- หลักสูตรสัมภาษณ์การเข้ารหัสฟรี ⇒ ดูหลักสูตร
- ติดตามเรา: Twitter | LinkedIn | จดหมายข่าว





































![รายการที่เชื่อมโยงคืออะไร? [ส่วนที่ 1]](https://post.nghiatu.com/assets/images/m/max/724/1*Xokk6XOjWyIGCBujkJsCzQ.jpeg)