מבוא למחשב, שפת פייתוןלתרגל עם המורה AI

מבוא למחשב פייתון (02340128), חורף תשפ״ב · מועד א׳ · פתרונות מלאים

שאלות: 1 · 2 · 3 · 4

שאלה 1 · 25 נקודות

מעקב: רשימות, מחרוזות והעתקת מטריצה

שאלה 1
הפתרון המלא

סעיף א:

[3, 7, 6]
[7, 6, 3, 3, 6]

סעיף ב:

I have COVID19
I am vaccinated
I have covid19

סעיף ג:

[[10, 11, 12], [4, 5, 6], [7, 8, 9]]
[[0, 2, 3], [4, 0, 6], [7, 8, 0]]
[[10, 11, 12], [4, 5, 6], [7, 8, 9]]

שאלה 2 · 25 נקודות

מיון ממספר x בעזרת היסטוגרמה

שאלה 2
הפתרון המלא

התשובה:

def sort_from(num_lst, x):
    hist = [0] * 100
    for num in num_lst:
        hist[num - 1] += 1
    new_lst = []
    for i in range(x, 101):
        if hist[i - 1]:
            new_lst += [i] * hist[i - 1]
    for i in range(x - 1, 0, -1):
        if hist[i - 1]:
            new_lst += [i] * hist[i - 1]
    return new_lst

שאלה 3 · 25 נקודות

רשימה ממוינת מוזזת ציקלית

שאלה 3
הפתרון המלא

סעיף א:

def rotate_list(lst, d):
    len_l = len(lst)
    new_lst = [0] * len_l
    for i in range(len_l):
        new_lst[(i+d)%len_l] = lst[i]
    return new_lst

סעיף ב:

def find_rotation(lst):
    if lst[0]<lst[-1]: # already sorted
        return 0
    low, high = 0, len(lst)-1
    while low < high:
        mid = (low+high)//2
        if lst[mid] > lst[mid+1]:
            return mid+1
        elif lst[mid] > lst[low]:
            low = mid+1
        else:
            high = mid
    return low  # or high - they're equal

שאלה 4 · 25 נקודות

מצא את המטמון ברקורסיה

שאלה 4
הפתרון המלא

התשובה:

def treasure_hunt(map, i, act):
    if i >= len(map) or i < 0:
        return False
    elif len(act)==0:
        if map[i] == 1:
            return True
        else:
            return False
    return treasure_hunt(map,i,act[1:]) or\
                treasure_hunt(map,i+act[0],act[1:])\
            or treasure_hunt(map,i-act[0],act[1:])

לתרגל שאלות כאלה עם המורה AI