מפגש 34: חיפוש בינארי, מיון, Big-O ובחירת מבנה נתונים.Session 34: Binary search, sorting, Big-O and choosing a data structure.
חיפוש בינארי, מיון, Big-O ובחירת מבנה נתונים. בסוף המפגש מוסיפים צעד לפרויקט המלווה.Binary search, sorting, Big-O and choosing a data structure. At the end we add a step to the companion project.
מה נעשה היוםToday's plan
למהWhy
Big OBig O
בינאריBinary
מבניםStructures
מיוןSorting
רקורסיהRecursion
עוברים על סדר היום ומזכירים את הפרויקט המלווה.Walk through the plan and mention the companion project.
ב-10 ספרים הכול מהירWith 10 books everything is fast
ב-מיליון, ההבדל בין שנייה לשעהWith a million, the gap between a second and an hour
עם 20 ספרים כל קוד מהיר. אבל ספרייה עירונית עם מיליון ספרים חושפת את ההבדל בין אלגוריתמים. במקום למדוד בשניות (שתלויות במחשב), סופרים צעדים: כמה השוואות עושה כל שיטה. כאן סופרים השוואות בחיפוש פריט אחרון ברשימות בגדלים שונים:With 20 books any code is fast. But a city library with a million books exposes the difference between algorithms. Instead of measuring seconds (which depend on the computer), count steps: how many comparisons each method makes. Here we count comparisons when searching for the last item in lists of different sizes:
אנלוגיהAnalogy
לחפש ספר מדף אחרי מדף זה כמו לחפש מכונית בחניון ענק שורה אחרי שורה. אם יודעים את מספר הקומה והשורה, מגיעים מיד.Searching shelf by shelf is like hunting for your car in a huge car park row by row. If you know the floor and row, you're there at once.
שואלים אם מישהו מכיר דוגמה נוספת מהחיים.Ask for another real-life example.
נושאTopic 2
Big OBig O
Big OBig O
O(1): קבוע, לא תלוי בגודלO(1): constant, independent of size
O(n): לולאה אחתO(n): one loop
O(n²): לולאה בתוך לולאהO(n²): a loop inside a loop
Big O מתאר איך מספר הצעדים גדל כשהקלט גדל, בלי פרטים קטנים. גישה לפי אינדקס shelf[5] היא O(1): לא משנה כמה ספרים יש. לולאה על כל הספרים היא O(n). לולאה בתוך לולאה (להשוות כל ספר לכל ספר) היא O(n²). והטבלה מראה למה זה משנה:Big O describes how the number of steps grows as input grows, without small details. Indexing shelf[5] is O(1): it doesn't matter how many books there are. A loop over all books is O(n). A loop inside a loop (comparing every book to every book) is O(n²). The table shows why it matters:
אנלוגיהAnalogy
O(n) הוא כמו לחלק עלונים בכל בית ברחוב: רחוב כפול, עבודה כפולה. O(n²) הוא כמו שכל שכן יכיר כל שכן: רחוב כפול, פי ארבעה היכרויות.O(n) is like delivering flyers to every house on a street: double the street, double the work. O(n²) is like every neighbour meeting every neighbour: double the street, four times the introductions.
שואלים אם מישהו מכיר דוגמה נוספת מהחיים.Ask for another real-life example.
נושאTopic 3
בינאריBinary
חיפוש בינאריBinary search
רק ברשימה ממוינתOnly on a sorted list
בודקים אמצע, זורקים חציCheck the middle, throw away half
מיליון → 20 צעדיםA million → 20 steps
חיפוש בינארי הוא האלגוריתם הקלאסי: ברשימה ממוינת, מסתכלים על האמצע. אם המבוקש גדול יותר, כל החצי השמאלי לא רלוונטי. בכל צעד חצי מהרשימה נעלם, ולכן מיליון פריטים דורשים רק כ-20 צעדים: O(log n). בסימולציה רואים את lo, hi ו-mid זזים:binary search is the classic algorithm: in a sorted list, look at the middle. If the target is bigger, the whole left half is irrelevant. Each step discards half the list, so a million items need only about 20 steps: O(log n). In the simulation you can watch lo, hi and mid move:
אנלוגיהAnalogy
חיפוש בינארי הוא כמו משחק "גבוה-נמוך" עם מספר בין 1 למיליון: כל ניחוש באמצע חוצה את האפשרויות, ותוך 20 ניחושים מגיעים.Binary search is like playing "higher or lower" with a number between 1 and a million: each middle guess halves the options, and 20 guesses get you there.
שואלים אם מישהו מכיר דוגמה נוספת מהחיים.Ask for another real-life example.
נושאTopic 4
מבניםStructures
מבנה הנתונים הנכוןThe right data structure
רשימה: סדר, אינדקס. in הוא O(n)List: order, index. in is O(n)
set ו-dict: גיבוב, in הוא O(1)set and dict: hashing, in is O(1)
Counter, deque, heapq לצרכים מיוחדיםCounter, deque, heapq for special needs
לעיתים קרובות השיפור הגדול ביותר לא בא מאלגוריתם חכם, אלא ממבנה נתונים נכון. set ו-dict בנויים על טבלת גיבוב: הם מחשבים מהמפתח איפה הוא שמור, ומגיעים אליו כמעט מיד. מדידה אמיתית של in:Often the biggest speedup doesn't come from a clever algorithm but from the right data structure. set and dict are built on a hash table: they compute from the key where it lives, and reach it almost at once. A real measurement of in:
אנלוגיהAnalogy
רשימה היא כמו ערימת מכתבים: כדי למצוא אחד מחפשים. dict הוא כמו תיבות דואר עם שמות: הולכים ישר לתיבה הנכונה.A list is like a pile of letters: to find one, you search. A dict is like named mailboxes: walk straight to the right box.
שואלים אם מישהו מכיר דוגמה נוספת מהחיים.Ask for another real-life example.
נושאTopic 5
מיוןSorting
מיוןSorting
מיון בועות: O(n²), טוב ללמידהBubble sort: O(n²), good for learning
sorted של פייתון: O(n log n)Python's sorted: O(n log n)
key= לכל סדר שרוציםkey= for any order you want
מיון בועות הוא האלגוריתם הראשון שכולם לומדים: עוברים שוב ושוב ומחליפים זוגות שבסדר הפוך. הוא פשוט להבנה, אבל O(n²). sorted של פייתון (Timsort) הוא O(n log n) ומנצל קטעים שכבר ממוינים. בפועל תמיד משתמשים ב-sorted, אבל לכתוב מיון בעצמכם מלמד לחשוב על צעדים:Bubble sort is the first algorithm everyone learns: pass again and again, swapping pairs that are out of order. It's simple to understand, but O(n²). Python's sorted (Timsort) is O(n log n) and takes advantage of runs that are already sorted. In practice you always use sorted, but writing a sort yourself teaches you to think in steps:
אנלוגיהAnalogy
מיון בועות הוא כמו לסדר ילדים בתור לפי גובה כשכל אחד יכול רק להתחלף עם השכן שלו: זה עובד, אבל לוקח הרבה סיבובים.Bubble sort is like lining children up by height when each may only swap with a neighbour: it works, but takes many rounds.
שואלים אם מישהו מכיר דוגמה נוספת מהחיים.Ask for another real-life example.
טעות נפוצהCommon mistake
sorting.py
print(sorted([412, "96", 240]))
מה Python עונהWhat Python says
TypeError: '<' not supported between instances of 'str' and 'int'
TypeError: '<' not supported between instances of 'str' and 'int': פייתון לא יודעת אם "96" קטן מ-412. ממירים קודם: sorted(int(x) for x in items).TypeError: '<' not supported between instances of 'str' and 'int': Python can't tell whether "96" is less than 412. Convert first: sorted(int(x) for x in items).
ממיינים ברשימה עם טיפוסים מעורבים.Sorting a list of mixed types.
נושאTopic 6
רקורסיהRecursion
רקורסיהRecursion
פונקציה שקוראת לעצמהA function that calls itself
חייב מקרה בסיסIt must have a base case
מתאים לעצים ותיקיותFits trees and folders
רקורסיה היא פונקציה שפותרת בעיה בעזרת גרסה קטנה יותר של אותה בעיה. לכל רקורסיה צריך מקרה בסיס שבו עוצרים, אחרת היא קוראת לעצמה לנצח. היא מתאימה במיוחד למבנים מקוננים, כמו תיקייה שיש בה תיקיות, או קטגוריות בתוך קטגוריות:Recursion is a function solving a problem using a smaller version of the same problem. Every recursion needs a base case where it stops, otherwise it calls itself forever. It fits nested structures especially well, like a folder holding folders, or categories inside categories:
אנלוגיהAnalogy
רקורסיה היא כמו בובות בבושקה: כדי לספור את כולן, פותחים בובה, סופרים אותה, ומבקשים מהבובה שבתוכה לספור את עצמה.Recursion is like Russian dolls: to count them all, open a doll, count it, and ask the doll inside to count itself.
שואלים אם מישהו מכיר דוגמה נוספת מהחיים.Ask for another real-life example.
טעות נפוצהCommon mistake
recursion.py
def countdown(n):
countdown(n -1)
countdown(5)
מה Python עונהWhat Python says
RecursionError: maximum recursion depth exceeded
RecursionError: maximum recursion depth exceeded: אין תנאי עצירה, והפונקציה ממשיכה לקרוא לעצמה עד שפייתון עוצרת אותה (בערך 1000 רמות). מוסיפים if n == 0: return.RecursionError: maximum recursion depth exceeded: there's no stopping condition, so the function keeps calling itself until Python stops it (about 1000 levels). Add if n == 0: return.
רקורסיה בלי מקרה בסיס.Recursion without a base case.