נבנה על ידיBuilt by Ariel Yohimovich

PythonPython
34
חלקPart 6: Python בעידן ה-AI וקריירהPython in the AI era & career כ-3 שעות (כולל הפסקה)About 3 hours (with a break)

אלגוריתמים וסיבוכיותAlgorithms & complexity

חיפוש בינארי, מיון, Big-O ובחירת מבנה נתונים.

Binary search, sorting, Big-O and choosing a data structure.

או Ctrl+Por Ctrl+P

הנקודות החשובותKey points

  • אלגוריתם = מתכוןAn algorithm = a recipe
  • ב-10 ספרים הכול מהירWith 10 books everything is fast
  • O(1): קבוע, לא תלוי בגודלO(1): constant, independent of size
  • O(n): לולאה אחתO(n): one loop
  • רק ברשימה ממוינתOnly on a sorted list
  • בודקים אמצע, זורקים חציCheck the middle, throw away half
  • רשימה: סדר, אינדקס. in הוא O(n)List: order, index. in is O(n)
  • set ו-dict: גיבוב, in הוא O(1)set and dict: hashing, in is O(1)
  • מיון בועות: O(n²), טוב ללמידהBubble sort: O(n²), good for learning

מונחיםTerms

  • אלגוריתםalgorithm: סדרת צעדים מוגדרת לפתרון בעיה, כמו מתכון. לאותה בעיה יש לפעמים אלגוריתמים מהירים ואיטיים.A defined series of steps solving a problem, like a recipe. The same problem may have fast and slow algorithms.
  • Big OBig O: דרך לתאר איך זמן הריצה גדל כשהקלט גדל: O(n) = פי 2 קלט, פי 2 זמן. O(n²) = פי 2 קלט, פי 4 זמן.A way to describe how running time grows as input grows: O(n) = twice the input, twice the time. O(n²) = twice the input, four times the time.
  • חיפוש לינאריlinear search: בודקים פריט אחרי פריט עד שמוצאים. O(n).Check item after item until found. O(n).
  • חיפוש בינאריbinary search: ברשימה ממוינת: בודקים את האמצע וזורקים חצי בכל צעד. O(log n).In a sorted list: check the middle and discard half each step. O(log n).
  • טבלת גיבובhash table: המבנה שמאחורי dict ו-set: מוצא פריט לפי המפתח שלו כמעט מיד, O(1) בממוצע.The structure behind dict and set: finds an item by its key almost instantly, O(1) on average.
  • רקורסיהrecursion: פונקציה שקוראת לעצמה על בעיה קטנה יותר, עד מקרה בסיס פשוט.A function that calls itself on a smaller problem, down to a simple base case.

Cheatsheet

למהWhy
def linear_steps(items, target):
    steps = 0
    for x in items:
        steps += 1
        if x == target:
            break
    return steps
Big OBig O
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,}")
בינאריBinary
def search(nums, target):
    lo, hi = 0, len(nums) - 1
    while lo <= hi:
        mid = (lo + hi) // 2
        if nums[mid] == target:
            return mid
        if nums[mid] < target:
מבניםStructures
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)
מיוןSorting
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]

שגיאות שפגשנוErrors we met

שגיאהErrorמה זה אומרWhat it meansמה עושיםWhat to do
AssertionErrorבודקים מהירות רק על קלט קטן.Checking speed only on a tiny input.AssertionError: 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.
AssertionErrorבודקים in על רשימה בתוך לולאה, ומקבלים O(n²) בלי לשים לב.Checking in on a list inside a loop, getting O(n²) without noticing.AssertionError: 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).
AssertionErrorחיפוש בינארי על רשימה לא ממוינת.Binary search on an unsorted list.AssertionError: בינארי מניח שהרשימה ממוינת. ממיינים קודם (O(n log n)), או משתמשים בחיפוש רגיל.AssertionError: binary search assumes a sorted list. Sort first (O(n log n)), or use a plain search.
AssertionErrorset לא שומר סדר.A set doesn't keep order.AssertionError: לסדר מקורי בלי כפילויות: list(dict.fromkeys(titles)).AssertionError: for the original order without duplicates: list(dict.fromkeys(titles)).
TypeErrorממיינים ברשימה עם טיפוסים מעורבים.Sorting a list of mixed types.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).
RecursionErrorרקורסיה בלי מקרה בסיס.Recursion without a base case.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.

נבנה על ידיBuilt by Ariel Yohimovich