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. · اضغط تشغيل لرؤية المخرجات هنا.