דיבאג עם VS CodeDebugging with VS Code
נקודות עצירה, צעד-אחר-צעד, צפייה במשתנים ושיטה למציאת באגים.
Breakpoints, stepping, watching variables and a method for finding bugs.
תקנו את הממוצעFix the average
תזכורת: מה ביקשוReminder: the task
הפונקציה מחזירה ממוצע שגוי. מצאו את הבאג (אפשר עם הדפסות) ותקנו. average([10, 20, 30]) צריך להיות 20.
The function returns a wrong average. Find the bug (prints help) and fix it. average([10, 20, 30]) should be 20.
הפתרון המלא והפלט שלוFull solution and its output
def average(nums):
total = 0
for n in nums:
total += n
return total / len(nums)
print(average([10, 20, 30]))20.0
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
הספר שלא נמצאThe book that isn't found
תזכורת: מה ביקשוReminder: the task
החיפוש לא מוצא את dune אף שהספר קיים. השתמשו ב-repr כדי לראות למה, ותקנו כך ש-find("dune") תחזיר True.
The search doesn't find dune although the book exists. Use repr to see why, and fix it so find("dune") returns True.
הפתרון המלא והפלט שלוFull solution and its output
shelf = [" Dune", "Emma ", "Matilda"]
def find(title):
for b in shelf:
if b.strip().lower() == title.strip().lower():
return True
return False
print(find("dune"))True
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
שלושה באגיםThree bugs
תזכורת: מה ביקשוReminder: the task
הפונקציה אמורה להחזיר רשימה של המספרים הזוגיים מ-1 עד n (כולל). יש בה שלושה באגים. תקנו את כולם.
The function should return a list of even numbers from 1 to n (inclusive). It has three bugs. Fix them all.
הפתרון המלא והפלט שלוFull solution and its output
def evens(n):
result = []
for i in range(1, n + 1):
if i % 2 == 0:
result.append(i)
return result
print(evens(10))[2, 4, 6, 8, 10]
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
assert שמגןA guarding assert
תזכורת: מה ביקשוReminder: the task
הוסיפו ל-discount(price, percent) שני assert: המחיר חיובי, והאחוז בין 0 ל-100 (עם הודעות). הפונקציה מחזירה את המחיר אחרי הנחה, מעוגל ל-2.
Add two asserts to discount(price, percent): the price is positive, and percent is 0 to 100 (with messages). It returns the price after the discount, rounded to 2.
הפתרון המלא והפלט שלוFull solution and its output
def discount(price, percent):
assert price > 0, "price must be positive"
assert 0 <= percent <= 100, f"percent must be 0-100, got {percent}"
return round(price * (1 - percent / 100), 2)
print(discount(80, 25))60.0
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
מדף, צעד 14: באג במדףShelf, step 14: a shelf bug
תזכורת: מה ביקשוReminder: the task
בגרסה הזו של המדף, מחיקת ספר מוחקת לפעמים ספר אחר, והספירה שגויה. מצאו ותקנו את שני הבאגים כך ש-remove_book תמחק לפי כותרת ו-count תחזיר את המספר הנכון.
In this shelf version, removing a book sometimes removes a different one, and the count is wrong. Find and fix both bugs so remove_book removes by title and count returns the right number.
הפתרון המלא והפלט שלוFull solution and its output
shelf = [{"title": "Dune"}, {"title": "Emma"}, {"title": "Matilda"}]
def remove_book(shelf, title):
for i, b in enumerate(shelf):
if b["title"] == title:
del shelf[i]
return True
return False
def count(shelf):
return len(shelf)
remove_book(shelf, "Emma")
print([b["title"] for b in shelf], count(shelf))['Dune', 'Matilda'] 2
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
חיפוש בינארי שבורA broken binary search
תזכורת: מה ביקשוReminder: the task
החיפוש הבינארי (נלמד לעומק במפגש 34) נתקע או מפספס את הפריט האחרון. תקנו אותו כך שיחזיר את האינדקס של target ברשימה ממוינת, או -1.
This binary search (covered in session 34) hangs or misses the last item. Fix it to return target's index in a sorted list, or -1.
הפתרון המלא והפלט שלוFull solution and its output
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:
lo = mid + 1
else:
hi = mid - 1
return -1
print(search([3, 8, 12, 20, 31], 31))4
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
רישום ביומןLogging it
תזכורת: מה ביקשוReminder: the task
כתבו process(orders) שעוברת על מחירים: מחיר שלילי נרשם כ-WARNING ומדולג, מחיר 0 נרשם כ-INFO ומדולג, והשאר נסכמים. הגדירו logging לרמת INFO עם הפורמט %(levelname)s: %(message)s ל-stdout, והדפיסו את הסכום.
Write process(orders) over prices: a negative price logs a WARNING and is skipped, 0 logs INFO and is skipped, the rest are summed. Configure logging at INFO with format %(levelname)s: %(message)s to stdout, and print the total.
הפתרון המלא והפלט שלוFull solution and its output
import logging
import sys
logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s", stream=sys.stdout, force=True)
log = logging.getLogger("orders")
def process(orders):
total = 0
for p in orders:
if p < 0:
log.warning(f"negative price: {p}")
continue
if p == 0:
log.info("free item skipped")
continue
total += p
return total
print(process([40, -5, 0, 60]))WARNING: negative price: -5 INFO: free item skipped 100
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.