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

הפתרון המלא
סעיף א:
[1, 10, 1, 2]
[10, 1, 2, 1]סעיף ב:
1
3
Noneסעיף ג:
We!! d1
!!eW
Well doneשאלה 2 · 25 נקודות
מיון תחנות אוטובוס לפי מרחק

הפתרון המלא
סעיף א:
def distance(bus_stop):
return (bus_stop[1][0]**2 + bus_stop[1][1]**2)**0.5
def sort_bus_stops(bus_stops):
bus_stops.sort(key=distance)
# אפשר היה גם
# SelectionSort or BubbleSort (~ O(n²))סעיף ב:
def k_farthest(bus_stops, k):
sort_bus_stops(bus_stops)
return bus_stops[-k:]
# פתרון נוסף
def bubble(lst, end_idx):
for i in range(end_idx):
if distance(lst[i]) > distance(lst[i+1]):
lst[i], lst[i+1] = lst[i+1], lst[i]
def k_farthest(bus_stops, k):
for i in range(len(bus_stops)-1, len(bus_stops)-1-k, -1):
bubble(bus_stops, i)
return bus_stops[len(bus_stops)-k:]שאלה 3 · 25 נקודות
מכפלת וקטורים וכפל מטריצות

הפתרון המלא
סעיף א:
def vec_mul(vec_a, vec_b):
# Get the length of the vectors
len_a = len(vec_a)
len_b = len(vec_b)
# Create the result matrix and fill it with zeros
result=[[0 for _ in range(len_b)] for _ in range(len_a)]
# Perform vector multiplication
for i in range(len_a):
for j in range(len_b):
result[i][j] = vec_a[i] * vec_b[j]
return resultסעיף ב:
def mat_mult(vec_a, vec_b, vec_c, vec_d):
# סעיף ב'.
# vec_a, vec_c: וקטור עמודה
# vec_b, vec_d: וקטור שורה
# Get the number of rows and columns for the resulting matrix
mat_a = vec_mul(vec_a, vec_b)
mat_b = vec_mul(vec_c, vec_d)
rows_a = len(mat_a)
cols_a = len(mat_a[0])
rows_b = len(mat_b)
cols_b = len(mat_b[0])
# Check if multiplication is possible
if cols_a != rows_b:
return -1
# Create the result matrix and fill it with zeros
result=[[0 for _ in range(cols_b)] for _ in range(rows_a)]
# Perform matrix multiplication
for i in range(rows_a):
for j in range(cols_b):
for k in range(cols_a):
result[i][j] += mat_a[i][k] * mat_b[k][j]
return resultשאלה 4 · 25 נקודות
מספר מרבי של שיעורים ברקורסיה

הפתרון המלא
התשובה:
def get_max_courses(courses, i=0):
if len(courses) == 0:
return 0
# if we can't attend first course and its mandatory - fail
if courses[0][3] and courses[0][2] < i:
return -1
# option 1: use first course (if possible)
option1 = 0
if courses[0][2] >= i:
option1=get_max_courses(courses[1:],courses[0][2]+courses[0][1])+1
# options 2: don't use first course
option2 = -1
if not courses[0][3]:
option2 = get_max_courses(courses[1:], i)
return max(option1, option2)