Hello, dear friend, you can consult us at any time if you have any questions, add WeChat: daixieit

CS1026 Computer Science Fundamentals: Final Exam Practice Questions

1.   What is value is returned if commonDivisor(10,5)is executed ?

def commonDivisor(n,d):

if (n%d==0):

return n

else:

return None

A. 2

B. 5

C. 10

D. None

E.   There is an execution error.

2.   What is printed by the following code snippet?

numList=[1,3,6,9]

for i in range(len(numList)):

print (i, end="-")

print()

A.1-3-6-9-

B.1-3-6-9

C.0-1-2-3

D.0-1-2-3-

E. None of the above

3.   Which of the following create an empty set?

A. s={}

B. s=[]

C. s=set([‘’])

D. s=set()

E.   None of the above

4.   What is printed by the following code snippet?

wordsList=['a']

wordsList.append('b')

wordsList.append('c')

wordsList.pop()

wordsList.append('d')

wordsList.append('e')

print(wordsList[:2])

A. [‘a’,’b’]

B. [‘b’,’c’]

C. [‘d’,’e’]

D. [‘c’,’d’]

E.   None of the above

5.   What is printed by the following code snippet?

line="This is question 5 for review for CS1206 in the fall of 2020" sum=0

for w in line:

if w.isdigit():

sum+=int(w)

print(sum)

A. 2025

B. 3231

C. 9

D. 20

E.   18

6.   Which of the following code snippets remove ‘$’ and ‘!’ in any order from right side of a sting, s?

A. s.rstrip(“$”)

B. s.lstrip(“!$”)

C. s.rstrip(“$”).rstrip(“!”)

D. s.rstrip(“!$”)

E.   None of the above

7.   What is the output of the following code snippet?

numset1 = {1, 1, 2, 3, 5, 8, 2, 3, 4, 5, 6}

numset2 = {2, 3, 4, 5, 7, 8, 9, 11}

numset3 = numset1.difference(numset2)

print(numset3)

A.   {2, 3, 4, 5, 8}

B.    {1, 1, 6}

C.    {7, 9, 11}

D.   {1, 6, 9, 11}

E.    {1, 6}

8.   Consider the following code segment:

print("W", end="")

try :

inFile = open("test.txt", "r")

line = inFile.readline()

value = int(line)

print("X", end="")

except IOError :

print("Y", end="")

except ValueError :

print("Z", end="")

What output is generated when this program runs if the file test.txt does not exist?

A.   W

B.   WZ

C.   WXZ

D.   WY

9.   Consider the following code segment:

fruit = {"Apple": "Green", "Banana": "Yellow"}

fruit["Plum"] = "Purple"

After it executes, what are the keys?

A.    "Apple", "Banana"

B.   “Plum”, "Apple", "Banana"

C.    "Green", "Yellow"

D.   "Green", "Purple", "Yellow"

10. Consider the following code segment:

student =

[{'name':'John','lastName':'Smith','course':['1026A','1026B','1027A']}, {'name':'Mario','lastName':'Rossi','course':['2026A','2026B','2027A']}]

Which of the following code snippet prints  '2026B'?

A. student[1][‘course’][2]

B. student[1][‘course’][1]

C. student[‘Mario’][‘course’][1]

D. student[0][‘course’][1]

E. None of the above

11. Assume that we store names and phone numbers in a dictionary as following:

phoneBook={'John':'5554441234','Kate':'4443331234'}

Which of the following code snippets print just names in the phonebook in one line?

a.   for k in phonebook.items():    print (phoneBook[k],end=’ ‘)

b.   for k in phonebook.items(): print (k,end=’ ‘)

c.   for k in phoneBook:  print (k, end=’ ’)

d.   for k in phoneBook:

print (phoneBook[k],end=’ ’)

e.   print(phonebook,end=’ ‘)

12. Consider the following code segment:

class Student :

def __init__(self, aName, anId):

self._name = aName

self._id = anId

def getName(self):

return self._name

def setName(self, newName):

self._name = newName

def

getId(self):

return self._id

student1=Student("John","1234567")

Which of the following code snippet is the correct way to print 'John'?

A. print (student1()._name)

B. print (._name)

C. print (student1.getName())

D. print (getName())

13. The function below is to compute the difference between an element in the list and the element  following it, i.e., subtracts the second element from the first, the third from the second, etc..  It is to return a list of these differences.  The program as logic errors.  From the list below, select the lines that all have errors.  Note: a line may contain more than one logic error.

1. def difflist(lst) :

2.    newlist = []

3.   for i in range(0,len(lst)) :

4.        n = lst[i-1]

5.        m = lst[i]

6.        newlist.append(m-n)

7.   return newlist

A.   Lines: 2,7

B.    Lines: 3,6

C.    Lines: 4,5

D.   Lines: 5,6

E.    Lines: 3,4

14. The following class, Message, is a class that might be used in designing an email system. Review the class definition and then answer the questions that follow.

class Message :

def __init__(self, sender, recipient) :

self._sender = sender

self._recipient = recipient

self._body = ""

def append(self, line) :

self._body = self._body + line + "\n"

def __repr__(self) :

result = "From: " + self._sender + "\n"

result = result + "To: " + self._recipient + "\n"

result = result + self._body

return result

What are the instance variables for this class?

A.  There are none.

B. self, sender, recipient, body

C. sender, recipient

D. _sender, _recipient, _body

E. sender, recipient

Which of the following would not be a reasonable getter or setter for this class?

A. setSender(self,snd)

B. getRecipient(self)

C. setRecipient(self,rec)

D. setMessageLine(self,line)

E.   All would be good getters or setters.

15. The following class, Mailbox, makes use of the class Message in the previous question and      stores a collection of messages.   Review the code that is given and then answer the questions that follow.

from message import Message

class Mailbox :

def __init__(self) :

self._messages = {}

def addMessage(self, messageId, message) :

self._messages[messageId] = message

def getMessage(self, index) :

return self._messages[index]

def print(self) :

for i in self._messages:

print(self._messages[i])

print()

What are the instance variables for this class?

A. message, messageId

B. _messages, message, messageId

C. messages, sender, recipient, body

D. _messages, _sender, _recipient, _body

E. _messages

Which of the following would be a valid method to remove a message from an object of the Message class given its id?

A. def removeMessage(self, id) : self._messages.pop(id)

B. def removeMessage(self, id) : self._messages.remove(id)

C. def removeMessage(self, id) : self._messages[id] = “”

D. def removeMessage(self, id) : if id in self._messages:

self._messages.pop(id)

E. def removeMessage(self, id): if id in self._messages:

self._messages.removeid)

A main program that will create a new mailbox, prompt a user for a sender, a receiver and multiple lines of a message, and add it to the mailbox has been started, but lines are missing.  Select the lines from the list below to complete the program.

from mailbox import Mailbox

from message import Message

# Create a mailbox and messages to it.

mbox = Mailbox()

sto = input("Enter who the message goes to: ")

sfrom = input("Enter who the message is from: ")

| line 1

aline = input("Enter a line of the message: ")

| line 2

| line 3

aline = input("Enter a line of the message: ")

mbox.addMessage(1,msg)

Lines of code:

1. msg = Message(sto,sfrom)

2. while sfrom != "":

3. msg.append(sfrom+sto+aline)

4. while aline == "":

5. msg[1] = aline

6. msg.append(aline)

7. msg = Message(sfrom,sto)

8. while aline != "":

A.  Line 1 is: 1 Line 2 is: 4 Line 3 is: 6

B.  Line 1 is: 1 Line 2 is: 8 Line 3 is: 6

C.  Line 1 is: 1 Line 2 is: 2 Line 3 is: 5

D.  Line 1 is: 7 Line 2 is: 4 Line 3 is: 6

E.   Line 1 is: 7 Line 2 is: 8 Line 3 is: 6

16. The program wordFrequency.py finds the frequency of words in a list of words and in a document that is provided by the user, as input.   There is a function

wordFrequency(l,wDict,words) that update the frequency of words in the dictionary (wDict) using the word in a line (l) and the list of predefined words (words); it strips off periods at the beginning or end of the word.  The Function, readFile() receives the name of the file   from the user and open the file. It returns the file object.

The program and function need to be completed.  Identify the number of the lines that are needed to complete the blanks in each Section of the code; the vertical bars indicate where the line of code is indented.  The code with blanks is below; lines to choose from follow.

# List of words to find their frequency

WORDSLIST=["Great","awesome","Good","happy","Excited"]

def wordFrequency(l,wDict,words):

|________Section 1

for w in splittedLine:

w=w.strip('. ')

if w in words:

try:

|________Section 2

|________

|________

def readFile():

try:

fileName = input("Enter file name: ")

inputFile=open(fileName,"r")

|________Section 3

|________Section 4

print ("The text file name does not exist.")

wordCountDict={}

|________Section 5

for line in inf:

|________Section 6

# Print out the words and their frequency

for key in wordCountDict:

print (key, "has frequency of ", wordCountDict[key])

Choose the lines from the list below; some lines may be used more than once.

1. return inputFile

2. inputFile=open(fileName,"r")

3. inputFile=open(fileName,"w")

4. inf=readFile()

5. readFile()

6. readFile(inf)

7. wordFrequency(line,wordCountDict,WORDSLIST)

8. wordFrequency(wordCountDict,WORDSLIST)

9. wordCountDict=wordFrequency(line,wordCountDict)

10. wordCountDict+=1

11. wDict[w]+=1

12. wDict[w]=1

13. wDict[w]=0

14. wDict[key]=1

15. splittedLine=l.split()

16. splittedLine=line.split()

17. splittedLine=l.split(‘ - ’)

18. splittedLine=splittedLine.strip('.')

19. except KeyError:

20. except IndexError

21. except ValueError

22. except FileNotFoundError:

16.1. Which line, in the order given, would complete Section #1 of the function wordFrequency(l,wDict,words)

a.   14

b.   17

c.   16

d.   15

e.   None of the above

16.2. Which lines, in the order given, would complete Section #2 of the function wordFrequency(l,wDict,words) ?

a.   11,18,11

b.   12,18,10

c.   11,20,12

d.   11,19,12

e.   None of the above

16.3. Which line would complete Section #3 of the function readFile()?

a.   6

b.   4

c.    1

d.   2

e.   None of the above

16.4. Which line would complete Section #4 of the function readFile()?

a.   19

b.   20

c.   21

d.   22

e.   None of the above

16.5. Which line would complete Section #5 of the main program?

a.   1

b.   6

c.   4

d.   5

e.   None of the above

16.6. Which line would complete Section #6 of the main program?

a.   10

b.   8

c.   7

d.   9

e.   None of the above