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

הפתרון המלא
סעיף א:
[0, 2, 3, 4, 5, 12, 'a', 'b']
['a', 'H']סעיף ב:
edcba
fdb
abcdefgסעיף ג:
[0, 0, 0, 3, 2, 2, 1]
[3, 2, 2, 1]
7
[3, 2, 2, 1, 0, 0, 0]שאלה 2 · 25 נקודות
פענוח מספר לאותיות בהזזה מעגלית

הפתרון המלא
סעיף א:
def num_to_chr(secret_num, k):
return chr((secret_num+k-ord('A')) % 26 + ord('A'))
# פתרון נוסף
# or equivalently
def num_to_chr(secret_num, k):
k = k%26
if secret_num + k > ord('Z'):
return chr(secret_num +k-ord('Z')+ord('A'))
else:
return chr(secret_num +k)סעיף ב:
def decode(secret_long_num, k):
res = ''
while secret_long_num > 0:
res += num_to_chr(secret_long_num % 100, k)
secret_long_num //= 100
return resשאלה 3 · 25 נקודות
מיזוג שלוש רשימות ממוינות

הפתרון המלא
התשובה:
def sort_by_year(bim, bam, bom):
sorted_tmp = index_sort(bim, bam)
sorted_final = index_sort(sorted_tmp, bom)
return sorted_final
# top-down design
# זו שיטת כתיבה וסידור קוד בקובץ פייתון כאשר הפתרון מחולק לפונקציות קטנות יחסית (ולפעמים ידועות כבר
# מהקורס) כך שקל לכתוב אות הקוד ולעקוב אחרי השגיאות ולעשות שינויים (אם צריך).
# מיזוג שתי רשימות ממוינות שנלמד בכיתה:
def index_sort(l1, l2):
sorted_lst = [0] * (len(l1) + len(l2))
i1, i2 = 0, 0
for i in range(len(sorted_lst)):
if i1 == len(l1):
sorted_lst[i] = l2[i2]
i2 += 1
elif i2 == len(l2):
sorted_lst[i] = l1[i1]
i1 += 1
elif l1[i1] < l2[i2]:
sorted_lst[i] = l1[i1]
i1 += 1
else:
sorted_lst[i] = l2[i2]
i2 += 1
return sorted_lstשאלה 4 · 25 נקודות
חיפוש ותת-קבוצה ברקורסיה

הפתרון המלא
סעיף א:
def in_rec(lst, value):
if not lst:
return False
if lst[0]==value:
return True
return in_rec(lst[1:], value)סעיף ב:
def is_subset(lst1, lst2):
# base case: an empty list is a subset of any list
if len(lst1) == 0:
return True
# recursive case:
#check if the first element of lst1 is in lst2
#and if the rest of lst1 is a subset of lst2
else:
return in_rec(lst2,lst1[0]) and is_subset(lst1[1:],lst2)