Searching & max / min · การค้นหา / ค่าสูงสุด/ต่ำสุด
Linear search
- A linear search looks at each item in turn until it finds the target.
- It is a named standard method in the syllabus.
- Use a loop and remember when you find a match.
การค้นหาแบบเชิงเส้น
- การค้นแบบเชิงเส้น (linear search) จะตรวจสอบรายการแต่ละชิ้น ตามลำดับ จนกว่าจะพบเป้าหมาย
- เป็น วิธีมาตรฐานที่มีชื่อเรียก ในหลักสูตร
- ใช้ลูปและจดจำเมื่อพบความตรงกัน
nums = [4, 9, 2, 7]
target = 9
found = False
for n in nums:
if n == target:
found = True
print(found) # True
Linear search, step by step · การค้นหาแบบเชิงเส้น, ทีละขั้นตอน
A linear search checks each item in turn until it finds the target. · การหาแบบเชิงเส้นจะตรวจสอบแต่ละรายการทีละตัวจนกว่าจะพบเป้าหมาย
Finding the maximum
- Start by assuming the first item is the biggest.
- Then check the rest; if one is bigger, remember it instead.
การหาค่าสูงสุด
- เริ่มต้นด้วยการสมมติว่ารายการ แรกสุด มีค่ามากที่สุด
- จากนั้นตรวจสอบรายการที่เหลือ; หากมีรายการใดมีค่ามากกว่า ให้จดจำรายการนั้นแทน
nums = [4, 9, 2, 7]
biggest = nums[0]
for n in nums:
if n > biggest:
biggest = n
print(biggest) # 9
Finding the minimum
- The same idea, but keep the smallest value seen so far.
การหาค่าน้อยที่สุด
- ความคิดเดียวกัน แต่คงค่าที่ น้อยที่สุด ที่พบมาจนถึงตอนนี้
nums = [4, 9, 2, 7]
smallest = nums[0]
for n in nums:
if n < smallest:
smallest = n
print(smallest) # 2
In the exam: standard methods
- Linear search and finding maximum / minimum / average are named in section 7.
ในการสอบ: วิธีการมาตรฐาน
- การค้นแบบเชิงเส้นและการหาค่าสูงสุด/ต่ำสุด/เฉลี่ย ถูกกล่าวถึงในส่วน 7
Found ← FALSE
FOR I ← 1 TO 4
IF Number[I] = Target
THEN
Found ← TRUE
ENDIF
NEXT I
Common mistakes
- Linear search checks each item in turn until it finds the target.
- For max or min, start from the first item, then compare the rest against it.
ข้อผิดพลาดที่พบบ่อย
- การค้นหาแบบเชิงเส้นจะตรวจสอบแต่ละรายการทีละตัว จนกว่าจะพบเป้าหมาย
- สำหรับค่าสูงสุดหรือต่ำสุด ให้เริ่มต้นจากรายการแรก แล้วเปรียบเทียบรายการที่เหลือกับมัน
Now you try
- Loop through the list to search or compare.
- Press Check answer to test your code.
ลองดูเลย
- ทำลูปผ่านรายการเพื่อค้นหาหรือเปรียบเทียบ
- กด Check answer เพื่อทดสอบโค้ดของคุณ
Write contains(nums, target) that returns True if target is in the list, using a linear search loop (do not use the in keyword). · เขียน contains(nums, target) ที่คืนค่า True หาก target อยู่ในรายการ โดยใช้ ลูปค้นหาแบบเชิงเส้น (ห้ามใช้คำสำคัญ in)
Click Run to see the output here. · คลิก Run เพื่อดูผลลัพธ์ที่นี่
The list nums is set. Find the largest value with a loop and store it in biggest (do not use max()). · รายการ nums ถูกกำหนดไว้แล้ว หา ค่ามากที่สุด ด้วยลูปและเก็บไว้ใน biggest (ห้ามใช้ max())
Click Run to see the output here. · คลิก Run เพื่อดูผลลัพธ์ที่นี่
Find the smallest value in nums with a loop and store it in smallest (do not use min()). · หา ค่าน้อยที่สุด ใน nums ด้วยลูปและเก็บไว้ใน smallest (ห้ามใช้ min())
Click Run to see the output here. · คลิก Run เพื่อดูผลลัพธ์ที่นี่