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

הפתרון המלא
סעיף א:
['L', 't', 'i', '-', 'o']
['e', '-', 't', 'g', '!']
Elsa, the balloon. Let-it-go!סעיף ב:
[16, 9, 6, 7]
[36, 23, 13]
[0, 1, 2, 3, 4]סעיף ג:
[[10, 20], [99, 4], [5, 6]]
[[1, 2], [3, 4], [5, 6]]שאלה 2 · 25 נקודות
הספרה הגדולה ביותר ומיון k איברים

הפתרון המלא
סעיף א:
def find_largest_digit_index(nums):
if not nums:
return -1
largest_index = 0
max_digit = 0
for i in range(0, len(nums)):
num = abs(nums[i])
while num > 0:
digit = num % 10
if digit >= max_digit:
largest_index = i
max_digit = digit
num //= 10
return largest_indexסעיף ב:
def my_k_sort(nums, k):
if k <= 0:
return []
k=min(k,len(nums)) #Ensure k does not exceed the length of nums
for i in range(len(nums)-1, len(nums)-1-k, -1):
largest_index = find_largest_digit_index(nums[:i])
nums[largest_index],nums[i]=nums[i],nums[largest_index]שאלה 3 · 25 נקודות
חיפוש בינארי בתקופות בצורת

הפתרון המלא
סעיף א:
def drought_year(starts, ends, year):
low, high = 0, len(starts) - 1
while low <= high:
mid = (low + high) // 2
if starts[mid] <= year and year <= ends[mid]:
return mid
elif year < starts[mid]:
high = mid - 1
else:
low = mid + 1
return -1סעיף ב:
def yoni_scores(starts, ends, years):
correct_guesses = 0
for year in years:
if drought_year(starts, ends, year) != -1:
correct_guesses+=1
accuracy = (correct_guesses / len(years))*100
return accuracyסעיף ג:
k הוא אורך הרשימה years.
שאלה 4 · 25 נקודות
בדיקת ספרות ופענוח מחרוזת ברקורסיה

הפתרון המלא
סעיף א:
def my_isdigit(my_s):
for tav in my_s:
if not ("0"<=tav<="9"):
return False
return Trueסעיף ב:
def decode(s):
if not s:
return ""
if len(s) < 3 or my_isdigit(s[2]):
return s[1] * int(s[0]) + decode(s[2:])
return s[1:3] * int(s[0]) + decode(s[3:])