מבוא למחשב פייתון (02340128), חורף תשפ״ד · מועד א׳ · פתרונות מלאים
שאלה 1 · 25 נקודות
מעקב: חיתוך רשימות, מחרוזות ומטריצה

הפתרון המלא
סעיף א:
[1, 2, 6, 4, 4, 6]
[1, 2, 6, 4, 4, 6]
[1, 3, 5, 1]סעיף ב:
Bed
Ad12cסעיף ג:
[0, 1, 2, 3]
[0, 4, 8, 12]
[1, 5, 9, 13]
[2, 6, 10, 14]
[3, 7, 11, 15]
30שאלה 2 · 25 נקודות
שחזור רשימה ממספר והיסטוגרמה

הפתרון המלא
סעיף א:
def maximal_num_lst(num, max_num):
temp_val = 0
num_lst = []
while num:
if temp_val * 10 + num % 10 < max_num:
temp_val = temp_val * 10 + num % 10
num //= 10
else:
num_lst.append(temp_val)
temp_val = 0
if temp_val:
num_lst.append(temp_val)
return num_lstסעיף ב:
def hist_dist(lst, k, max_num):
hist = [0] * (max_num //k)
for i in lst:
hist[i//k] += 1
return histשאלה 3 · 25 נקודות
איתור הפרעה באק"ג בחיפוש בינארי

הפתרון המלא
התשובה:
def Ichilov_ECG(lst):
lo, hi = 0, len(lst) - 1
sign = 1 if lst[0] > 0 else -1
while (lo <= hi):
mid = (lo + hi) // 2
if mid == len(lst)-1:
return "Healthy"
elif lst[mid] > 0 and lst[mid+1] > 0:
return "Positive patent", mid+1
elif lst[mid] < 0 and lst[mid+1] < 0:
return "Negative patent", mid+1
if (mid % 2 == 0 and lst[mid] * sign > 0) or \
(mid % 2 and lst[mid] * sign < 0):
lo = mid + 1
else:
hi = mid – 1שאלה 4 · 25 נקודות
הסרת חזרות מרשימה ברקורסיה

הפתרון המלא
התשובה:
def unique_check(lst, i=1):
if not lst:
return []
if i == len(lst):
return [lst[0]] + unique_check(lst[1:])
elif lst[0] == lst[i]:
return unique_check(lst[:i] + lst[i+1:], i)
return unique_check(lst, i + 1)
# פתרון נוסף
# ==== without i
def unique_check(lst, i=1):
if len(lst)<=1:
return lst
if lst[0]==lst[1]:
# remove duplicate
return unique_check(lst[1:])
else:
# continue removing lst[0] from the rest of the lst
lst_clean = unique_check([lst[0]]+lst[2:])
# lst_clean is without duplicates of lst[0]
#now clean the rest
return [lst[0]]+unique_check([lst[1]]+lst_clean[1:])