國立暨南國際大學 105 學年度第一學期 期末考試卷

科目名稱:計算機概 論 開課系所:資訊工程 學系 考試日期 2017.1.4
系所別:
年級:
學號:
姓名:
考試時間 08:20-10:00
1
2
3
4
5  
6
7  
8
9  
10

  1. (10%) Determine whether the following code has syntax errors or not.  If it is correct, predict its output.  If it is incorrect, point out the mistake(s).

    # String Methods (P.142)
    def main():
        plaintext = "FCPPXOCYYECP"
        t = ['ABCDE', 'FGHIJ', 'KLMNO', 'PQRST', 'UVWXY']
        ciphertext = enc(plaintext, t)
        print(ciphertext)

    def enc(s, tabula):
        ciphertext = ""
        for i in range(0, len(s)-1, 2):
            x1, y1, x2, y2 = findDiagonal(tabula, s[i:i+2])
            c3c4 = getDiagonal(tabula, x1, y2, x2, y1)
            ciphertext = ciphertext + c3c4
        return ciphertext

    def getDiagonal(tabula, x1, y1, x2, y2):
        return tabula[x1][y1] + tabula[x2][y2]

    def findDiagonal(tabula, s):
        # s is a 2-character string
        c1, c2 = s[0], s[1]
        longStr = "".join(tabula)
        p1 = longStr.find(c1)
        x1, y1 = p1 // 5, p1 % 5
        p2 = longStr.find(c2)
        x2, y2 = p2 // 5, p2 % 5
        return x1, y1, x2, y2

    if __name__ == "__main__":
        main()


  2. (10%) Determine whether the following code has syntax errors or not.  If it is correct, predict its output.  If it is incorrect, point out the mistake(s).

    # Recursive Functions (P.468)
    def anagrams(s):
        if s == "":
            return [s]
        else:
            ans = []
            for w in anagrams(s[1:]):
                for pos in range(len(w)+1):
                    ans.append(w[:pos]+s[0]+w[pos:])
            return ans

    print( anagrams("book") )


  3. (10%) Determine whether the following code has syntax errors or not.  If it is correct, predict its output.  If it is incorrect, point out the mistake(s).

    # Merge Sort (P.479)
    def showList(nums):
        for x in nums:
            if x == nums[-1]:
                print(x, end='\n')
            else:
                print(x, end='\t')

    def merge(lst1, lst2, lst3):
        i1, i2, i3 = 0, 0, 0  # all start at the front
        n1, n2 = len(lst1), len(lst2)

        while i1 < n1 and i2 < n2:
            if lst1[i1] < lst2[i2]: # top of lst1 is smaller
                lst3[i3] = lst1[i1] #  copy it into current spot in lst3
                i1 = i1 + 1
            else:                   # top of lst2 is smaller
                lst3[i3] = lst2[i2] #  copy itinto current spot in lst3
                i2 = i2 + 1
            i3 = i3 + 1             # item added to lst3, update position

        while i1 < n1:
            lst3[i3] = lst1[i1]
            i1 = i1 + 1
            i3 = i3 + 1

        while i2 < n2:
            lst3[i3] = lst2[i2]
            i2 = i2 + 1
            i3 = i3 + 1

    def mergeSort(nums):
        n = len(nums)
        if n > 1:
            m = n//2
            nums1, nums2 = nums[:m], nums[m:]
            mergeSort(nums1)
            mergeSort(nums2)
            merge(nums1, nums2, nums)
            showList(nums)

    a = [82, 45, 30, 48, 61, 77, 2, 14, 98, 57]
    mergeSort(a)


  4. (10%) Determine whether the following code has syntax errors or not.  If it is correct, predict its output.  If it is incorrect, point out the mistake(s).

    # Nested loop (P.254)  and break (P.263)
    sum = 0
    i = 1
    while i < 5:
        j = i
        while j < 6:
            sum = sum + j
            if i < j: break
            j = j + 1
        i = i + 1
    print(sum)


  5. (10%) Determine whether the following code has syntax errors or not.  If it is correct, predict its output.  If it is incorrect, point out the mistake(s).

    # String Formatting (P.154)
    N = 5
    s = " "*N + "{0}"
    for i in range(N):
        print( s[N-i:].format( "*"*(2*(N-i)-1) ) )

  6. (10%) Determine whether the following code has syntax errors or not.  If it is correct, predict its output.  If it is incorrect, point out the mistake(s).

    #
    List slicing and concatenation (P.367)
    s1 = [1,2,3,4]
    s2=['a','b','c','d']
    print(s1[:2] + s2[-1:])

  7. (10%) Determine whether the following code has syntax errors or not.  If it is correct, predict its output.  If it is incorrect, point out the mistake(s).

    # File I/O (P.158)
    def generate_data_file():
        ex7_data = """klim:10 20 30\nmilk:199
    oak:100\nred:200 10
    joe:198 22\nmarry:20\njulie:2000"""
        outfile = open("ex7.dat", "w")
        print(ex7_data, file=outfile)
        outfile.close()

    def main():
        generate_data_file()
        infile = open("ex7.dat", "r")
        for line in infile:
            name, numbers = line.split(':')
            sum = 0
            numbers = numbers.split()
            for num in numbers:
                sum = sum + eval(num)
            print(name, int(sum / len(numbers)), sep=':' )
        infile.close()

    if __name__ == "__main__":
        main()


  8. (10%) Determine whether the following code has syntax errors or not.  If it is correct, predict its output.  If it is incorrect, point out the mistake(s).
    # Define a class for Polynomial (P.321)
    class Polynomial:
        def __init__(self, aList):
            self.coefficients = aList
        def __str__(self):
            def needPlus(coefficient, order):
                if order == 0:
                    necessity = False
                else:
                    if coefficient > 0:
                        necessity = True
                    else:
                        necessity = False
                return necessity

            result = ""
            cList = self.coefficients
            for i in range( len(cList) ):
                a = cList[i]        # coefficient

                if i == 0:
                    expo = ''
                elif i == 1:
                    expo = 'x'
                else:
                    expo = "x**" + str(i)

                if a != 0:
                    if needPlus(a, i):
                        if a == 1:   # i must be gt 0, because needPlus
                            result = result + "+" + expo
                        else:
                            result = result + "+" + str( a ) + expo
                    else:
                        if a == -1 and i > 0:
                            result = result + '-' + expo
                        else:
                            result = result + str(a) + expo
            return result

    p1 = Polynomial([0, 0, 7])
    p2 = Polynomial([0, 1, 0])
    print(p1)
    print(p2)

  9. (10%) Determine whether the following code has syntax errors or not.  If it is correct, predict its output.  If it is incorrect, point out the mistake(s).

    # Dictionary (P.401)
    def generate_data_file():
        ex9_data = """klim 10 20 milk 199 joe 20
    oak 100 red 200 10 klim 30
    joe 199  marry 20 julie 2000"""
        outfile = open("ex9.dat", "w")
        print(ex9_data, file=outfile)
        outfile.close()

    def main():
        generate_data_file()
        infile = open("ex9.dat", "r")
        count = {}  # Dictionary
        sum = {}
        for line in infile:
            for item in line.split():
                if item.isalpha():
                    name = item
                else:
                    if not name in count:
                        count[name] = sum[name] = 0
                    count[name] = count[name] + 1
                    sum[name] = sum[name] + eval(item)
        infile.close()
        for k in sorted(count.keys()):
            print(k, count[k], sum[k])

    if __name__ == "__main__":
        main()

  10. (10%) Determine whether the following code has syntax errors or not.  If it is correct, predict its output.  If it is incorrect, point out the mistake(s).

    # Key Function for Sorting (P.377)
    class Student:
        def __init__(self, i, n, s):
            self.id, self.name, self.score = i, n, s
        def __str__(self):
            return str(self.id) + ' ' + self.name + ' ' + str(self.score)

    def score(aStudent):
        return 100 - aStudent.score

    students = [Student(580, "Alice",   35),
                Student(191, "Bob",     75),
                Student(641, "Charlie", 76),
                Student(813, "Dennis",  27),
                Student(809, "Emily",   79),
                Student(568, "Fiona",   65) ]
    students.sort(key=score)
    print( students[1] )