אלגוריתמים וסיבוכיותAlgorithms & complexity
חיפוש בינארי, מיון, Big-O ובחירת מבנה נתונים.
Binary search, sorting, Big-O and choosing a data structure.
חיפוש בינאריBinary search
תזכורת: מה ביקשוReminder: the task
כתבו binary_search(nums, target) שמחזירה את האינדקס של target ברשימה ממוינת, או -1. בלי index ובלי bisect.
Write binary_search(nums, target) returning target's index in a sorted list, or -1. Without index or bisect.
הפתרון המלא והפלט שלוFull solution and its output
def binary_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:
lo = mid + 1
else:
hi = mid - 1
return -1
print(binary_search([96, 208, 240, 412, 604], 412), binary_search([96, 208], 100))3 -1
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
מ-O(n²) ל-O(n)From O(n²) to O(n)
תזכורת: מה ביקשוReminder: the task
common_slow(a, b) מחזירה את הפריטים של a שמופיעים גם ב-b (בסדר של a, בלי כפילויות), אבל היא O(n²). כתבו common_fast(a, b) שמחזירה אותה תוצאה ב-O(n) בעזרת set.
common_slow(a, b) returns a's items that also appear in b (in a's order, no duplicates), but it's O(n²). Write common_fast(a, b) returning the same result in O(n) using a set.
הפתרון המלא והפלט שלוFull solution and its output
def common_slow(a, b):
out = []
for x in a:
if x in b and x not in out:
out.append(x)
return out
def common_fast(a, b):
in_b, seen, out = set(b), set(), []
for x in a:
if x in in_b and x not in seen:
out.append(x)
seen.add(x)
return out
a = ["Dune", "Emma", "Dune", "Matilda"]
b = ["Matilda", "Dune", "Ulysses"]
print(common_fast(a, b), common_fast(a, b) == common_slow(a, b))['Dune', 'Matilda'] True
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
מיון בחירהSelection sort
תזכורת: מה ביקשוReminder: the task
כתבו selection_sort(items) שמחזירה רשימה ממוינת חדשה בלי sort/sorted: בכל סיבוב מוצאים את הקטן ביותר מהחלק שעוד לא מוין ומחליפים אותו לתחילת החלק.
Write selection_sort(items) returning a new sorted list without sort/sorted: each round, find the smallest in the unsorted part and swap it to the start of that part.
הפתרון המלא והפלט שלוFull solution and its output
def selection_sort(items):
a = list(items)
for i in range(len(a)):
smallest = i
for j in range(i + 1, len(a)):
if a[j] < a[smallest]:
smallest = j
a[i], a[smallest] = a[smallest], a[i]
return a
pages = [412, 96, 604, 240]
print(selection_sort(pages), pages)[96, 240, 412, 604] [412, 96, 604, 240]
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
רקורסיה: גודל תיקייהRecursion: folder size
תזכורת: מה ביקשוReminder: the task
תיקייה מיוצגת כמילון: מפתח שהוא שם קובץ ממופה לגודל (int), ומפתח שהוא שם תיקייה ממופה למילון נוסף. כתבו total_size(folder) רקורסיבית שמחזירה את סך הגדלים, ו-deepest(folder) שמחזירה את העומק המקסימלי (תיקייה ריקה = 1).
A folder is a dict: a file name maps to a size (int), and a sub-folder name maps to another dict. Write a recursive total_size(folder) returning the total size, and deepest(folder) returning the maximum depth (an empty folder = 1).
הפתרון המלא והפלט שלוFull solution and its output
def total_size(folder):
return sum(total_size(v) if isinstance(v, dict) else v for v in folder.values())
def deepest(folder):
return 1 + max((deepest(v) for v in folder.values() if isinstance(v, dict)), default=0)
project = {"shelf.py": 1200, "data": {"shelf.json": 800, "old": {"backup.json": 750}}, "README.md": 300, "empty": {}}
print(total_size(project), deepest(project))3050 3
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
מדף, צעד 34: חיפוש מהיר בספרייה גדולהShelf, step 34: fast search in a big library
תזכורת: מה ביקשוReminder: the task
כתבו מחלקה Index(books) שבונה פעם אחת: מילון ISBN → ספר, ומילון מילה (באותיות קטנות) → set של ISBN, מכל מילה בכותרת ובשם הסופר. by_isbn(isbn) היא O(1) (או None), ו-search(query) מחזירה כותרות ממוינות של ספרים שמכילים את כל מילות השאילתה. בדיקה על 50,000 ספרים צריכה לעבור מהר.
Write an Index(books) class that builds once: a dict ISBN → book, and a dict word (lowercase) → set of ISBNs, from every word in the title and author. by_isbn(isbn) is O(1) (or None), and search(query) returns sorted titles of books containing all query words. A test on 50,000 books must be fast.
הפתרון המלא והפלט שלוFull solution and its output
class Index:
def __init__(self, books):
self.by_id = {b["isbn"]: b for b in books}
self.words = {}
for b in books:
for w in (b["title"] + " " + b["author"]).lower().split():
self.words.setdefault(w, set()).add(b["isbn"])
def by_isbn(self, isbn):
return self.by_id.get(isbn)
def search(self, query):
sets = [self.words.get(w, set()) for w in query.lower().split()]
if not sets:
return []
return sorted(self.by_id[i]["title"] for i in set.intersection(*sets))
books = [{"isbn": "1", "title": "Dune", "author": "Frank Herbert"}, {"isbn": "2", "title": "Dune Messiah", "author": "Frank Herbert"},
{"isbn": "3", "title": "Matilda", "author": "Roald Dahl"}]
idx = Index(books)
print(idx.search("herbert dune"), idx.search("messiah"), idx.search("dahl dune"), idx.by_isbn("3")["title"])['Dune', 'Dune Messiah'] ['Dune Messiah'] [] Matilda
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
מיון מיזוגMerge sort
תזכורת: מה ביקשוReminder: the task
כתבו merge_sort(items) רקורסיבית: רשימה באורך 0 או 1 כבר ממוינת; אחרת מחלקים לשניים, ממיינים כל חצי, וממזגים שתי רשימות ממוינות בפונקציה merge(a, b). זה O(n log n).
Write a recursive merge_sort(items): a list of length 0 or 1 is already sorted; otherwise split in two, sort each half, and merge two sorted lists with merge(a, b). This is O(n log n).
הפתרון המלא והפלט שלוFull solution and its output
def merge(a, b):
out, i, j = [], 0, 0
while i < len(a) and j < len(b):
if a[i] <= b[j]:
out.append(a[i])
i += 1
else:
out.append(b[j])
j += 1
return out + a[i:] + b[j:]
def merge_sort(items):
if len(items) <= 1:
return list(items)
mid = len(items) // 2
return merge(merge_sort(items[:mid]), merge_sort(items[mid:]))
print(merge_sort([412, 96, 604, 240, 474, 208, 96]))[96, 96, 208, 240, 412, 474, 604]
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
k הגדוליםThe top k
תזכורת: מה ביקשוReminder: the task
כתבו top_k(books, k) שמחזירה את k הספרים הארוכים ביותר (לפי pages, מהארוך לקצר, ובשוויון לפי כותרת) בלי למיין את כל הרשימה: השתמשו ב-heapq.nlargest, שהוא O(n log k). ואז top_k_manual שעושה אותו דבר עם ערימה (heapq.heappush/heappushpop) בגודל k.
Write top_k(books, k) returning the k longest books (by pages, longest first, ties by title) without sorting the whole list: use heapq.nlargest, which is O(n log k). Then top_k_manual doing the same with a heap (heapq.heappush/heappushpop) of size k.
הפתרון המלא והפלט שלוFull solution and its output
import heapq
def rank_key(b):
return (b["pages"], [-ord(c) for c in b["title"]])
def top_k(books, k):
return [b["title"] for b in heapq.nlargest(k, books, key=rank_key)]
def top_k_manual(books, k):
heap = []
for i, b in enumerate(books):
item = (rank_key(b), i, b)
if len(heap) < k:
heapq.heappush(heap, item)
elif item > heap[0]:
heapq.heappushpop(heap, item)
return [b["title"] for _, _, b in sorted(heap, reverse=True)]
books = [{"title": "Dune", "pages": 412}, {"title": "Emma", "pages": 474}, {"title": "Atlas", "pages": 412}, {"title": "Matilda", "pages": 240}]
print(top_k(books, 3), top_k_manual(books, 3))['Emma', 'Atlas', 'Dune'] ['Emma', 'Atlas', 'Dune']
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.