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.
חיפוש ליניארי
- חיפוש ליניארי בודק כל פריט בתורו עד למציאת המטרה.
- זוהי שיטה סטנדרטית המוגדרת בתוכנית הלימודים.
- השתמש בלולאה וזכור מתי מצאת התאמה.
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.
כעת תנסו בעצמכם
- חזור על הרשימה כדי לבצע חיפוש או השוואה.
- לחץ על בדוק תשובה כדי לבדוק את הקוד שלך.
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. · לחץ על הרץ כדי לראות את התוצא כאן.
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. · לחץ על הרץ כדי לראות את התוצא כאן.
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. · לחץ על הרץ כדי לראות את התוצא כאן.