אלגוריתמים וסיבוכיותAlgorithms & complexity
חיפוש בינארי, מיון, Big-O ובחירת מבנה נתונים.
Binary search, sorting, Big-O and choosing a data structure.
01למה יעילות?Why efficiency?
עם 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:
def linear_steps(items, target):
steps = 0
for x in items:
steps += 1
if x == target:
break
return steps
for n in [10, 1_000, 100_000, 1_000_000]:
items = list(range(n))
print(f"{n:>9,} books -> {linear_steps(items, n - 1):>9,} comparisons") 10 books -> 10 comparisons
1,000 books -> 1,000 comparisons
100,000 books -> 100,000 comparisons
1,000,000 books -> 1,000,000 comparisonsלחפש ספר מדף אחרי מדף זה כמו לחפש מכונית בחניון ענק שורה אחרי שורה. אם יודעים את מספר הקומה והשורה, מגיעים מיד.
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.
בודקים מהירות רק על קלט קטן.
Checking speed only on a tiny input.
def has_duplicates(items):
return any(items[i] == items[j] for i in range(len(items)) for j in range(i + 1, len(items)))
small = sum(1 for i in range(10) for j in range(i + 1, 10))
big = sum(1 for i in range(2000) for j in range(i + 1, 2000))
assert big < small * 1000, f"10 items: {small} checks, 2000 items: {big:,} checks: fine on small input, slow on real data"Traceback (most recent call last):
File "/Users/you/python-course/steps.py", line 6, in <module>
assert big < small * 1000, f"10 items: {small} checks, 2000 items: {big:,} checks: fine on small input, slow on real data"
^^^^^^^^^^^^^^^^^^
AssertionError: 10 items: 45 checks, 2000 items: 1,999,000 checks: fine on small input, slow on real dataAssertionError: 10 items: 45 checks, 2000 items: 1,999,000 checks: ...: קוד שנראה מהיר על 10 פריטים עלול לקרוס על אלפים. בודקים גם קלט גדול.AssertionError: 10 items: 45 checks, 2000 items: 1,999,000 checks: ...: code that seems fast on 10 items can crawl on thousands. Test big input too.02Big OBig O
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:
import math
print(f"{'n':>9} {'O(1)':>5} {'O(log n)':>9} {'O(n)':>10} {'O(n^2)':>16}")
for n in [10, 1_000, 1_000_000]:
print(f"{n:>9,} {1:>5} {math.ceil(math.log2(n)):>9} {n:>10,} {n * n:>16,}") n O(1) O(log n) O(n) O(n^2)
10 1 4 10 100
1,000 1 10 1,000 1,000,000
1,000,000 1 20 1,000,000 1,000,000,000,000צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
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.
בודקים in על רשימה בתוך לולאה, ומקבלים O(n²) בלי לשים לב.
Checking in on a list inside a loop, getting O(n²) without noticing.
import time
seen = list(range(20_000))
wanted = list(range(10_000, 30_000))
start = time.perf_counter()
common = [x for x in wanted if x in seen]
slow = time.perf_counter() - start
assert slow < 0.01, f"took {slow:.1f}s: `x in list` scans the whole list every time; use a set"Traceback (most recent call last):
File "/Users/you/python-course/bigo.py", line 7, in <module>
assert slow < 0.01, f"took {slow:.1f}s: `x in list` scans the whole list every time; use a set"
^^^^^^^^^^^
AssertionError: took 1.6s: `x in list` scans the whole list every time; use a setAssertionError: in על רשימה הוא O(n), ובתוך לולאה זה O(n²). set(seen) הופך כל בדיקה ל-O(1).AssertionError: in on a list is O(n), inside a loop that's O(n²). set(seen) makes each check O(1).03חיפוש בינאריBinary search
חיפוש בינארי הוא האלגוריתם הקלאסי: ברשימה ממוינת, מסתכלים על האמצע. אם המבוקש גדול יותר, כל החצי השמאלי לא רלוונטי. בכל צעד חצי מהרשימה נעלם, ולכן מיליון פריטים דורשים רק כ-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:
מה קורה עכשיוWhat happens now
מסך הפלטOutput screen
import bisect
def steps_binary(n):
lo, hi, steps = 0, n - 1, 0
target = n - 1
while lo <= hi:
steps += 1
mid = (lo + hi) // 2
if mid == target:
return steps
if mid < target:
lo = mid + 1
else:
hi = mid - 1
for n in [1_000, 1_000_000, 1_000_000_000]:
print(f"{n:>13,} items: {steps_binary(n)} steps")
print(bisect.bisect_left([96, 208, 240, 412], 240)) 1,000 items: 10 steps
1,000,000 items: 20 steps
1,000,000,000 items: 30 steps
2חיפוש בינארי הוא כמו משחק "גבוה-נמוך" עם מספר בין 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.
חיפוש בינארי על רשימה לא ממוינת.
Binary search on an unsorted list.
import bisect
pages = [412, 96, 604, 240]
i = bisect.bisect_left(pages, 240)
assert i < len(pages) and pages[i] == 240, f"bisect said index {i}: the list was not sorted"Traceback (most recent call last):
File "/Users/you/python-course/binary.py", line 4, in <module>
assert i < len(pages) and pages[i] == 240, f"bisect said index {i}: the list was not sorted"
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: bisect said index 2: the list was not sortedAssertionError: בינארי מניח שהרשימה ממוינת. ממיינים קודם (O(n log n)), או משתמשים בחיפוש רגיל.AssertionError: binary search assumes a sorted list. Sort first (O(n log n)), or use a plain search.צפו איפה זה נשברWatch where it breaks
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
חיפוש בינארי חוצה את הטווח בכל צעד.
Binary search halves the range every step.
secret, lo, hi, tries = 37, 1, 100, 0
while lo <= hi:
mid = (lo + hi) // 2
tries += 1
if mid == secret:
break
if mid < secret:
lo = mid + 1
else:
hi = mid - 1
print("found", mid, "in", tries, "tries")found 37 in 3 tries
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
04מבנה הנתונים הנכוןThe right data structure
לעיתים קרובות השיפור הגדול ביותר לא בא מאלגוריתם חכם, אלא ממבנה נתונים נכון. 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:
import timeit
n = 100_000
as_list = list(range(n))
as_set = set(as_list)
t_list = timeit.timeit(lambda: (n - 1) in as_list, number=200)
t_set = timeit.timeit(lambda: (n - 1) in as_set, number=200)
print("list faster?", t_list < t_set)
print(f"set is about {t_list / t_set:,.0f}x faster here" if t_set else "set is instant")list faster? False set is about 6,822x faster here
| פעולהOperation | listlist | set / dictset / dict |
|---|---|---|
x in ...x in ... | O(n) | O(1) |
| גישה לפי אינדקס / מפתחAccess by index / key | O(1) | O(1) |
| הוספה בסוףAppend at the end | O(1) | O(1) |
| הוספה בהתחלהInsert at the start | O(n) | אין סדרNo order |
| מיוןSorting | O(n log n) | —— |
רשימה היא כמו ערימת מכתבים: כדי למצוא אחד מחפשים. 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.
set לא שומר סדר.
A set doesn't keep order.
titles = ["Dune", "Emma", "Matilda", "Dune"]
unique = list(set(titles))
assert unique == ["Dune", "Emma", "Matilda"], f"got {unique}: a set has no order"Traceback (most recent call last):
File "/Users/you/python-course/structures.py", line 3, in <module>
assert unique == ["Dune", "Emma", "Matilda"], f"got {unique}: a set has no order"
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: got ['Matilda', 'Emma', 'Dune']: a set has no orderAssertionError: לסדר מקורי בלי כפילויות: list(dict.fromkeys(titles)).AssertionError: for the original order without duplicates: list(dict.fromkeys(titles)).צפו איפה זה נשברWatch where it breaks
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
05מיוןSorting
מיון בועות הוא האלגוריתם הראשון שכולם לומדים: עוברים שוב ושוב ומחליפים זוגות שבסדר הפוך. הוא פשוט להבנה, אבל 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:
def bubble_sort(items):
a = list(items)
swaps = 0
for end in range(len(a) - 1, 0, -1):
for i in range(end):
if a[i] > a[i + 1]:
a[i], a[i + 1] = a[i + 1], a[i]
swaps += 1
return a, swaps
pages = [412, 96, 604, 240, 474, 208]
print(bubble_sort(pages))
print(sorted(pages) == bubble_sort(pages)[0])
books = [("Emma", 474), ("Dune", 412), ("Matilda", 240)]
print(sorted(books, key=lambda b: b[1]))([96, 208, 240, 412, 474, 604], 8)
True
[('Matilda', 240), ('Dune', 412), ('Emma', 474)]מיון בועות הוא כמו לסדר ילדים בתור לפי גובה כשכל אחד יכול רק להתחלף עם השכן שלו: זה עובד, אבל לוקח הרבה סיבובים.
Bubble sort is like lining children up by height when each may only swap with a neighbour: it works, but takes many rounds.
ממיינים ברשימה עם טיפוסים מעורבים.
Sorting a list of mixed types.
print(sorted([412, "96", 240]))Traceback (most recent call last):
File "/Users/you/python-course/sorting.py", line 1, in <module>
print(sorted([412, "96", 240]))
~~~~~~^^^^^^^^^^^^^^^^^^
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).צפו איפה זה נשברWatch where it breaks
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
06רקורסיהRecursion
רקורסיה היא פונקציה שפותרת בעיה בעזרת גרסה קטנה יותר של אותה בעיה. לכל רקורסיה צריך מקרה בסיס שבו עוצרים, אחרת היא קוראת לעצמה לנצח. היא מתאימה במיוחד למבנים מקוננים, כמו תיקייה שיש בה תיקיות, או קטגוריות בתוך קטגוריות:
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:
מה קורה עכשיוWhat happens now
פלטOutput
משתנים (frames)Variables (frames)
אובייקטים בזיכרוןObjects in memory
רקורסיה היא כמו בובות בבושקה: כדי לספור את כולן, פותחים בובה, סופרים אותה, ומבקשים מהבובה שבתוכה לספור את עצמה.
Recursion is like Russian dolls: to count them all, open a doll, count it, and ask the doll inside to count itself.
רקורסיה בלי מקרה בסיס.
Recursion without a base case.
def countdown(n):
countdown(n - 1)
countdown(5)Traceback (most recent call last):
File "/Users/you/python-course/recursion.py", line 4, in <module>
countdown(5)
~~~~~~~~~^^^
File "/Users/you/python-course/recursion.py", line 2, in countdown
countdown(n - 1)
~~~~~~~~~^^^^^^^
File "/Users/you/python-course/recursion.py", line 2, in countdown
countdown(n - 1)
~~~~~~~~~^^^^^^^
File "/Users/you/python-course/recursion.py", line 2, in countdown
countdown(n - 1)
~~~~~~~~~^^^^^^^
[Previous line repeated 996 more times]
RecursionError: maximum recursion depth exceededRecursionError: 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.פונקציה שקוראת לעצמה עם בעיה קטנה יותר, עד תנאי עצירה.
A function that calls itself on a smaller problem, down to a base case.
def fact(n):
if n <= 1:
return 1
return n * fact(n - 1)
print(fact(4))24
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
סיימתם את ההרצאה!Lecture complete!
עכשיו המצגת לחזרה מהירה, או ישר לתרגול.
Next: the slides for a quick review, or straight to practice.