פתרונות בקוד לבעיות

Image

הוראות המופיעות בגוף של מבנה while ומתבצעות כל עוד תנאי הלולאה מתקיים צריכות להיות מוזזות ימינה ביחס לשורה הראשונה במבנה. הקוד התקין:

age = input(‘Insert age; -1 to stop: ‘)

while age != ‘-1’:

    print(age)

    age = input(‘Insert age; -1 to stop: ‘)

 

בעיה א’

• פתרון ראשון – 

def deleteStrings(lst):

    lst = lst[:]

    newLst = [] 

    for item in lst: 

        if type(item) != str: 

            newLst.append(item)

    return newLst

פתרון שני  – 

def deleteStrings(lst):

    lst = lst[:]

    i = 0

    while i < len(lst): 

        item = lst[i]

        if type(item) == str: 

            lst.remove(item)

        else: 

            i += 1

    return lst

פתרון שלישי –

def deleteStrings(lst):

    lst = lst[:]

    for i in range(len(lst) – 1, -1, -1): 

        if type(lst[i]) == str: 

            del lst[i] 

    return lst 

בעיה ב’

(א)

s1 = “Christmas without presents.”

s2 = “Christmas won’t be Christmas without any presents.”

i = 0

found = False

while i < len(s1) and not found: 

    substring = s1[:i]

    if substring not in s2: 

        print(substring)

        found = True 

        continue 

    i = i + 1

(ב) 

s1 = “Christmas without presents.”

s2 = “Christmas won’t be Christmas without any presents.”

found = False

for i in range(1, len(s1) + 1): 

    for j in range(len(s1)):

        substring = s1[j:j+i]

        if len(substring) == i and substring not in s2 and not found: 

            print(substring)

            found = True

(ג) 

def findShortest(s1, s2): 

    for i in range(1, len(s1) + 1): 

        for j in range(len(s1)):

            substring = s1[j:j+i]

            if len(substring) == i and substring not in s2: 

                return substring

 

בעיה ג’

פתרון א’

def sortPositives(nums):

    positiveNums = [] 

    for num in nums: 

        if num > 0: 

            positiveNums.append(num)

    positiveNums.sort()

    j = 0 

    for i in range(len(nums)): 

        if nums[i] > 0: 

            nums[i] = positiveNums[j]

            j += 1 

    return nums

פתרון ב’

def sortPositives(nums): 

    positiveNums = [] 

    inds = []     

    for i in range(len(nums)):         

        if nums[i] > 0: 

            inds.append(i)

            positiveNums.append(nums[i])

    positiveNums.sort() 

    for i in range(len(positiveNums)):             

        nums[inds[i]] = positiveNums[i]

    return nums

בעיה ד’

פתרון א’

def multipleAndConsecutive(s): 

    chars = set() 

    for char in set(s): 

        times = s.count(char)        

        if times > 1 and char * times in s:         

            chars.add(char)

    return chars

פתרון ב’

def multipleAndConsecutive(s): 

    chars = set() 

    for char in set(s):         

        if s.count(char) >= 2:                         

            consecutive = True 

            currentInd = s.find(char)

            while currentInd != -1 and consecutive: 

                nextInd = s.find(char, currentInd + 1)

                if (nextInd != -1 and 

                    currentInd + 1 != nextInd):

                    consecutive = False 

                    continue 

                currentInd = nextInd              

            if consecutive: 

                chars.add(char)

    return chars

 

בעיה ה’

books = [‘1984’, ‘Dracula’, ‘Ulysses’, ‘Beloved’]

printed = [] 

for book1 in books: 

    for book2 in books: 

        for book3 in books: 

            if book1 != book2 and book2 != book3 and book1 != book3: 

                sortedTriad = sorted([book1, book2, book3])

                if sortedTriad not in printed: 

                    print([book1, book2, book3])

                    printed.append(sortedTriad)

בעיה ו’

def oneEligible(idsAndAges, maxSum): 

    itemsCopy = list(idsAndAges.items()) 

    while itemsCopy: 

        key1, val1 = itemsCopy.pop()

        for key2, val2 in itemsCopy:                       

            if val1 + val2 <= maxSum:

                del idsAndAges[key1]

                del idsAndAges[key2]

                return [[key1, key2], idsAndAges]

    return [[], idsAndAges]

 

בעיה ז’

def game100(player1, player2):

    import random 

    roundNum = 1

    curPlayer = player1 

    nextPlayer = player2

    points = {player1:0, player2:0} 

    while points[nextPlayer] <= 100:        

        cube1 = random.randint(1, 6)

        cube2 = random.randint(1, 6)

        if (cube1 == roundNum and cube2 == roundNum):

            points[curPlayer] += 21

        elif (cube1 == roundNum or cube2 == roundNum):

            points[curPlayer] += playNum

        curPlayer, nextPlayer = nextPlayer, curPlayer

        roundNum = (roundNum + 1) % 7

    return [points[curPlayer], curPlayer]

 

בעיה ח’

(א)

def numsFreq(nums):     

    return {num : nums.count(num) for num in set(nums)}

(ב)

def digitsFreq(nums):    

    d = {} 

    for num in nums: 

        digits = set(str(num))

        for digit in digits:             

            intDigit = int(digit)

            if intDigit not in d: 

                d[intDigit] = 1 

            else: 

                d[intDigit] += 1

    return d 

 

בעיה ט’

def mostActive(erruptions, measure): 

    mountains = {} 

    for erruption in erruptions: 

        if erruption[2] > measure: 

            if erruption[1] not in mountains: 

                mountains[erruption[1]] = 1

            else:

                mountains[erruption[1]] += 1       

    revMountains = [[freq, name] for name, freq in mountains.items()] 

    return sorted(revMountains, reverse = True)[0][1]

בעיה י’

def winners(types, choices): 

    choices = choices[:]

    winners = set() 

    while sum(types) != 0 and choices: 

        applicant, typeInd = choices[0]         

        if types[typeInd] > 0: 

            types[typeInd] -= 1 

            winners.add(applicant)

        del choices[0]

    return sorted(list(winners))

בעיה י”א

def digitsAndNums(nums):    

    d = {} 

    for num in nums: 

        digits = set(str(num))

        for digit in digits:             

            intDigit = int(digit)

            if intDigit not in d: 

                d[intDigit] = [num,]

            else: 

                d[intDigit] += [num]

    for k in d: 

        d[k] = tuple(d[k])    

    return d 

בעיה י”ב

import random

def game():

    d = {}

    stop = False

    while not stop:

        name = input(“Please enter name: “)

        if (name == “end”):

            stop = True

            continue

        computer = “enm”[random.randint(0, 2)]

        player = input(“Please enter item: “)

        winner = 0

        if ((player == “n”) & (computer == “e”)

            |

            (player == “e”) & (computer == “m”)

            |

            (player == “m”) & (computer == “n”)

            ):

            winner = 1

        if name not in d.keys():

            d[name] = [1, winner]

        else:                        

            d[name][0] += 1

            d[name][1] += winner

    return d

בעיה י”ג

(א)

def tableByInds(table, inds):

    filteredDict = {}

    for key, values in table.items():

        filteredDict[key] = [values[ind] for ind in inds]

    return filteredDict

(ב)

def filterTable(table, colName, values):     

    inds = [] 

    for ind in range(len(table[colName])): 

        if table[colName][ind] in values: 

            inds.append(ind)        

    return tableByInds(table, inds)

(ג)

def sortTable(table, colname, rev = False):     

  valuesAndIndices=[[table[colname][ind], ind] for ind in range(len(table[colname]))]  

  valuesAndIndices = sorted(valuesAndIndices, reverse = rev)    

  return tableByInds([item[1] for item in valuesAndIndices], indsList)

בעיה י”ד

def insertWord(myDict, word):  

    key = word.count(‘a’)

    if key not in myDict: 

        myDict[key] = [word]

    else: 

        i = 0         

        while i < len(myDict[key]) and len(word) > len(myDict[key][i]):          

            i = i + 1

        myDict[key].insert(i, word)

    return myDict

בעיה ט”ו

def pricesDiffs(dicts): 

    alwaysSold = set(dicts[0].keys())

    for d in dicts[1:]:         

        alwaysSold = alwaysSold & set(d.keys())            

    return {product : dicts[-1][product] – dicts[0][product] for product in alwaysSold}

בעיה ט”ז

(א)

def getPatientsDetails(patientsDict):

  proceed = True    

  while proceed:        

    if (input(“Get details of a new patient (‘y’ or ‘n’)? “) == ‘y’):                                 

      hospitalName = input(“Enter hospital name: “)

      patientCode = int(input(“patient code: “))

      patientDetails = input(“Age, days, recovery status: “)                        

      if patientsDict.get((hospitalName, patientCode), False):

        print(“Patient’s details will be updated.”)

      patientDetailsList = patientDetails.split(‘,’)

      patientDetailsTuple = (int(patientDetailsList[0]),

                             int(patientDetailsList[1]),

                             eval(patientDetailsList[2]))

      patientsDict[(hospitalName, patientCode)] = patientDetailsTuple

    else:

      proceed = False

  return patientsDict

(ב)

def recoveryByHospital(patientsDict, recovered = 1):

    hospitalNames = {key[0] for key in patientsDict}    

    results = []        

    for name in sorted(hospitalNames):

        numOfRecoveries = 0        

        patientsNum = 0        

        for k, v in patientsDict.items():            

            if k[0] == name:

                patientsNum += 1                

                if v[2]: numOfRecoveries += 1

        if (recovered == 1):

            results.append([name, numOfRecoveries])

        else:

            results.append([name, patientsNum – numOfRecoveries])

    return results

בעיה י”ז

def minimalText(filename, chars): 

    f = open(filename, “r”)

    s = “”  

    ch = f.read(1)  

    while chars != {} and ch != “”: 

        s += ch 

        if ch in chars: 

            if chars[ch] == 1: 

                del chars[ch]            

            else: 

                chars[ch] -= 1            

        if not chars: 

            return s 

        ch = f.read(1)

    f.close() 

    return “”

בעיה י”ח

def produceCSVDict(filename): 

    f = open(filename)

    s = f.read() 

    f.close()     

    csvDict = {}

    lines = s.split(“\n”)    

    colnames = lines[0].split(“,”)    

    for line in lines[1:]:

        words = line.split(“,”)                

        for i in range(len(words)):            

            if colnames[i] not in csvDict:

                csvDict[colnames[i]] = [words[i]]

            else:

                csvDict[colnames[i]].append(words[i])

    return csvDict

בעיה י”ט

def getFileString(filename): 

    f = open(filename, ‘r’)

    s = f.read()

    f.close() 

    return s

 

def getCleanFile(s, puncts): 

    s = s.lower() 

    newS = “” 

    for c in s: 

        if c not in puncts: 

            newS = newS + c 

        else: 

            newS = newS + ” “

    return newS

 

def findWordsAndFreqs(text, wordFirst = True): 

    words = text.split()

    wordsAndFreqs = () 

    for word in set(words): 

        if wordFirst: 

            wordsAndFreqs += ((word, words.count(word)),)    

        else: 

            wordsAndFreqs += ((words.count(word), word),)    

    return wordsAndFreqs

 

def compareFreqs(filename1, filename2, puncts, exclude):

    cleanText1 = getCleanFile(getFileString(filename1), puncts)    

    wordsAndFreq1 = findWordsAndFreqs(cleanText1, False)    

    sortedPairs = sorted(wordsAndFreq1, reverse = True)

    nonExcluded = [pair for pair in sortedPairs if pair[1] not in exclude] 

    cleanText2 = getCleanFile(getFileString(filename2), puncts)    

    wordsAndFreq2 = findWordsAndFreqs(cleanText2)    

    freqsDict = dict(wordsAndFreq2)

    result = () 

    for freq, word in nonExcluded[:10]: 

        result += ((word, freq, freqsDict.get(word, “NA”)),)    

    return result