Fundamentals of Python First Programs, 2nd Edition

Page 1

Fundamentals of Python First Programs, 2nd Edition

By Kenneth A. Lambert


Name:

Class:

Date:

Chapter 01: Basic Python Programming True / False 1. Python programs require two or more modules. a. True b. False ANSWER: False

2. The main python module contains the starting point of execution. a. True b. False ANSWER: True

3. You can use the # symbol to create a multiline comment. a. True b. False ANSWER: False

4. A docstring is another term for a Python variable that holds a string constant. a. True b. False ANSWER: False

5. The keyword while means the same thing as While in Python. a. True b. False ANSWER: False

6. In Python, _MyVar15 is a valid variable name. a. True b. False ANSWER: True

7. To make your program more secure, use obscure variable names such as xz14dEEa. a. True b. False ANSWER: False

8. The keywords True and False are floating point values. a. True b. False ANSWER: False

9. If you print the string "Hello, it is a very \nice day", there will be two lines of output. Copyright Cengage Learning. Powered by Cognero.

Page 1


Name:

Class:

Date:

Chapter 01: Basic Python Programming a. True b. False ANSWER: True

10. Use the comparison operator != to check if one value is not equal to another value. a. True b. False ANSWER: True

11. In Python, a variable containing the value 5 will evaluate as true if used with the and logical operator. a. True b. False ANSWER: True

12. The input function returns a numeric value by default. a. True b. False ANSWER: False

13. The print function outputs a newline by default before its arguments are printed. a. True b. False ANSWER: False

14. Standard functions and Python's library functions check the types of their arguments when the function is called. a. True b. False ANSWER: True

15. It is good practice to import all names from a module using the * operator. a. True b. False ANSWER: False

16. Indenting code that should be executed when an if statement evaluates as true makes your program easier to read, but the indentation is not necessary. a. True b. False ANSWER: False

17. The while statement uses the syntax while <Boolean expression>: and is the preferred control statement to iterate over a definite range of sequences. Copyright Cengage Learning. Powered by Cognero.

Page 2


Name:

Class:

Date:

Chapter 01: Basic Python Programming a. True b. False ANSWER: False

18. Strings are compared using ASCII ordering. a. True b. False ANSWER: True

19. Strings are mutable objects, which means you can replace their contents. a. True b. False ANSWER: False

20. You can use the slice operator to obtain a substring from a string. a. True b. False ANSWER: True

21. A literal representation of a list is made using parentheses to enclose items separated by commas. a. True b. False ANSWER: False

22. A list mutator is a method used to modify the contents of a list. a. True b. False ANSWER: True

23. A tuple is an immutable sequence of items and does not have mutator methods. a. True b. False ANSWER: True

24. The expression primes = (2, 3, 5, 7, 11) creates a list named primes. a. True b. False ANSWER: False

25. A dictionary object contains zero or more entries where each entry associates a unique key with a value. a. True b. False Copyright Cengage Learning. Powered by Cognero.

Page 3


Name:

Class:

Date:

Chapter 01: Basic Python Programming ANSWER: True

Multiple Choice 26. What is the name of the function that contains the starting point of program execution? a. start b. main c. begin d. enter ANSWER: b

27. To create an end-of-line comment, which symbol do you use to begin the comment? a. # b. * c. / d. @ ANSWER: a

28. What can you use a docstring for? a. to hold the name of a document file b. to create a large string variable c. to hold data of type string d. to create a multiline comment ANSWER: d

29. Which of the following is true about Python keywords? a. they can begin with a number, letter, or hyphen b. they are case sensitive c. they are written in uppercase d. they can be a maximum of 6 characters long ANSWER: b

30. Which statement is true about Python syntax? a. a code block must begin with a left brace b. each code statement must end with a semicolon c. white space is ignored d. blocks of code are indicated by indentation ANSWER: d

31. What keywords does Python use for Boolean values? a. Yes, No b. On, Off Copyright Cengage Learning. Powered by Cognero.

Page 4


Name:

Class:

Date:

Chapter 01: Basic Python Programming c. True, False d. Set, Unset ANSWER: c

32. What symbol is used to insert a tab in a string? a. \t b. [TAB] c. /t d. @tab ANSWER: a

33. Which comparison operation returns True if variable x is not equal to variable y? a. x .ne. y b. x neq y c. x <> y d. x != y ANSWER: d

34. Assume x is equal to 5 and y is equal to 0. Which comparison operation returns True? a. x == y or y b. y < 5 and y c. (x > y) and x d. x > 0 and None ANSWER: c

35. With what character does the print function terminate its output by default? a. newline b. null c. period d. space ANSWER: a

36. What keyword is used to make a multiway if statement? a. else b. elif c. then d. elseif ANSWER: b

37. Which statement allows a programmer to run a module as a standalone program or import it from the shell? a. do _module(main) Copyright Cengage Learning. Powered by Cognero.

Page 5


Name:

Class:

Date:

Chapter 01: Basic Python Programming b. while main != _module c. if self == "main()": d. if __name__ == "__main__": ANSWER: d

38. What is the output of the following code? sum = 0 value = 3 while value <= 5: sum += value value += 1 print(sum) a. 15 b. 10 c. 12 d. 18 ANSWER: c

39. What is the output of the following code? sum = 0 for value in range(1,4): sum += value print(sum) a. 5 b. 10 c. 4 d. 6 ANSWER: d

40. What is the output of the following code? sum = 0 for value in range(1,4): if value == 2: sum = sum**2 sum += value print(sum) a. 6 b. 12 c. 8 Copyright Cengage Learning. Powered by Cognero.

Page 6


Name:

Class:

Date:

Chapter 01: Basic Python Programming d. 16 ANSWER: a

41. What are the values of variables x, y, and z after the following code is run? y = 0 z = 0 for x in range(5,7): if y > z: z, y = y, z y = y + x; a. x == 7, y == 11, z == 6 b. x == 6, y == 6, z == 5 c. x = 6, y == 5, z == 6 d. x == 7, y == 12, z == 5 ANSWER: b

42. What is the value of z after the following code is run? y = 0 z = 0 for x in range(5,8): z = max(x, y) y = y + x a. 18 b. 11 c. 7 d. 13 ANSWER: b

43. What is the value of string1 after the following statement is executed? string1 = "hello"[:3] + "python"[0] a. lpython b. llo c. help d. lop ANSWER: c

44. What is the last line of the output when the following code is executed? x = 2 Copyright Cengage Learning. Powered by Cognero.

Page 7


Name:

Class:

Date:

Chapter 01: Basic Python Programming for exp in range (5): print ("%2d.0" % x**exp) a. 8.0 b. 16 c. 32 d. 16.0 ANSWER: d

45. What is the value of newList after the following code is executed? newList = ["George", "John", "Thomas", "James"] newList.pop() newList.append("Andrew") a. ["George", "John", "Thomas", "James", "Andrew"] b. ["George", "John", "Thomas", "Andrew"] c. ["Andrew", "John", "Thomas", "James"] d. ["Andrew", "George", "John", "Thomas", "James"] ANSWER: b

46. Which of the following statements creates a tuple containing four items? a. t = [1: 2: 3: 4] b. t = {1, 2, 3, 4} c. t = <1; 2; 3; 4> d. t = (1, 2, 3, 4) ANSWER: d

47. What is the last line of output of the following code? pres = {1:"Washington", 16:"Lincoln", 35: "Kennedy", 40:"Reagan"} for nth in pres: print("%2d:" % nth,pres[nth]) a. 35: Kennedy b. 40: Reagan c. 03: Kennedy d. 04: Reagan ANSWER: b

48. Which of the following correctly defines a function named myFunc? a. def myFunc(): b. func myfunc: Copyright Cengage Learning. Powered by Cognero.

Page 8


Name:

Class:

Date:

Chapter 01: Basic Python Programming c. myfunc()# d. int myFunc: ANSWER: a

49. How do you describe a function that calls itself? a. self_calling function b. iterative function c. derivative function d. recursive function ANSWER: d

50. Select the answer that should be used to replace the missing code in the following statements. myList = list() fileObj = open("myfile.dat", "rb") while True: try: item = pickle.load(fileObj) myList.append(item) <missing code> fileObj.close() break print(myList)

a. if EOF: b. elif Error: c. except EOFError: d. else while TRUE: ANSWER: c

51. In a class definition, what type of method uses the values of the object's instance variables without changing them? a. constructor b. accessor c. instance d. mutator ANSWER: b

Copyright Cengage Learning. Powered by Cognero.

Page 9


Name:

Class:

Date:

Chapter 01: Introduction True / False 1. Computer science focuses on a broad set of interrelated ideas. a. True b. False ANSWER: True

2. Informally, a computing agent is like a recipe. a. True b. False ANSWER: False

3. An algorithm describes a process that ends with a solution to a problem. a. True b. False ANSWER: True

4. Each individual instruction in an algorithm is well defined. a. True b. False ANSWER: True

5. An algorithm describes a process that may or may not halt after arriving at a solution to a problem. a. True b. False ANSWER: False

6. An algorithm solves a general class of problems. a. True b. False ANSWER: True

7. The algorithms that describe information processing can also be represented as information. a. True b. False ANSWER: True

8. When using a computer, human users primarily interact with the memory. a. True b. False ANSWER: False

9. Information is stored as patterns of bytes (1s and 0s). Copyright Cengage Learning. Powered by Cognero.

Page 1


Name:

Class:

Date:

Chapter 01: Introduction a. True b. False ANSWER: False

10. The part of a computer that is responsible for processing data is the central processing unit (CPU). a. True b. False ANSWER: True

11. Magnetic storage media, such as tapes and hard disks, allow bit patterns to be stored as patterns on a magnetic field. a. True b. False ANSWER: True

12. A program stored in computer memory must be represented in binary digits, which is also known as ASCII code. a. True b. False ANSWER: False

13. The most important example of system software is a computer's operating system. a. True b. False ANSWER: True

14. An important part of any operating system is its file system, which allows human users to organize their data and programs in permanent storage. a. True b. False ANSWER: True

15. A programmer typically starts by writing high-level language statements in a text editor. a. True b. False ANSWER: True

16. Ancient mathematicians developed the first algorithms. a. True b. False ANSWER: True

17. In the 1930s, the mathematician Blaise Pascal explored the theoretical foundations and limits of algorithms Copyright Cengage Learning. Powered by Cognero.

Page 2


Name:

Class:

Date:

Chapter 01: Introduction and computation. a. True b. False ANSWER: False

18. The first electronic digital computers, sometimes called mainframe computers, consisted of vacuum tubes, wires, and plugs, and filled entire rooms. a. True b. False ANSWER: True

19. In the early 1940s, computer scientists realized that a symbolic notation could be used instead of machine code, and the first assembly languages appeared. a. True b. False ANSWER: False

20. The development of the transistor in the early 1960s allowed computer engineers to build ever smaller, faster, and less expensive computer hardware components. a. True b. False ANSWER: False

21. Moore's Law states that the processing speed and storage capacity of hardware will increase and its cost will decrease by approximately a factor of 3 every 18 months. a. True b. False ANSWER: False

22. In the 1960s, batch processing sometimes caused a programmer to wait days for results, including error messages. a. True b. False ANSWER: True

23. In 1984, Apple Computer brought forth the Macintosh, the first successful mass-produced personal computer with a graphical user interface. a. True b. False ANSWER: True

24. By the mid 1980s, the ARPANET had grown into what we now call the Internet, connecting computers owned by large institutions, small organizations, and individuals all over the world. Copyright Cengage Learning. Powered by Cognero.

Page 3


Name:

Class:

Date:

Chapter 01: Introduction a. True b. False ANSWER: True

25. In Python, the programmer can force the output of a value by using the cout statement. a. True b. False ANSWER: False

Multiple Choice 26. How is data stored within a computer's memory? a. It is stored as hexadecimal data. b. It is stored as octal data. c. It is stored as binary data. d. It is stored in plain text data. ANSWER: c

27. In a computer, what component is known as the "processor"? a. RAM b. CPU c. basic input/output devices d. motherboard ANSWER: b

28. A flash memory stick is an example of what type of storage media? a. magnetic storage media b. optical storage media c. electrical storage media d. semiconductor storage media ANSWER: d

29. What program is used by a programmer to convert high-level code into executable code? a. translator b. run-time system c. interpreter d. text editor ANSWER: a

30. What problem was the Atanasoff-Berry Computer designed to solve? a. The automatic creation of ballistics tables for the U.S. military. b. The coded transmissions used by Germany in WWII. Copyright Cengage Learning. Powered by Cognero.

Page 4


Name:

Class:

Date:

Chapter 01: Introduction c. The solving of systems of simultaneous linear equations. d. The calculation of maritime navigation routes for the U.S. Navy. ANSWER: c

31. Who is credited as having created the World Wide Web in 1992? a. Steve Jobs b. Albert Gore c. Tim Berners-Lee d. Paul Allen ANSWER: c

32. What kind of programming language is Python? a. An interpreted language. b. A compiled language. c. A interpolated language. d. A manufactured language. ANSWER: a

33. What is the name used for the integrated program development environment that comes with a Python installation? a. Eclipse b. IDLE c. PyShell d. PyDDL ANSWER: b

34. While viewing a screen displaying an active IDLE session, what does green text mean? a. The text is the result of output, or is the name of a function. b. The text represents a string. c. The text is a built-in function name. d. The text indicates a variable's name. ANSWER: b

35. What built-in function should you use in Python to prompt a user for data input? a. input b. cin c. prompt d. get ANSWER: a

36. What would be the output if you were to print the variable named value as declared by this statement: value = "2" + "2"? Copyright Cengage Learning. Powered by Cognero.

Page 5


Name:

Class:

Date:

Chapter 01: Introduction a. The number "4". b. A floating point value of 4.0. c. The string "22". d. A type error, as integers cannot be concatenated. ANSWER: c

37. When a Python interpreter runs a script, what is the script translated into? a. assembly code b. byte code c. interpolated language code d. ELF-formatted binary ANSWER: b

38. What component of Python is responsible for the execution of Python byte code? a. IDLE b. Python interpreter c. Python virtual machine (PVM) d. Python Script Engine (PSE) ANSWER: c

39. At what point in the interpretation of a Python program are syntax error messages generated? a. After the conversion of the code into byte code. b. Before execution of the program, when it is passed through the translator. c. During execution of the program by the Python virtual machine. d. After user input defined by the program is collected. ANSWER: b

40. When using IDLE for Python programming, what color is used to distinguish built-in function names? a. blue b. green c. purple d. red ANSWER: c

41. What language, created by Tim Berners-Lee, allows browsers to structure the information to be displayed on Web pages? a. Python b. HTML c. HTTP d. Java ANSWER: b Copyright Cengage Learning. Powered by Cognero.

Page 6


Name:

Class:

Date:

Chapter 01: Introduction 42. What processor was contained in the first mass-produced personal computer? a. Intel 8080 b. AMD486 c. NEC V20 d. Motorola 88000 ANSWER: a

43. What type of processing occurs when processes run for a slice of time, then yield access to the CPU to another process, cycling through processes repeatedly? a. coalescent processing b. cooperative processing c. concurrent processing d. divisive processing ANSWER: c

44. What is NOT one of the initial four locations connected by the ARPANET in the 1970s? a. Stanford Research Institute b. University of California at Los Angeles c. UC Santa Barbara d. Massachusetts Institute of Technology ANSWER: d

45. Regardless of whether print is passed a single or multiple expressions, what does output always end with by default? a. A carriage return. b. A null terminator. c. A newline. d. An EOL. ANSWER: c

46. In order to change the print function to output on the same line as the previous one, without printing a newline, what expression can be added? a. terminator = "" b. end = "" c. eol = "" d. newline = 0 ANSWER: b

47. What language was designed based on a theory of recursive functions and is considered to be an ideal language for solving difficult or complex problems? a. COBOL b. FORTRAN Copyright Cengage Learning. Powered by Cognero.

Page 7


Name:

Class:

Date:

Chapter 01: Introduction c. LISP d. Assembler ANSWER: c

48. What technology replaced the vacuum tube as the mechanism for implementing electronic switches in computer hardware? a. transistor b. resistor c. fully programmable gate array d. microprocessor ANSWER: a

49. When reading the syntax for the print command, what does the ellipsis between expressions indicate? a. They indicate that all expressions are required to be included. b. They indicate that the program has a minimum number of expressions that must be included. c. They indicate that you must pass a value of specific type to the expression. d. They indicate that you could include multiple expressions after the first one. ANSWER: d

50. What was the first PC-based operating system called? a. Microsoft Disk Operating System (MS-DOS) b. UNIX c. Linux d. Control Program for Microcomputers (CP/M) ANSWER: d

Copyright Cengage Learning. Powered by Cognero.

Page 8


Name:

Class:

Date:

Chapter 02: 2. An Overview of Collections True / False 1. A collection contains at least one item. a. True b. False ANSWER: False

2. The use of collections is a Python programming requirement, but they are not very useful for working with real-world objects. a. True b. False ANSWER: False

3. A set is a built-in Python collection type. a. True b. False ANSWER: True

4. A tuple is an immutable collection type. a. True b. False ANSWER: True

5. A line of customers waiting to get into a movie is an example of a hierarchical collection. a. True b. False ANSWER: False

6. Graph collections are organized in a parent/children relationship. a. True b. False ANSWER: False

7. A search operation is usually more efficient on a sorted collection than on an unsorted collection. a. True b. False ANSWER: True

8. A sorted collection must be in a linear structure, ordered by position. a. True b. False ANSWER: False Copyright Cengage Learning. Powered by Cognero.

Page 1


Name:

Class:

Date:

Chapter 02: 2. An Overview of Collections 9. To traverse a collection's items, use the for loop. a. True b. False ANSWER: True

10. Use the & operator to concatenate two collections. a. True b. False ANSWER: False

11. To determine equality of two collections, use the == operator. a. True b. False ANSWER: True

12. The pop method is used to add items to a Python list. a. True b. False ANSWER: False

13. All collections are also iterable objects. a. True b. False ANSWER: True

14. If you clone an object using the = operator (as in myList=list(yourList)), the is operator returns True while the == operator returns False. a. True b. False ANSWER: False

15. When collections share mutable items, a deep copy using a for loop should be used to explicitly clone items before adding them to a new collection. a. True b. False ANSWER: True

16. To be considered equal, two lists must have the same length and the same items in each position, whereas the same sets must simply contain exactly the same items, but in no particular order. a. True b. False ANSWER: True Copyright Cengage Learning. Powered by Cognero.

Page 2


Name:

Class:

Date:

Chapter 02: 2. An Overview of Collections 17. When using a for loop to iterate over a list, the items are visited in no particular order. a. True b. False ANSWER: False

18. The map, filter, and reduce functions can only be used on list collections. a. True b. False ANSWER: False

19. By default, items in a sorted collection are visited in descending order when using a for loop iterator. a. True b. False ANSWER: False

20. When a shallow copy of a collection is made, only references to the items in the existing collection are copied to the new collection. a. True b. False ANSWER: True

21. In computer science, collections are also called objective data types (ODTs). a. True b. False ANSWER: False

22. In computer science, abstraction is used for ignoring or hiding details that are nonessential. a. True b. False ANSWER: True

23. In Python, modules and methods are the smallest units of abstraction, classes are the next in size, and functions are the largest. a. True b. False ANSWER: False

24. Without abstraction, you would need to consider all aspects of a software system simultaneously. a. True b. False ANSWER: True

25. Python includes two implementations of lists: arrays and linked lists. Copyright Cengage Learning. Powered by Cognero.

Page 3


Name:

Class:

Date:

Chapter 02: 2. An Overview of Collections a. True b. False ANSWER: False

Multiple Choice 26. What is a group of zero or more items that can be operated on as a unit? a. grouping b. collection c. array d. organization ANSWER: b

27. Which of the following is true about Python collections? a. most can be heterogeneous b. all are homogeneous c. they are typically static d. all are immutable object types ANSWER: a

28. Which object type is immutable? a. list b. set c. dict d. tuple ANSWER: d

29. Which type of collection is ordered by position? a. linear b. hierarchical c. graph d. sorted ANSWER: a

30. Which real-world item best represents a linear collection? a. file system b. organizational chart c. stack of bricks d. table of contents ANSWER: c

31. Which real-world item best represents a hierarchical collection? Copyright Cengage Learning. Powered by Cognero.

Page 4


Name:

Class:

Date:

Chapter 02: 2. An Overview of Collections a. a queue of customers b. wiring diagrams c. a box of legos d. a family tree ANSWER: d

32. Which statement is true about a sorted collection? a. must be ordered by position b. they need not be linear c. searching is inefficient d. a box of donuts is an example ANSWER: b

33. Which of the following is an unordered collection? a. string b. stack c. dictionary d. queue ANSWER: c

34. Which Python function returns the total number of items in a collection? a. sizeof b. len c. count d. total ANSWER: b

35. Which operator can you use to test for item membership in a collection? a. in b. == c. @ d. is ANSWER: a

36. What is the value of c after the following code executes? a = [10, 20, 30] b = [40, 50, 60] c = a + b a. [50, 70, 90] b. {[10, 20, 30], [40, 50, 60]} Copyright Cengage Learning. Powered by Cognero.

Page 5


Name:

Class:

Date:

Chapter 02: 2. An Overview of Collections c. [10, 20, 30, 40, 50, 60] d. ([10, 40], [20, 50], [30, 60]) ANSWER: c

37. Which of the following is a special case of type conversion, where the two collections are of the same type? a. replacing b. copying c. duplicating d. cloning ANSWER: d

38. What is the value of aList after the following code is executed? aList = [10, 20, 30] aList.pop()

a. [10, 20, 30] b. [10, 20] c. [] d. [20, 30] ANSWER: b

39. What is the value of aList after the following code is executed? aList = [1, 2, 3] aList.remove(2) a. [1, 2] b. [1, 3] c. [3] d. [1] ANSWER: b

40. What is the value of myObject after the following code executes? yourObject = "Hi" myObject = tuple(yourObject) a. ('H', 'i') b. ["H", "i"] c. (Hi) d. ("Hi") Copyright Cengage Learning. Powered by Cognero.

Page 6


Name:

Class:

Date:

Chapter 02: 2. An Overview of Collections ANSWER: a

41. What is the value of newList after the following code executes? newList = list(range(9, 0, -3)) a. [8, 5, 2] b. [9, 6, 3, 0] c. [9, 6, 3] d. [] ANSWER: c

42. What is the value of newObject after the following code executes? newObject = tuple("Hello") a. ('H', 'e', 'l', 'l', 'o') b. ["Hello"] c. ("Hello") d. ['H', 'e', 'l', 'l', 'o'] ANSWER: a

43. What is the value of r after the following code executes? myList = [2, 3, 5, 7, 11] yourList = list(myList) r = yourList is myList a. [2, 3, 5, 7, 11] b. True c. None d. False ANSWER: d

44. What is the value of r after the following code executes? mySet = {2, 3, 5, 7, 11} yourSet = {5, 7, 2, 11, 3} r = yourSet == mySet a. {5, 7, 2, 11, 3} b. True c. False d. 0 Copyright Cengage Learning. Powered by Cognero.

Page 7


Name:

Class:

Date:

Chapter 02: 2. An Overview of Collections ANSWER: b

45. What can a programmer do to prevent side effects from cloning mutable objects? a. create a deep copy using a for loop b. create a shallow copy using a type conversion c. create a deep copy using a type conversion d. use the assignment operator instead of a type conversion ANSWER: a

46. When a for loop is used to iterate over a collection, which statement is true? a. list items are visited from last to first b. items in a list are visited in a random order c. items in a sorted collection are visited in ascending order d. items in a dictionary are visited in descending order ANSWER: c

47. Which of the following lists Python units of abstraction from smallest to largest? a. classes, methods, functions, modules b. functions, methods, classes, modules c. modules, functions, methods, classes d. modules, classes, methods, function ANSWER: b

48. In what order are dictionary items visited during an iteration? a. the order in which they were added b. ascending, by key value c. descending, by item value d. no particular order ANSWER: d

49. Which operator is used to obtain a string representation of a collection? a. len b. char c. str d. in ANSWER: c

50. In which type of collection does each item have many predecessors and successors, called neighbors? a. linear b. hierarchical c. graph Copyright Cengage Learning. Powered by Cognero.

Page 8


Name:

Class:

Date:

Chapter 02: 2. An Overview of Collections d. unordered ANSWER: c

Copyright Cengage Learning. Powered by Cognero.

Page 9


Name:

Class:

Date:

Chapter 02: Software Development, Data Types, and Expressions True / False 1. Computer scientists refer to the process of planning and organizing a program as software development. a. True b. False ANSWER: True

2. The design phase of the waterfall model is also called the coding phase. a. True b. False ANSWER: False

3. In the maintenance phase of the waterfall model, the parts of a program are brought together into a smoothly functioning whole, usually not an easy task. a. True b. False ANSWER: False

4. Modern software development is usually incremental and iterative. a. True b. False ANSWER: True

5. Programs rarely work as hoped the first time they are run. a. True b. False ANSWER: True

6. The cost of developing software is spread equally over the phases. a. True b. False ANSWER: False

7. Python is a loosely typed programming language. a. True b. False ANSWER: False

8. Testing is a deliberate process that requires some planning and discipline on the programmer's part. a. True b. False ANSWER: True Copyright Cengage Learning. Powered by Cognero.

Page 1


Name:

Class:

Date:

Chapter 02: Software Development, Data Types, and Expressions 9. Text processing is by far the least common application of computing. a. True b. False ANSWER: False

10. When the Python interpreter evaluates a literal, the value it returns is simply that literal. a. True b. False ANSWER: True

11. string is an example of a data type in Python. a. True b. False ANSWER: False

12. In Python, \b is a escape sequence that represents a horizontal tab. a. True b. False ANSWER: False

13. The + operator allows you to build a string by repeating another string a given number of times. a. True b. False ANSWER: False

14. A variable associates a name with a value, making it easy to remember and use the value later in a program. a. True b. False ANSWER: True

15. In general, a variable name must begin with either a letter or an underscore (_). a. True b. False ANSWER: True

16. Variables receive their initial values and can be reset to new values with an assignment statement. a. True b. False ANSWER: True

17. 1,500 is a valid integer literal in Python. a. True Copyright Cengage Learning. Powered by Cognero.

Page 2


Name:

Class:

Date:

Chapter 02: Software Development, Data Types, and Expressions b. False ANSWER: False

18. Real numbers have infinite precision, which means that the digits in the fractional part can continue forever. a. True b. False ANSWER: True

19. In Python, a floating-point number must be written using scientific notation. a. True b. False ANSWER: False

20. Expressions provide an easy way to perform operations on data values to produce other data values. a. True b. False ANSWER: True

21. In Python, % is the exponentiation operator. a. True b. False ANSWER: False

22. The modulus operator has the highest precedence and is evaluated first. a. True b. False ANSWER: False

23. You can use parentheses to change the order of evaluation in an arithmetic expression. a. True b. False ANSWER: True

24. Exponentiation and assignment operations are left associative. a. True b. False ANSWER: False

25. A semantic error is detected when the action that an expression describes cannot be carried out, even though that expression is syntactically correct. a. True b. False ANSWER: True Copyright Cengage Learning. Powered by Cognero.

Page 3


Name:

Class:

Date:

Chapter 02: Software Development, Data Types, and Expressions Multiple Choice 26. In the waterfall development model, what is the most expensive part of software development? a. The design phase. b. The integration phase. c. The maintenance phase. d. The analysis phase. ANSWER: c

27. When attempting to produce a correct program, what is the point of developing a test suite? a. To provide a small set of inputs as a test to verify that a program will be correct for all inputs. b. To modify the running program's variables and verify that the program will still function, even if the code changes. c. To test the outputs of a program against known values to verify that the math coprocessor is performing properly. d. To test the code syntax for possible errors such as undefined variables. ANSWER: a

28. Which of the following literals would be considered a float type in Python? a. -1 b. 3.14 c. '88' d. 5 ANSWER: b

29. What print statement will output a single '\' character? a. print('\') b. print('\\') c. print('"\"') d. print('\\\') ANSWER: b

30. What special character does the '\b' escape sequence generate? a. It generates a border special character. b. It generates a bold special character, causing all text after the character to be bolded. c. It denotes a block of text follows the escape sequence. d. It produces a backspace special character, which performs the same function as the backspace key. ANSWER: d

31. Which of the following is NOT a valid name that can be used for a variable? a. total Copyright Cengage Learning. Powered by Cognero.

Page 4


Name:

Class:

Date:

Chapter 02: Software Development, Data Types, and Expressions b. 1ending c. propertyValue d. TEST ANSWER: b

32. What is the largest value of an int data type in the Python programming language? a. 2,147,483,647 b. 4,294,967,294 c. 2,147,483,647^100 d. The value is limited only by the memory of the host computer. ANSWER: d

33. In Python, what data type is used to represent real numbers between -10^308 and 10^308 with 16 digits of precision? a. int b. float c. string d. array ANSWER: b

34. Which of the following functions and expressions will convert the ASCII character "Z" to its numeric equivalent ASCII code? a. ord('Z') b. chr('Z') c. ord(chr('Z')) d. chr(ord('Z')) ANSWER: a

35. What effect does the following print statement have? print("Hello" * 5) a. The string "Hello" is converted into an int type of value 1 and then multiplied by 5, producing "5". b. The string is indexed and the character count is multiplied with the total number of characters in the string, producing "25". c. The print statement produces a type error as you cannot multiply a string type with an integer type. d. The print statement will produce "HelloHelloHelloHelloHello". ANSWER: d

36. What statement accurately describes what a semantic error is? a. A semantic error is the result of an expression that is syntactically incorrect. b. A semantic error occurs when an expression is syntactically correct, but the expression cannot be carried out. c. A semantic error happens when an expression attempts to perform operations between incompatible data types. Copyright Cengage Learning. Powered by Cognero.

Page 5


Name:

Class:

Date:

Chapter 02: Software Development, Data Types, and Expressions d. A semantic error is the result of an improperly nested if statement. ANSWER: b

37. What statement accurately reflects the difference between the quotient operator and the division operator? a. The two operators are effectively the same, unless being carried out on strings. b. The quotient operator produces a float, while the division operator produces an integer. c. The quotient operator produces a float, while the division operator produces an integer + remainder. d. The quotient operator produces an integer, while the division operator produces a float. ANSWER: d

38. What must be done in order to concatenate a string and a float object? a. Nothing can be done, as the two data types cannot be converted to a compatible type. b. The string object must be converted to a float object via the float() function. c. The float object must be converted to an integer object via the int() function. d. The float object must be converted to a string object via the str() function. ANSWER: d

39. What function can you call inside of IDLE to show the resources of the math module, once it has been imported? a. show(math) b. list(math) c. dir(math) d. resource(math) ANSWER: c

40. In evaluating the precedence rules used by Python, what statement is accurate? a. Exponentiation has the highest precedence. b. Multiplication is evaluated before unary multiplication. c. Addition and subtraction are evaluated after assignment. d. Exponentiation and assignment operations are left associative. ANSWER: a

41. In Python, what does the "%" operator do in the expression 6 % 4? a. It performs an exponentiation to the 4th power. b. It returns a remainder or modulus. c. It returns a float as a result of division. d. It returns the percentage of the operation. ANSWER: b

42. How does the int function convert a float to an int? a. By rounding to the nearest whole number. b. By removing the fractional value of the number. Copyright Cengage Learning. Powered by Cognero.

Page 6


Name:

Class:

Date:

Chapter 02: Software Development, Data Types, and Expressions c. By rounding up to the closest whole number. d. By rounding down to the closest whole number. ANSWER: b

43. You are working on a Python script that relies heavily on the cos and sin functions of the math module. As these are the only functions you require, what should you do to import only these functions, rather than the whole math module? a. import cos, sin b. import cos, sin from math c. import math.cos, math.sin d. from math import cos, sin ANSWER: d

44. Functions that are always available in Python come from what module? a. main b. internal c. __builtin__ d. __system__ ANSWER: c

45. What term describes the process of substituting a simple process for a complex process in a program to make the program easier to understand and maintain? a. refactoring b. abstraction c. inferring d. subletting ANSWER: b

46. What is the total number of distinct values in the ASCII set? a. 64 b. 128 c. 256 d. 512 ANSWER: c

47. What will be the return value of running the following function? chr(ord('T') + 5)? a. 78 b. \t c. 0x89 d. "Y" ANSWER: d Copyright Cengage Learning. Powered by Cognero.

Page 7


Name:

Class:

Date:

Chapter 02: Software Development, Data Types, and Expressions 48. What statement accurately describes the analysis phase of the waterfall model? a. In this phase, the programmers determine what the program will do. b. In this phase, the programmers determine how the program will do its task. c. In this phase, the programmers receive a broad statement of a problem that may be solved by the development of a program. d. In this phase, the programmers bring together the various parts of a program into a smoothly functioning whole. ANSWER: a

49. You are reviewing the code written by another programmer and encounter a variable whose name is entirely in capital letters. What might you discern from this variable name? a. The variable is a symbolic constant. b. The variable is a reference variable. c. The variable is part of a program loop. d. The variable is used to store a dynamic value that is constantly changing. ANSWER: a

Multiple Response 50. What are the two different means by which a floating-point number can be written? (Choose two.) a. decimal notation b. line notation c. scientific notation d. octal notation ANSWER: a, c

Copyright Cengage Learning. Powered by Cognero.

Page 8


Name:

Class:

Date:

Chapter 03: Loops and Selection Statements True / False 1. There are two types of loops—those that repeat an action a predefined number of times (definite iteration) and those that perform the action until the program determines that it needs to stop (indefinite iteration). a. True b. False ANSWER: True

2. The statements in the loop body need not be indented and aligned in the same column. a. True b. False ANSWER: False

3. The assignment symbol can be combined with the arithmetic and concatenation operators to provide augmented assignment operations. a. True b. False ANSWER: True

4. The augmented assignment operations have a higher precedence than the standard assignment operation. a. True b. False ANSWER: False

5. For the most part, off-by-one errors result when the programmer incorrectly specifies the lower bound of the loop. a. True b. False ANSWER: False

6. When the step argument is a negative number, the range function generates a sequence of numbers from the first argument down to the second argument plus 1. a. True b. False ANSWER: True

7. A condition expresses a hypothesis about the state of its world at that point in time. a. True b. False ANSWER: True

8. Loop statements allow a computer to make choices. a. True Copyright Cengage Learning. Powered by Cognero.

Page 1


Name:

Class:

Date:

Chapter 03: Loops and Selection Statements b. False ANSWER: False

9. The Boolean data type is named for the twentieth-century British mathematician George Boole. a. True b. False ANSWER: False

10. Simple Boolean expressions consist of the Boolean values True or False, variables bound to those values, function calls that return Boolean values, or comparisons. a. True b. False ANSWER: True

11. 4 != 4 evaluates to True. a. True b. False ANSWER: False

12. "A" < "B" evaluates to False. a. True b. False ANSWER: False

13. In Python, = means equals, whereas == means assignment. a. True b. False ANSWER: False

14. The comparison operators are applied after addition but before assignment. a. True b. False ANSWER: True

15. The if-else statement is the most common type of selection statement. a. True b. False ANSWER: True

16. The simplest form of selection is the if-else statement. a. True b. False ANSWER: False Copyright Cengage Learning. Powered by Cognero.

Page 2


Name:

Class:

Date:

Chapter 03: Loops and Selection Statements 17. The or operator returns True if and only if both of its operands are true, and returns False otherwise. a. True b. False ANSWER: False

18. The not operator expects a single operand and returns its logical negation, True, if it's false, and False if it's true. a. True b. False ANSWER: True

19. The not operator has a lower precedence than the and and or operators. a. True b. False ANSWER: False

20. Conditional iteration requires that a condition be tested within the loop to determine whether the loop should continue. a. True b. False ANSWER: True

21. The while loop is also called a sentinel-control loop, because its condition is tested at the top of the loop. a. True b. False ANSWER: False

22. The statements within a while loop can execute one or more times. a. True b. False ANSWER: False

23. A while loop can be used for a count-controlled loop. a. True b. False ANSWER: True

24. Although the while loop can be complicated to write correctly, it is possible to simplify its structure and thus improve its readability. a. True b. False ANSWER: True Copyright Cengage Learning. Powered by Cognero.

Page 3


Name:

Class:

Date:

Chapter 03: Loops and Selection Statements 25. Some computer scientists argue that a while True loop with a delayed exit violates the spirit of the while loop. a. True b. False ANSWER: True

Multiple Choice 26. What is the minimum number of spaces that should be used to create an indented statement? a. one space b. two spaces c. three spaces d. four spaces ANSWER: d

27. In evaluating a loop, you find the following statement: "value += 1". What happens to the value variable upon each iteration of the loop? a. The variable is reset to an int type, with a value of 1. b. The variable's value is changed to a positive value. c. The variable is increased by 1 each iteration through the loop. d. The variable is incremented by itself. ANSWER: c

28. An off-by-one error is an example of what type of error in programming? a. logic error b. syntax error c. type error d. input error ANSWER: a

29. When using the range function, what effect does the specification of a third argument have? a. The third argument is used as the starting point for the range function. b. The third argument specifies a step value to be used in the range. c. The third argument declares an exponential value the numbers will be raised to. d. The third argument is simply included in the sequence, assuming it wasn't already in the range. ANSWER: b

30. What character is used as the format operator when formatting output? a. ^ b. $ c. % Copyright Cengage Learning. Powered by Cognero.

Page 4


Name:

Class:

Date:

Chapter 03: Loops and Selection Statements d. @ ANSWER: c

31. Given the following statement: "%4d" % var1, which of the following is accurate? a. The variable var1 must be an integer value. b. The variable var1 must be a string value. c. The variable var1 will be in octal format. d. The variable var1 will be formatted regardless of type. ANSWER: a

32. What statement should you use to print the value of total with a precision of 5 digits? a. print("The total is %5." % total) b. print("The total is %0.5d" % total) c. print("The total is %f" % float(total, 5)) d. print("The total is %0.5f" % total) ANSWER: d

33. What comparison operator is used to test whether an expression does NOT equal another expression? a. -= b. != c. /= d. _= ANSWER: b

34. What is a one-way selection statement in the context of Python? a. It is a single if statement without a corresponding else statement used to test a condition and run statements, then proceed to the next statement. b. It is a single if-else statement block that is used to test a condition and run statements, as well as provide a default path for execution. c. It is a switch statement block that is used to direct the flow of data based on a single condition. d. It is an if statement that tests no conditions, but provides a block for execution. ANSWER: a

35. If A is True, what will the statement "not A" return? a. Undefined b. True c. False d. BooleanError ANSWER: c

36. In a conditional iteration loop, such as a while loop, what is a sentinel value? a. A sentinel value is a user-provided input value that proceeds to the next loop. Copyright Cengage Learning. Powered by Cognero.

Page 5


Name:

Class:

Date:

Chapter 03: Loops and Selection Statements b. A sentinel value is a user-provided input value that changes the structure of the loop. c. A sentinel value is a special value provided by the user to terminate the loop. d. A sentinel value is a special value provided by the user to restart the loop. ANSWER: c

37. The while loop is also known as what kind of a loop? a. infinite loop b. operational loop c. user-control loop d. entry-control loop ANSWER: d

38. Inside of a loop, after a termination condition has been met, what statement can be used to cause an exit from the loop and execute the remainder of the script? a. exit b. break c. quit d. halt ANSWER: b

39. You are running a Python script and suspect that the script has entered an infinite loop. What key combination can you use to halt the loop? a. CTRL + Esc b. CTRL + c c. Alt + b d. CTRL + Break ANSWER: b

40. What function call will generate a random number in the range of 1 through 6 using the random module? a. random.randnum(1, 6) b. random.randint(range(1-6)) c. random.randint(1, 6) d. random.random(1, 6) ANSWER: c

41. What is a count controlled loop? a. It is a loop that counts iterations until a sentinel value is received. b. It is a loop that continues based on a certain time interval. c. It is a loop that prints out a count of values for the user. d. It is a loop that counts through a range of numbers to control when the loop ends. ANSWER: d Copyright Cengage Learning. Powered by Cognero.

Page 6


Name:

Class:

Date:

Chapter 03: Loops and Selection Statements 42. What part of the loop comprises the statements to be executed? a. The loop header. b. The loop body. c. The loop end. d. The loop tail. ANSWER: b

43. The use of +=, -=, and *= are all examples of what type of operators? a. protracted assignment operators b. augmented assignment operators c. extended arithmetic operators d. overloaded mathematic operators ANSWER: b

44. In programming, what is a prototype? a. It is a rough draft of a program. b. It is a program in final stages of development. c. It is a program statement that builds a module. d. It is a production-ready program. ANSWER: a

45. In general terms, what does a selection statement do? a. It forces a computer to favor one value over another. b. It allows a computer to make choices based on test conditions. c. It allows a computer to select the values that are most economical. d. It allows a computer to selectively execute based on processing cost. ANSWER: b

46. What scenario would it make logical sense to use a multi-way selection statement for? a. You need to convert numeric grades to letter grades. b. You need to test if the value of A is larger than B. c. You need to determine if a number is positive or negative. d. You need to test if a variable is True or False. ANSWER: a

47. What is NOT a Boolean or logical operator used in the Python language? a. and b. or c. not d. xor ANSWER: d Copyright Cengage Learning. Powered by Cognero.

Page 7


Name:

Class:

Date:

Chapter 03: Loops and Selection Statements 48. What statement regarding precedence of operators is accurate? a. The assignment operator (=) is higher in precedence than exponentiation (**). b. The logical conjunction (and) is higher in precedence than the logical negation (not). c. The comparison operators (==, !=, <, >, <=, >=) are higher in precedence than the assignment operator (=). d. The addition and subtraction operators (+, -) are lower in precedence than the logical conjunction operator (and). ANSWER: c

49. Assuming that the value of x is 4, and the value of y is 6, what is the value of the following expression? (x y)**2 > y a. True b. False c. Undefined d. TypeError ANSWER: b

Multiple Response 50. What are the two different types of loops that are used within the Python language? (Choose two.) a. predetermined looping b. definite iteration c. infinite cycling d. indefinite iteration ANSWER: b, d

Copyright Cengage Learning. Powered by Cognero.

Page 8


Name:

Class:

Date:

Chapter 03: Searching, Sorting, and Complexity Analysis True / False 1. All algorithms that perform the same task take the same amount of time to complete. a. True b. False ANSWER: False

2. Benchmarking is the process of using the computer's clock to obtain run time information for an algorithm. a. True b. False ANSWER: True

3. The time() function returns the amount of time a program has been running in seconds. a. True b. False ANSWER: False

4. An algorithm that uses the exact same Python code run on two different machines should have the same performance data. a. True b. False ANSWER: False

5. The number of Python instructions executed in an algorithm will differ from the number of machine language instructions executed. a. True b. False ANSWER: True

6. The performance of an algorithm in a single loop is linear. a. True b. False ANSWER: True

7. Algorithms with linear behavior do more work than those with quadratic behavior. a. True b. False ANSWER: False

8. The amount of work of a logarithmic algorithm is proportional to the log2 of the problem size. a. True b. False ANSWER: True Copyright Cengage Learning. Powered by Cognero.

Page 1


Name:

Class:

Date:

Chapter 03: Searching, Sorting, and Complexity Analysis 9. The order of complexity of a linear-time algorithm is On. a. True b. False ANSWER: False

10. Python's in operator is implemented as a method named __contains__ in the list class. a. True b. False ANSWER: True

11. The in operator performs a binary search algorithm. a. True b. False ANSWER: False

12. The sequential search algorithm does more work to find a target at the beginning of a list than at the end of the list. a. True b. False ANSWER: False

13. On sorted data, you can use a binary search. a. True b. False ANSWER: True

14. Using a binary search, a list of 1 million items requires only 20 comparisons. a. True b. False ANSWER: True

15. In a bubble sort, each pass through the main loop selects a single item to be moved. a. True b. False ANSWER: False

16. In a selection sort, the outer loop executes n - 1 times. a. True b. False ANSWER: True

17. In a selection sort, the inner loop is executed n - 2 times for every pass through the outer loop. Copyright Cengage Learning. Powered by Cognero.

Page 2


Name:

Class:

Date:

Chapter 03: Searching, Sorting, and Complexity Analysis a. True b. False ANSWER: False

18. This bubble sort has the effect of bubbling the largest items to the end of the list. a. True b. False ANSWER: True

19. The bubble sort has a complexity of O(n2). a. True b. False ANSWER: True

20. In the average case, where many items in a list are out of order, an insertion sort is linear. a. True b. False ANSWER: False

21. A bubble sort always requires approximately n2 comparisons. a. True b. False ANSWER: False

22. In the first step of the quicksort, you begin by selecting the item at the list's midpoint. a. True b. False ANSWER: True

23. The merge sort employs a recursive, divide-and-conquer strategy to break the O(n2) barrier. a. True b. False ANSWER: True

24. The first two numbers in the Fibonacci sequence are 1s, and each number after that is the sum of the previous two numbers. a. True b. False ANSWER: True

25. The result of fib(4) is 8. a. True Copyright Cengage Learning. Powered by Cognero.

Page 3


Name:

Class:

Date:

Chapter 03: Searching, Sorting, and Complexity Analysis b. False ANSWER: False

Multiple Choice 26. Why is the efficiency of algorithms desirable? a. an inefficient algorithm may use too much time or space b. efficient algorithms always cost less money c. inefficient algorithms always use too much memory d. efficient algorithms always use less memory ANSWER: a

27. Which of the following is a common way to measure the time cost of an algorithm? a. count lines of code b. use a stopwatch c. calculate memory usage d. use the computer's clock ANSWER: d

28. What should the missing code be in the following algorithm if the goal is to determine how many seconds the algorithm runs? start = time.time() myCount = 1 for x in range(100): myCount *= x elapsed = time.time() - <missing code> a. myCount b. elapsed c. start d. x ANSWER: c

29. What does the Python time() function return? a. The seconds elapsed since January 1, 1970 b. The number of instructions executed c. The number of seconds the code has been running d. The number of milliseconds to execute a line of code ANSWER: a

30. Which of the following is a method to estimate the efficiency of an algorithm that predicts the amount of work an algorithm performs regardless of the platform? Copyright Cengage Learning. Powered by Cognero.

Page 4


Name:

Class:

Date:

Chapter 03: Searching, Sorting, and Complexity Analysis a. using a millisecond counter b. counting instructions c. determining memory usage d. convert the algorithm to byte code ANSWER: b

31. Which method of determining the efficiency of algorithms allows you to rate them independently of timings or instruction counts? a. elapsed time profiling b. byte-code assembly c. complexity analysis d. memory usage analysis ANSWER: c

32. How can the performance complexity of the following algorithm be described? for x in range(numIterations): value = value * x print(value) a. exponential b. logarithmic c. quadratic d. linear ANSWER: d

33. How can an algorithm be described in which the work it does grows as a function of the square of the problem size? a. exponential b. logarithmic c. quadratic d. linear ANSWER: c

34. What type of algorithm is list indexing an example of? a. constant-time b. logarithmic-time c. exponential-time d. linear-time ANSWER: a

35. In the following code, what is the algorithm's complexity? Copyright Cengage Learning. Powered by Cognero.

Page 5


Name:

Class:

Date:

Chapter 03: Searching, Sorting, and Complexity Analysis minIndex = 0 currentIndex = 1 while currentIndex < len(lyst): if lyst[currentIndex] < lyst[minIndex]: minIndex = currentIndex currentIndex += 1 return minIndex a. O(n2) b. O(n) c. O(log2n) d. O2 ANSWER: b

36. In a binary search of an ascending order list, where does the search algorithm begin the search? a. the beginning of the list b. a random spot in the list c. the end of the list d. the middle of the list ANSWER: d

37. How can the following algorithm be described? position = 0 while position < len(lyst): if target == lyst[position]: return position position += 1 return -1 a. binary search b. bubble sort c. sequential search d. selection sort ANSWER: c

38. How can the following algorithm be described? left = 0 right = len(sortedLyst) - 1 while left <= right: midpoint = (left + right) // 2 if target == sortedLyst[midpoint]: Copyright Cengage Learning. Powered by Cognero.

Page 6


Name:

Class:

Date:

Chapter 03: Searching, Sorting, and Complexity Analysis return midpoint elif target < sortedLyst[midpoint]: right = midpoint - 1 else: left = midpoint + 1 return -1 a. binary search b. bubble sort c. sequential search d. selection sort ANSWER: a

39. What is the worst-case complexity of a binary search? a. O(n2) b. O(n) c. O(log2n) d. O2 ANSWER: c

40. What term best describes the following code? x = myList[i] myList[i] = myList[j] myList[j] = x a. sequential search b. binary sort c. selection algorithm d. swap function ANSWER: d

41. What type of algorithm is the following code? i = 0 while i < len(myList) - 1: minIndex = i j = i + 1 while j < len(myList): if myList[j] < myList[minIndex]: minIndex = j j += 1 if minIndex != i: swap(myList, minIndex, i) Copyright Cengage Learning. Powered by Cognero.

Page 7


Name:

Class:

Date:

Chapter 03: Searching, Sorting, and Complexity Analysis i += 1 a. binary search b. bubble sort c. sequential search d. selection sort ANSWER: d

42. What is the complexity of a selection sort? a. O(n2) b. O(n) c. O(log2n) d. O2 ANSWER: a

43. What type of algorithm is the following code? n = len(myList) while n > 1: i = 1 while i < n: if myList[i] < myList[i - 1]: swap(myList, i, i - 1) i += 1 n -= 1 a. linear sort b. bubble sort c. insertion sort d. selection sort ANSWER: b

44. Which type of algorithm is analogous to how many people organize playing cards in their hands? a. linear sort b. bubble sort c. insertion sort d. selection sort ANSWER: c

45. How many loops are found in a typical insertion sort? a. 1 b. 2 Copyright Cengage Learning. Powered by Cognero.

Page 8


Name:

Class:

Date:

Chapter 03: Searching, Sorting, and Complexity Analysis c. 3 d. 4 ANSWER: b

46. In terms of complexity, what is the worst-case scenario for an insertion sort? a. O(n2) b. O(n) c. O(log2n) d. O2 ANSWER: a

47. In terms of complexity, what is the average case for an insertion sort? a. linear b. quadratic c. exponential d. logarithmic ANSWER: b

48. What should the missing code be in the following insertion sort algorithm? i = 1 while i < len(myList): itemToInsert = myList[i] j = i - 1 while j >= 0: if itemToInsert < myList[j]: myList[j + 1] = myList[j] j -= 1 else: break <missing code> i += 1 a. myList[i + 1] = itemToInsert b. myList[j] = itemToInsert c. myList[j + 1] = itemToInsert d. myList[i] = itemToInsert ANSWER: c

49. An analysis of an algorithm's complexity divides its behavior into what three types of cases? a. best case, worst case, average case b. minimum case, maximum case, average case Copyright Cengage Learning. Powered by Cognero.

Page 9


Name:

Class:

Date:

Chapter 03: Searching, Sorting, and Complexity Analysis c. linear case, quadratic case, logarithmic case d. sequential case, exponential case, binary case ANSWER: a

50. What is the best case performance of a sequential search? a. On b. linear c. quadratic d. O(1) ANSWER: d

Copyright Cengage Learning. Powered by Cognero.

Page 10


Name:

Class:

Date:

Chapter 04: Arrays and Linked Structures True / False 1. The list is the primary implementing structure in Python collections. a. True b. False ANSWER: False

2. When an array object is traversed in a for loop, the object's __iter__ method is called. a. True b. False ANSWER: True

3. When an array is instantiated, it is filled with zeros by default. a. True b. False ANSWER: False

4. If an array's logical size is greater than zero, the index of the last item in the array is the logical size plus 1. a. True b. False ANSWER: False

5. If the logical size of an array equals the physical size of the array, a new array must be created to add elements to the array. a. True b. False ANSWER: True

6. Time performance is improved if you double the size of the array when you need to increase its size. a. True b. False ANSWER: True

7. When a list's append method results in memory wasted beyond a threshold, the size of the underlying array is decreased. a. True b. False ANSWER: False

8. When an item is inserted into an array, the logical size of the array increases. a. True b. False ANSWER: True Copyright Cengage Learning. Powered by Cognero.

Page 1


Name:

Class:

Date:

Chapter 04: Arrays and Linked Structures 9. To access a two-dimensional array, you use two subscripts. a. True b. False ANSWER: True

10. A ragged grid has a fixed number of columns and a variable number of rows. a. True b. False ANSWER: False

11. A linked structure can have items that have a maximum of one link to another item. a. True b. False ANSWER: False

12. The first item in a singly linked structure is accessed using a head link. a. True b. False ANSWER: True

13. It's easier to get to an item's predecessor in a singly linked structure than in a doubly linked structure. a. True b. False ANSWER: False

14. In a doubly linked structure, the first and last item have an empty link. a. True b. False ANSWER: True

15. A linked structure can be stored in noncontiguous memory. a. True b. False ANSWER: True

16. In Python, a node in a doubly linked structure contains two fields: a data item and a reference to the next node. a. True b. False ANSWER: False

17. On a linked structure, index-based operations must be emulated by manipulating links within the structure. Copyright Cengage Learning. Powered by Cognero.

Page 2


Name:

Class:

Date:

Chapter 04: Arrays and Linked Structures a. True b. False ANSWER: True

18. To start a traversal of a linked structure, initialize a variable to the structure's head pointer. a. True b. False ANSWER: True

19. A traversal of a singly linked structure terminates when the temporary variable is equal to the head pointer. a. True b. False ANSWER: False

20. Similar to an array, linked structures support random access. a. True b. False ANSWER: False

21. Inserting data at the beginning of a linked structure uses constant time and memory. a. True b. False ANSWER: True

22. The operation of removing an item at the end of a linked structure is constant in time and memory. a. True b. False ANSWER: False

23. The insertion and removal of the first node of a singly linked structure require that the head pointer be reset. a. True b. False ANSWER: True

24. A circular linked structure contains a link from the last node back to the first node in the structure. a. True b. False ANSWER: True

25. The run-time complexities of the operations on a doubly linked structure are typically double compared to the corresponding operations on the singly linked structure. a. True Copyright Cengage Learning. Powered by Cognero.

Page 3


Name:

Class:

Date:

Chapter 04: Arrays and Linked Structures b. False ANSWER: False

Multiple Choice 26. Which of the following best describes an array? a. a collection of data points that represent an object b. a list of values that are indexes to a database c. a numeric value that points to a position in RAM where data can be found d. a sequence of items that can be accessed at given index positions ANSWER: d

27. What is the primary implementing structure of Python collections? a. list b. array c. linked list d. dictionary ANSWER: b

28. Which of the following is true of the array class included in Python’s array module? a. it is limited to storing numbers b. it behaves much like a dictionary c. it can only hold character values d. you can define its size at run time ANSWER: a

29. In the Array class defined in Chapter 4, how do you instantiate an array object that can hold 10 values? a. myArray(10) = Array b. Array myArray, 10 c. myArray = Array(10) d. Array(10) myArray ANSWER: c

30. Older programming languages implement arrays as static data structures which are inefficient. What do modern languages use to remedy the problems of static arrays? a. dynamic arrays b. linked lists c. data stacks d. hash tables ANSWER: a

31. What method does Python's list type use to increase the size of the underlying array? Copyright Cengage Learning. Powered by Cognero.

Page 4


Name:

Class:

Date:

Chapter 04: Arrays and Linked Structures a. size b. append c. increase d. augment ANSWER: b

32. The process for resizing an array named myArray is shown below. What is the missing code? if logicalSize == len(myArray): temp = Array(len(myArray) + 1) for i in range(logicalSize): <missing code> a = temp a. myArray[temp] = myArray[i] b. temp [i] = myArray[i] c. myArray[i] = temp[i] d. temp = myArray(len(myArray)) ANSWER: b

33. What process is required to avoid wasting memory if successive calls to the pop method on a list are made? a. delete the array b. grow the array c. reset the array d. shrink the array ANSWER: d

34. In the following code to insert an item in an array, what is the missing code? for x in range(logicalSize, targetIndex, -1): myArray[x] = myArray[x - 1] a[targetIndex] = newItem <missing code> a. targetIndex += 1 b. targetIndex -= 1 c. logicalSize += 1 d. logicalSize -= 1 ANSWER: c

35. Which of the following statements accesses the second column in the third row of a two-dimensional array? a. twoDim[2][1] b. twoDim[4][3] Copyright Cengage Learning. Powered by Cognero.

Page 5


Name:

Class:

Date:

Chapter 04: Arrays and Linked Structures c. twoDim[1][2] d. twoDim[2][3] ANSWER: a

36. The following code sums all the values in the two-dimensional array. What is the missing code? sum = 0 for row in range(grid.getHeight()): for column in range(grid.getWidth()): <missing code> a. sum += grid[column][row] b. sum += grid[row-1][column-1] c. sum += grid[column+1][row+1] d. sum += grid[row][column] ANSWER: d

37. How does a programmer access the first item in a singly linked structure? a. by using the 0 index b. with the first() method c. by following a head link d. by a call to getLink(1) ANSWER: c

38. Which of the following is an advantage of a doubly linked structure over a singly linked structure? a. it is less complex to implement b. you can easily access the predecessor of an item c. you can easily access the successor of an item d. it uses less memory ANSWER: b

39. What does the last item in a singly linked structure contain? a. an empty link b. a link to the first item c. a link to the previous item d. a method for appending an item ANSWER: a

40. What type of memory scheme does a linked list use? a. overlapping b. noncontiguous c. sequential Copyright Cengage Learning. Powered by Cognero.

Page 6


Name:

Class:

Date:

Chapter 04: Arrays and Linked Structures d. random ANSWER: b

41. Which statement tests if a singly linked node variable named myItem has been initialized? a. if myItem is Null: b. if myItem != None: c. if myItem = None: d. if myItem is not Null: ANSWER: b

42. What are almost all operations on arrays based upon? a. hashes b. keys c. links d. indexes ANSWER: d

43. What is the operation on a linked structure called that visits each node without deleting it? a. probe b. insertion c. removal d. traversal ANSWER: d

44. What type of linked structure operation is the following code performing? z = 0 probe = head while probe != None: z = probe.data + z probe = probe.next a. traversal b. initialization c. visit with removal d. insertion ANSWER: a

45. The following code searches a linked structure. What is the missing code? probe = head while probe != None and targetItem != probe.data: <missing code> Copyright Cengage Learning. Powered by Cognero.

Page 7


Name:

Class:

Date:

Chapter 04: Arrays and Linked Structures if probe != None: print("Target item found!") else: print("Target item not found!") a. probe.data = next.data b. probe.next = targetItem.data c. probe = probe.next d. probe.head = probe.next ANSWER: c

46. On average, what is the performance of a sequential search on a singly linked structure? a. logarithmic b. linear c. exponential d. random ANSWER: b

47. What type of operation is the following code performing? probe = head while probe != None and targetItem != probe.data: probe = probe.next if probe != None: probe.data = newItem return True else: return False a. sum of all items b. replacement c. insertion d. deletion ANSWER: b

48. What action does the following code perform assuming the Node class defined in Chapter 4? head = Node(newItem, head) a. deletion of an item in a linked list b. appending an item to the end of a linked list c. replacing an item at the beginning of a linked list d. insertion of an item at the beginning of a linked list ANSWER: d Copyright Cengage Learning. Powered by Cognero.

Page 8


Name:

Class:

Date:

Chapter 04: Arrays and Linked Structures 49. When inserting or removing the ith node of a singly linked structure, why is doing so for the first node a special case? a. the tail pointer must be reset b. the first item must be deleted c. the head pointer must be reset d. the last item must be deleted ANSWER: c

50. How does the class definition of a doubly linked structure differ from a singly linked structure? a. by adding a previous pointer b. by adding another head pointer c. by adding an extra data field d. by removing the tail pointer ANSWER: a

Copyright Cengage Learning. Powered by Cognero.

Page 9


Name:

Class:

Date:

Chapter 04: Strings and Text Files True / False 1. A data structure is a compound unit that consists of several smaller pieces of data. a. True b. False ANSWER: True

2. The string is a mutable data structure. a. True b. False ANSWER: False

3. Some applications extract portions of strings called characters. a. True b. False ANSWER: True

4. When used with strings, the left operand of Python's in operator is a target substring and the right operand is the string to be searched. a. True b. False ANSWER: True

5. Many applications now use data mangling to protect information transmitted on networks. a. True b. False ANSWER: False

6. A Caesar cipher uses a plaintext character to compute two or more encrypted characters, and each encrypted character is computed using two or more plaintext characters. a. True b. False ANSWER: False

7. The decimal number system is also called the base ten number system. a. True b. False ANSWER: True

8. The two digits in the base two number system are 0 and 1. a. True b. False ANSWER: True Copyright Cengage Learning. Powered by Cognero.

Page 1


Name:

Class:

Date:

Chapter 04: Strings and Text Files 9. The absolute value of a digit is determined by raising the base of the system to the power specified by the position (baseposition). a. True b. False ANSWER: False

10. A binary number is sometimes referred to as a string of bits or a bit string. a. True b. False ANSWER: True

11. A module behaves like a function, but has a slightly different syntax. a. True b. False ANSWER: False

12. A method is always called with a given data value called an object, which is placed before the method name in the call. a. True b. False ANSWER: True

13. A difference between functions and methods is that methods cannot return values. a. True b. False ANSWER: False

14. In Python, all data values are objects. a. True b. False ANSWER: True

15. The string method isalpha returns True if the string contains only letters or False otherwise. a. True b. False ANSWER: True

16. The string method isnumeric returns True if the string contains only digits or False otherwise. a. True b. False ANSWER: False Copyright Cengage Learning. Powered by Cognero.

Page 2


Name:

Class:

Date:

Chapter 04: Strings and Text Files 17. Using a text editor such as Notepad or TextEdit, you can create, view, and save data in a text file. a. True b. False ANSWER: True

18. All data output to or input from a text file must be strings. a. True b. False ANSWER: True

19. Data can be output to a text file using a(n) output object. a. True b. False ANSWER: False

20. When using the open function to open a file for output (i.e., using 'w' as the mode string), if the file does not exist, Python raises an error. a. True b. False ANSWER: False

21. The file method write expects a single string as an argument. a. True b. False ANSWER: True

22. When using the open function to open a file for input (i.e., using 'r' as the mode string), if the file does not exist, Python raises an error. a. True b. False ANSWER: True

23. After input is finished, another call to read returns an empty string to indicate that the end of the file has been reached. a. True b. False ANSWER: True

24. The remove file system function is included in the os.path module. a. True b. False ANSWER: False Copyright Cengage Learning. Powered by Cognero.

Page 3


Name:

Class:

Date:

Chapter 04: Strings and Text Files 25. The exists file system function is included in the os.path module. a. True b. False ANSWER: True

Multiple Choice 26. What statement regarding the structure of strings is accurate? a. A string is a sequence of zero or more characters. b. A string's length as calculated by the len() function is always "1". c. A string cannot be decomposed into more primitive parts. d. A string is a mutable data structure. ANSWER: a

27. What happens if you attempt to access a string using an index equal to the string's length? a. The entirety of the string will be accessed. b. The name of the string will be accessed. c. The string's location in memory will be returned. d. An error will occur, indicating the index is out of range. ANSWER: d

28. Your script is parsing filenames and is creating a count of how many files per file extension type exist within a directory. What slice could you use to extract the file extension substring, assuming the extensions are three letters only? a. filename[-3:] b. filename[-3] c. filename[:-3] d. filename[$-3] ANSWER: a

29. When a sender of information encrypts that information, what is the resulting text known as? a. plain text b. garbage text c. cipher text d. junk text ANSWER: c

30. The encryption method that replaces a character in a text with another character some given distance away in the alphabet from the original is known as what type of cipher? a. Alpha cipher b. Caesar cipher c. Jumble cipher Copyright Cengage Learning. Powered by Cognero.

Page 4


Name:

Class:

Date:

Chapter 04: Strings and Text Files d. Alternate cipher ANSWER: b

31. What does a block cipher utilize in order to change plaintext characters into two or more encrypted characters? a. A mathematical structure known as an invertible matrix. b. A random noise sampling from the computer's hardware. c. A pseudorandom number generator defined by the encrypting language. d. A hardware encryption chip designed to perform obfuscation. ANSWER: a

32. The decimal number system, which utilizes the numbers 0-9, is also known as what number system? a. The base-9 numbering system. b. The base-10 numbering system. c. The Octal numbering system. d. The hexadecimal numbering system. ANSWER: b

33. What is the value of the binary number 10010110 in base-10? a. 144 b. 150 c. 169 d. 232 ANSWER: b

34. What is the decimal number 98 in binary? a. 110010 b. 1100011 c. 1100010 d. 1110010 ANSWER: c

35. A legacy program is outputting values in octal format, and you need to translate the octal to hexadecimal. What is 173 in octal expressed as a hexadecimal value? a. FA b. 7B c. 5D d. 9C ANSWER: b

36. You are parsing a comma separated value string with Python. What method can you use to separate the values in each line and place them in a list? Copyright Cengage Learning. Powered by Cognero.

Page 5


Name:

Class:

Date:

Chapter 04: Strings and Text Files a. string.split(',') b. string.delimit(',') c. string.parsetolist(',') d. string.strip(',') ANSWER: a

37. What string method can you use to locate the lowest index in a string named s where substring "findme" is found? a. s.locate("findme") b. s.find("findme") c. s.grep('findme') d. s.search("findme") ANSWER: b

38. What does a mode string of 'r' indicate when opening a file in Python? a. The file will be opened for random access. b. The file will be opened for read access. c. The file will be opened for write access. d. The file will be opened in binary mode. ANSWER: b

39. You are running a Python script that is supposed to write data to an open file, but discover that the file contents are not updating even after the script finishes. What is most likely the issue? a. The file was opened using 'w' instead of 'b' as the mode string. b. The file is not being updated because it doesn't exist. c. The file is not being written to using the dump() method. d. The file was not closed using the close() method. ANSWER: d

40. What file access method can be used to read a single line of input and return the line as a string, including the newline character? a. getline b. readline c. fetch d. read ANSWER: b

41. You are attempting to open a file containing a list of integer numbers, each on a separate line, and read them into Python as int types. What statement could you use to do this, assuming each line is represented by the line variable in a continuous loop? a. num = int(line.strip()) b. num = line.strip() Copyright Cengage Learning. Powered by Cognero.

Page 6


Name:

Class:

Date:

Chapter 04: Strings and Text Files c. num = line.strip(int(line)) d. num = line[:-1] ANSWER: a

42. You are running a Python script that is supposed to write data to an open file, but discover that the file contents are being erased each time the script runs. What is most likely the issue? a. The file was opened using a mode string other than 'a'. b. The file is truncated by default with the write() method. c. The file is erased when the script uses the close() method. d. The file must be opened using a mode string of 'rw'. ANSWER: a

43. When you launch Python, what file system path does it start with? a. The root directory of the file system. b. The current working directory. c. The same folder as the Python executable file. d. The user's home folder. ANSWER: b

44. What os module function should you use to get the path of the current working directory? a. getcwd() b. cwd() c. getpwd() d. showcwd() ANSWER: a

45. What os.path module function can you use to convert a path to a pathname appropriate for the current file system? a. localize(path) b. system(path) c. convert(path) d. normcase(path) ANSWER: d

46. In the binary number system, each digit or bit has a positional value that is a power of what? a. 1 b. 2 c. 8 d. 16 ANSWER: b

47. What specific Python module can you use to determine the file size in bytes of a given file? Copyright Cengage Learning. Powered by Cognero.

Page 7


Name:

Class:

Date:

Chapter 04: Strings and Text Files a. os.stat b. io.file c. os.path d. file.ops ANSWER: c

48. What does the os module function remove do when called? a. It removes a given file or directory that is passed to it. b. It removes a given directory that is passed to it. c. It removes a given file that is passed to it. d. It removes a given symbolic link file and its associated node. ANSWER: c

Multiple Response 49. Which of the following are examples of protocols that utilize encryption for data transfer? (Choose two.) a. HTTP b. HTTPS c. FTPS d. RCP ANSWER: b, c

50. What two methods can be used to return a copy of a string named s converted to all lowercase and all uppercase respectively? a. s.lower() b. s.lowcase() c. s.upper() d. s.upcase() ANSWER: a, c

Copyright Cengage Learning. Powered by Cognero.

Page 8


Name:

Class:

Date:

Chapter 05: Interfaces, Implementations, and Polymorphism True / False 1. Each time you run Python's document function to obtain information about a module, data type, method, or function, you are accessing documentation about that resource's interface. a. True b. False ANSWER: False

2. An interface's documentation gives you enough information to know how to use or call a method and what to expect it to accomplish and return. a. True b. False ANSWER: True

3. A bag is a type of ordered collection. a. True b. False ANSWER: False

4. Software bags can grow as more items are added, or they can shrink as items are removed. a. True b. False ANSWER: True

5. The clear method empties a bag. a. True b. False ANSWER: True

6. When used with a bag object, the in operator returns an integer value. a. True b. False ANSWER: False

7. When defining the Bag class, the __init__ operation is the constructor for the class. a. True b. False ANSWER: True

8. A docstring is a string enclosed in double quotes that will be displayed when Python's help function is run on a resource. a. True b. False Copyright Cengage Learning. Powered by Cognero.

Page 1


Name:

Class:

Date:

Chapter 05: Interfaces, Implementations, and Polymorphism ANSWER: False

9. A precondition is a statement of what must be true for a method to perform its actions correctly. a. True b. False ANSWER: True

10. Once the designer of a collection class has obtained its interface, the implementation of the class includes completing code for the methods. a. True b. False ANSWER: True

11. Data that is needed to represent the state of a collection are assigned to instance variables in the __help__ method of the class. a. True b. False ANSWER: False

12. The logical size of an array-based bag will always be the same as the array's capacity. a. True b. False ANSWER: False

13. You can use a for loop on any collection. a. True b. False ANSWER: True

14. The statement in the ArrayBag constructor to copy an item from a source collection to a new ArrayBag object is self.init(item). a. True b. False ANSWER: False

15. Whenever you need to use the logical size of the bag within a class definition, run len(self) instead of referring directly to the instance variable self.size. a. True b. False ANSWER: True

16. When Python sees a for loop on an iterable object, it runs that object's __add__ method. a. True Copyright Cengage Learning. Powered by Cognero.

Page 2


Name:

Class:

Date:

Chapter 05: Interfaces, Implementations, and Polymorphism b. False ANSWER: False

17. The __iter__ method uses a yield statement to send each item to the calling for loop. a. True b. False ANSWER: True

18. When Python sees the in operator used with a collection, it runs the __contains__ method in the collection's class. a. True b. False ANSWER: True

19. You should always try to hide the implementing data structures behind a wall of method calls on the object being implemented. a. True b. False ANSWER: True

20. When the LinkedBag structure is not empty, self.items refers to the last node in the linked structure. a. True b. False ANSWER: False

21. The __iter__ method is identical in the ArrayBag and LinkedBag classes. a. True b. False ANSWER: False

22. In the remove method for LinkedBag, if probe points to the node at the head of the linked structure, trailer will point to the tail. a. True b. False ANSWER: False

23. The running times of the operations of ArrayBag and LinkedBag are similar. a. True b. False ANSWER: True

24. While desirable, testing is not a critical part of software resource development. a. True Copyright Cengage Learning. Powered by Cognero.

Page 3


Name:

Class:

Date:

Chapter 05: Interfaces, Implementations, and Polymorphism b. False ANSWER: False

25. Class diagrams show the relationships among classes at various levels of detail. a. True b. False ANSWER: True

Multiple Choice 26. Which of the following is one of the hallmarks of well-designed software? a. a random grouping of interfaces to ensure secure code b. an interface that is tightly coupled to the implementation c. the clean separation of interfaces from implementations d. a sophisticated interface with a high learning curve ANSWER: c

27. Which of the following is NOT a goal of the barrier that separates an interface from implementation? a. allows users to quickly glue resources together b. allows alternative implementations of the same resource c. changes to a resource's implementations do not disturb user code d. increases the learning curve for resource's users ANSWER: d

28. Which Python function allows you to obtain information about a module, data type, method, or function? a. help b. list c. doc d. info ANSWER: a

29. Which is true about a bag collection? a. it is an unordered collection b. it is a standard collection type in Python c. bags can contain only numeric objects d. bags are of a fixed size ANSWER: a

30. What is it called when the contents of two bags are combined into a third bag? a. iteration b. appending c. concatenation Copyright Cengage Learning. Powered by Cognero.

Page 4


Name:

Class:

Date:

Chapter 05: Interfaces, Implementations, and Polymorphism d. reduction ANSWER: c

31. What word is best defined as the use of common names for operations on different types of collections? a. anachronism b. polymorphism c. concatenation d. modularization ANSWER: b

32. What is the name of the method that performs the constructor operation for a class? a. __eq__ b. __iter__ c. __add__ d. __init__ ANSWER: d

33. In the Bag class defined in the chapter, what is one of the purposes of the sourceCollection argument in the __init__ method? a. to create a bag with the contents of another collection b. to delete the contents of an existing collection c. to define source code for the method d. to add data to an existing bag collection ANSWER: a

34. What is found in the body of the method code that is used to document the method? a. mutators b. parameters c. docstring d. arguments ANSWER: c

35. The design and implementation of a collection class consists of two steps. What is the first step? a. document the class using docstrings b. choose an appropriate data structure c. write the code for the defined methods d. test the method using sample data ANSWER: b

36. In the ArrayBag class, why must the ArrayBag object track its logical size in a separate instance variable? a. because the physical size is always smaller than the logical size b. because the initial size of the object can't be changed Copyright Cengage Learning. Powered by Cognero.

Page 5


Name:

Class:

Date:

Chapter 05: Interfaces, Implementations, and Polymorphism c. because the logical size will likely differ from the array's capacity d. because the array size and the logical size are identical ANSWER: c

37. In the ArrayBag class, what must the __init__ method do if a source collection is specified? a. the new instantiation of the bag must be copied to the source collection. b. the source collection must be initialized with the clear method c. the data in the source collection must be deleted d. the data in the source collection must be copied ANSWER: d

38. The code for the add method for the ArrayBag class is shown below. What is the missing code? def add(self, item): self.items[len(self)] = item <missing code> a. self.items +=1 b. self = self + 1 c. self.size += 1 d. self.len = self.items ANSWER: c

39. What does Python do when it sees a for loop on an iterable object? a. executes a do loop b. runs the __iter__ method c. runs the clear method d. executes a return statement ANSWER: b

40. The code for the __iter__ method is shown below. What is the missing code? def __iter__(self): <missing code> while cursor < len(self): yield self.items[cursor] cursor += 1 a. cursor = 0 b. cursor = 1 c. cursor = self.size d. cursor = len(self) ANSWER: a Copyright Cengage Learning. Powered by Cognero.

Page 6


Name:

Class:

Date:

Chapter 05: Interfaces, Implementations, and Polymorphism 41. In the ArrayBag class, what function does the __str__ method use to generate a sequence of strings from a bag? a. count b. len c. add d. map ANSWER: d

42. What method does Python run when it sees the in operator used with a collection? a. __contains__ b. __iter__ c. __eq__ d. __add__ ANSWER: a

43. What is the last step in the remove function in the ArrayBag class? a. check the precondition b. shift items to the right c. resize the array d. search for the target item index ANSWER: c

44. Which of the following methods will require changes between the ArrayBag and the LinkedBag class? a. isEmpty b. remove c. __eq__ d. __len__ ANSWER: b

45. Why won't some of the ArrayBag methods require changes when implementing the LinkedBag class? a. because the methods don't use the self variable b. because the ArrayBag class is based on lists c. because the LinkedBag object is not iterable d. because the methods don't directly access the array variable ANSWER: d

46. What is one of the pieces of data that must be initialized in the __init__ method in the LinkedBag class? a. an array b. a linked structure c. a physical size d. a string pointer Copyright Cengage Learning. Powered by Cognero.

Page 7


Name:

Class:

Date:

Chapter 05: Interfaces, Implementations, and Polymorphism ANSWER: b

47. The following code copies the data from a specified source collection in the LinkedBag __init__ method. What is the missing code? for item in sourceCollection: <missing code>

a. add(item.self) b. self.add(item) c. self.item(add) d. self.item = source.item ANSWER: b

48. How can the performance of the in and remove functions be described in the two bag implementations? a. they take linear time b. they take constant time c. the performance is exponential according to the size of the bag d. the performance is logarithmic according to the size of the bag ANSWER: a

49. What testing tool can be used to help ensure that a resource meets its requirements? a. unittest b. pytest c. pyunit d. unitcheck ANSWER: c

50. Which of the following is a visual aid to help catalog resources in your software toolbox? a. docstring b. method mapper c. unit modeler d. class diagram ANSWER: d

Copyright Cengage Learning. Powered by Cognero.

Page 8


Name:

Class:

Date:

Chapter 05: Lists and Dictionaries True / False 1. A list is a sequence of data values called indexes. a. True b. False ANSWER: False

2. Each item in a list has a unique index that specifies its position. a. True b. False ANSWER: True

3. The index of the first item in a list is 1. a. True b. False ANSWER: False

4. The index of the last item in a list is the length of the list. a. True b. False ANSWER: False

5. Lists of integers can be built using the range function. a. True b. False ANSWER: True

6. The print function strips the quotation marks from a string, but it does not alter the look of a list. a. True b. False ANSWER: True

7. A list is immutable. a. True b. False ANSWER: False

8. When replacing an element in a list, the subscript is used to reference the target of the assignment statement, which is not the list but an element's position within it. a. True b. False ANSWER: True Copyright Cengage Learning. Powered by Cognero.

Page 1


Name:

Class:

Date:

Chapter 05: Lists and Dictionaries 9. Although a list's elements are always ordered by position, it is possible to impose a natural ordering on them as well. a. True b. False ANSWER: True

10. The list method ascending mutates a list by arranging its elements in ascending order. a. True b. False ANSWER: False

11. To prevent aliasing, a new object can be created and the contents of the original can be copied to it. a. True b. False ANSWER: True

12. The == operator returns True if the variables are aliases for the same object. Unfortunately, == returns False if the contents of two different objects are the same. a. True b. False ANSWER: False

13. The is operator has no way of distinguishing between object identity and structural equivalence. a. True b. False ANSWER: False

14. Anytime you foresee using a list whose structure will not change, you can, and should, use a tuple instead. a. True b. False ANSWER: True

15. A function can be defined in a Python shell, but it is more convenient to define it in an IDLE window, where it can be saved to a file. a. True b. False ANSWER: True

16. An Identity function usually tests its argument for the presence or absence of some property. a. True b. False ANSWER: False Copyright Cengage Learning. Powered by Cognero.

Page 2


Name:

Class:

Date:

Chapter 05: Lists and Dictionaries 17. In scripts that include the definitions of several cooperating functions, it is often useful to define a special function named init that serves as the entry point for the script. a. True b. False ANSWER: False

18. The main function usually expects no arguments and returns no value. a. True b. False ANSWER: True

19. The definition of the main function and the other function definitions can appear in no particular order in the script, as long as main is called at the very end of the script. a. True b. False ANSWER: True

20. A Python dictionary is written as a sequence of key/value pairs separated by commas. These pairs are sometimes called indexes. a. True b. False ANSWER: False

21. In a dictionary, a -> separates a key and its value. a. True b. False ANSWER: False

22. You add a new key/value pair to a dictionary by using the subscript operator []. a. True b. False ANSWER: True

23. If pop is used with just one argument and this key is absent from the dictionary, Python raises an error. a. True b. False ANSWER: True

24. A lookup table is a type of dictionary. a. True b. False ANSWER: True Copyright Cengage Learning. Powered by Cognero.

Page 3


Name:

Class:

Date:

Chapter 05: Lists and Dictionaries 25. The median of a list of values is the value that occurs most frequently. a. True b. False ANSWER: False

Multiple Choice 26. What statement regarding the use of lists is accurate? a. The individual elements within a list are immutable, in that the values cannot be changed. b. Two lists cannot be concatenated together, without the creation of a third list. c. A list can be sliced into sublists. d. When a list is evaluated, the elements are not evaluated. ANSWER: c

27. What list method should you use in order to remove and return the element at the end of the list named "books"? a. books.get() b. books.pop() c. books.fetch() d. books.pull() ANSWER: b

28. What method should you utilize to add the elements of list2 onto the end of list1? a. list1.extend(list2) b. list1.append(list2) c. list2.append(list1) d. list2.extend(list1) ANSWER: a

29. What statement accurately describes what a mutator is in the Python language? a. A mutator is a method that converts immutable data into mutable data. b. A mutator is a method used to encrypt text. c. A mutator is a method that is devoted entirely to the modification of the internal state of an object. d. A mutator is a method that changes the structure of a block of Python code. ANSWER: c

30. What operator should you utilize if you wish to test for object identity between two objects? a. == b. is c. != d. @! ANSWER: b Copyright Cengage Learning. Powered by Cognero.

Page 4


Name:

Class:

Date:

Chapter 05: Lists and Dictionaries 31. What statement accurately describes the difference between a list and a tuple? a. A list is immutable, while a tuple is not. b. A list is created with elements in parentheses, while a tuple is created with square brackets. c. A tuple's contents cannot be changed. d. A tuple can only hold integer and float data. ANSWER: c

32. You are designing a script that may be imported as a module in other scripts. What variable can you use to check whether the script has been imported as a module, or is running as the main script? a. __parent__ b. __name__ c. __operating_mode__ d. __status__ ANSWER: b

33. When a Python script is running as a standalone program, what will the __name__ variable be set to? a. The variable will hold the name of the script itself. b. The variable will be set to "__main__". c. The variable will be set to "standalone". d. The variable will be set to "None". ANSWER: b

34. In order to create a docstring for a defined function, where should the docstring be? a. The docstring should be just before the declaration of def. b. The docstring should be placed at the end of the execution block for the function. c. The docstring should be the next indented line after the def statement. d. The docstring should be placed at the end of the function, before the return statement. ANSWER: c

35. What is the return value for a function that has no return statement defined? a. The function will return a value of False. b. The function will return a value of True, provided there are no errors. c. The function will return a NULL value. d. The function will return a special value of None. ANSWER: d

36. What happens if you attempt to pop a key from a dictionary and the key does not exist, and you specified no default return? a. The pop will return a None value. b. The pop will return a value of 0. c. The pop will return a value of False. Copyright Cengage Learning. Powered by Cognero.

Page 5


Name:

Class:

Date:

Chapter 05: Lists and Dictionaries d. An error will be raised. ANSWER: d

37. What statement accurately describes the use of a parameter in Python? a. A parameter is the name used in the function definition for an argument that is passed to the function when it is called. b. A parameter is the name used for a function that is then referenced by other parts of the program. c. A parameter is the name used for data that is returned from the execution of a function. d. A parameter is the name given to an acceptable range of values that are output from a program. ANSWER: a

38. You are creating a Python script that will make use of user input contact names and their associated phone numbers. What would be ideal for storing and accessing these associated values? a. lists b. tuples c. dictionaries d. strings ANSWER: c

39. What dictionary operation can you use to remove all the keys within the dictionary named contacts? a. contacts.delete() b. contacts.remove() c. contacts.clear() d. contacts.dump() ANSWER: c

40. Which of the following assigns a dictionary list of keys and values to the variable named persons? a. persons = ["Sam":"CEO", "Julie":"President"] b. persons = ("Sam":"CEO", "Julie":"President") c. persons = {"Sam":"CEO", "Julie":"President"} d. persons = {["Sam", "CEO"], ["Julie", "President"]} ANSWER: c

41. What statement correctly defines what a median is? a. A median is the minimum value that is smaller than all other values in a set. b. A median is the maximum value that is greater than all other values in a set. c. A median is the value that is less than half the numbers in a set and greater than the other half. d. A median is the sum of all odd values in a set. ANSWER: c

42. When creating a list of items whose structure will not change, what should you ideally use to contain the values? Copyright Cengage Learning. Powered by Cognero.

Page 6


Name:

Class:

Date:

Chapter 05: Lists and Dictionaries a. lists b. tuples c. dictionaries d. strings ANSWER: b

43. When declaring a tuple, you enclose the tuple's elements in what two characters? a. [] b. () c. {} d. <> ANSWER: b

44. What happens if you use the following statement to sort a list of numbers called numbers? numbers = numbers.sort() a. numbers is a value of None b. The list is now ordered in ascending order. c. The list is now ordered in descending order. d. The numbers variable becomes a reference to a sorted list. ANSWER: a

45. What dictionary method can be utilized to access the entries in a dictionary variable with a name of parts? a. parts.list() b. parts.items() c. parts.print() d. parts.show() ANSWER: b

46. If you use the range method with a single parameter of 50, what will be the range of integers included in the returned list? a. 0 through 50 b. 0 through 49 c. 1 through 50 d. 1 through 49 ANSWER: b

Multiple Response 47. A list is a sequence of data values known by either of what two terms? (Choose two.) a. cards b. instances c. items Copyright Cengage Learning. Powered by Cognero.

Page 7


Name:

Class:

Date:

Chapter 05: Lists and Dictionaries d. elements ANSWER: c, d

48. In a Python dictionary, an association is formed between what two components of the dictionary? (Choose two.) a. lists b. keys c. values d. indexes ANSWER: b, c

49. What are the two arguments expected by the get method for a dictionary object? (Choose two.) a. A possible key. b. An index position. c. A list of keys. d. A default value. ANSWER: a, d

50. In computer science, what are two names that are used to describe data structures organized by association? (Choose two.) a. matrices b. tables c. association lists d. family trees ANSWER: b, c

Copyright Cengage Learning. Powered by Cognero.

Page 8


Name:

Class:

Date:

Chapter 06: Design with Functions True / False 1. It is possible to construct any algorithm using only Python's built-in operators and control statements. a. True b. False ANSWER: True

2. An abstraction hides detail and thus allows a person to view many things as just one thing. a. True b. False ANSWER: True

3. A function call expresses the idea of a process to the programmer, forcing him or her to wade through the complex code that realizes that idea. a. True b. False ANSWER: False

4. When you design an algorithm, it should be general enough to provide a solution to many problem instances, not just one or a few of them. a. True b. False ANSWER: True

5. A black-box chart is a diagram that shows the relationships among a program's functions and the passage of data between them. a. True b. False ANSWER: False

6. Each box in a structure chart is labeled with a module name. a. True b. False ANSWER: False

7. The assignment of roles and responsibilities to different actors in a program is also called responsibilitydriven design. a. True b. False ANSWER: True

8. The use of a common pool of data allows a program to grow easily as new data sources are added to the program. Copyright Cengage Learning. Powered by Cognero.

Page 1


Name:

Class:

Date:

Chapter 06: Design with Functions a. True b. False ANSWER: True

9. In bottom-up design, you decompose a complex problem into a set of simpler problems and solve these with different functions. a. True b. False ANSWER: False

10. A recursive function must contain at least one repetition statement. a. True b. False ANSWER: False

11. Most recursive functions expect no arguments. a. True b. False ANSWER: False

12. To get a better understanding of how recursion works, it is helpful to trace its calls. a. True b. False ANSWER: True

13. Recursive functions are frequently used to design algorithms for computing values that have a recursive definition. a. True b. False ANSWER: True

14. The first five numbers of the Fibonacci sequence are 1 3 5 8 13. a. True b. False ANSWER: False

15. Recursive functions tend to be more complicated than the corresponding loops. a. True b. False ANSWER: False

16. In a case of infinite recursion, the Python virtual machine eventually runs out of memory resources to manage the process, so it halts execution with an error message. Copyright Cengage Learning. Powered by Cognero.

Page 2


Name:

Class:

Date:

Chapter 06: Design with Functions a. True b. False ANSWER: True

17. An infinite recursion eventually halts execution with an error message. a. True b. False ANSWER: False

18. Recursive solutions are often more natural and elegant than their iterative counterparts. a. True b. False ANSWER: True

19. When a call returns or completes its execution, the memory for the stack frame is reallocated. a. True b. False ANSWER: False

20. The amount of memory needed for a loop grows with the size of the problem's data set. a. True b. False ANSWER: False

21. Smart compilers exist that can optimize some recursive functions by translating them to iterative machine code. a. True b. False ANSWER: True

22. A program's namespace is the set of its variables and their values. a. True b. False ANSWER: True

23. A method reference always uses an object, which can be denoted by a string followed by a dot and the method name. a. True b. False ANSWER: True

24. A Python function cannot under normal circumstances reference a module variable for its value. a. True Copyright Cengage Learning. Powered by Cognero.

Page 3


Name:

Class:

Date:

Chapter 06: Design with Functions b. False ANSWER: False

25. When using functions that have default arguments, the required arguments must be provided and must be placed in the same positions as they are in the function definition's header. a. True b. False ANSWER: True

Multiple Choice 26. The process of hiding a complex process by developing a mechanism to simplify or hide that process is known by what term? a. simplification b. obfuscation c. abstraction d. diffraction ANSWER: c

27. How does top-down design work? a. A problem is solved by employing a large task force to evaluate the cause. b. A problem is solved by redesigning and repurposing existing software. c. A solution is created to solve a problem, and individual issues are resolved as they are encountered. d. A problem is decomposed into smaller problems, which are gradually solved to produce a solution. ANSWER: d

28. What is the name for a diagram that shows the relationships among a program's functions and the passage of data between them? a. data map b. structure map c. structure chart d. program flowchart ANSWER: c

29. What can often provide you with a pattern for designing the structure of a program? a. The structure of the problem you're attempting to solve. b. The structure of code written by other people. c. The structure of an organization's workforce. d. The structure of the programming language used. ANSWER: a

30. The assignment of roles and responsibilities to different actors in a program is known as what type of Copyright Cengage Learning. Powered by Cognero.

Page 4


Name:

Class:

Date:

Chapter 06: Design with Functions design? a. role-based access design b. responsibility-driven design c. delegated assignment design d. task abstraction design ANSWER: b

31. The Fibonacci sequence is a series of values that can be easily calculated with what kind of function? a. recursive function b. repeating function c. duplicating function d. compounding function ANSWER: a

32. In a recursive function, what is used to determine whether to stop or to continue with another recursive step? a. terminator value b. base case c. recursion factor d. step counter ANSWER: b

33. What type of error is raised when the Python virtual machine runs out of memory resources to manage a process? a. runaway process error b. out of memory error c. input output error d. stack overflow error ANSWER: d

34. What is the call stack used for in the Python virtual machine? a. The call stack is an area of reserved memory used to store chunks of memory related to functions. b. The call stack is an area of reserved memory used to perform system calls for access to hardware. c. The call stack is a log of called functions and methods within the program. d. The call stack is a temporary storage area for junk data. ANSWER: a

35. For each call of a function, the Python virtual machine must allocate a small chunk of memory on the call stack, which is known by what term? a. stack chunk b. stack frame c. data nibble Copyright Cengage Learning. Powered by Cognero.

Page 5


Name:

Class:

Date:

Chapter 06: Design with Functions d. memory slice ANSWER: b

36. What happens when a function tries to assign or change a value of a variable that has been defined at the module level? a. The function succeeds, because the module variable is considered global in scope. b. The function succeeds, but the value is appended to the variable. c. The function fails, and an out of scope error message is raised. d. Python creates a temporary variable with the same name, and the value of that variable exists only within the scope of the function. ANSWER: d

37. Where can the required arguments for a function be found? a. In the function header. b. In the module docstring. c. In the function keyword list. d. In the function's return list. ANSWER: a

38. What is the purpose of a higher-order function? a. It separates the task of transforming data values from the logic of accumulating the results. b. It is a mutator that can be utilized on functions to remove redundant patterns in code. c. It allows the definition of specialized ordering logic for data sets. d. It is a special function that ignores program scope and has access to localized variables. ANSWER: a

39. In Python, functions are treated as first-class data objects. What does this mean? a. It means that they are considered to be global variables inside any Python code. b. It means that the functions are given higher priority over resource access than regular chunks of code. c. It means that functions are protected objects and are not easily imported from other modules, unless the author desires it. d. It means that functions can be assigned to variables, passed as arguments to other functions, returned as values, and stored in data structures. ANSWER: d

40. What higher-order function process applies a function to each value in a sequence and returns a new sequence of the results? a. mapping b. filtering c. reducing d. associating Copyright Cengage Learning. Powered by Cognero.

Page 6


Name:

Class:

Date:

Chapter 06: Design with Functions ANSWER: a

41. In what higher-order function do you apply a predicate to each value within a list, and if the predicate returns true, the value is added to an object? a. mapping b. filtering c. reducing d. associating ANSWER: b

42. What higher-order function takes a list of values and repeatedly applies a function to accumulate a single data value? a. mapping b. filtering c. reducing d. associating ANSWER: c

43. What is the lambda function in Python utilized for? a. It allows for the creation of an anonymous function, which contains the names of its arguments and a single expression. b. It creates an overloaded function, such that the function can be repurposed on the fly. c. It allows for the tracking of use of a targeted function. d. It allows for multiple higher-order functions to be utilized on the same selection statements. ANSWER: a

44. What term describes a dictionary of functions keyed by command names? a. command table b. jump table c. skip table d. function table ANSWER: b

45. What makes up a Python program's namespace? a. The combination of all included modules and their functions. b. The set of all its variables and their values. c. The defined methods of the program. d. The main method of the program itself. ANSWER: b

46. The gradual process of developing functions to solve each subproblem in a top-down design is known as what process? Copyright Cengage Learning. Powered by Cognero.

Page 7


Name:

Class:

Date:

Chapter 06: Design with Functions a. procedural refinement b. stepwise refinement c. progressing resolution d. incremental solving ANSWER: b

47. In Python, what is the term that is used to describe the area of a program text in which an object name refers to a given value? a. relation b. relevance c. lifetime d. scope ANSWER: d

Multiple Response 48. What are two common methods by which functions serve as abstraction mechanisms? (Choose two.) a. The elimination of redundant, or repetitious code. b. The availability of detailed docstring data. c. The hiding of complicated processes. d. The use of a bottom-up approach to design. ANSWER: a, c

49. What are the two different ways that default arguments can be provided to a function? (Choose two.) a. By supplying arguments in which they occur in the function header. b. By using a reference pointer variable. c. By overloading the function and redefining the arguments. d. By assigning values to the keys in the function header. ANSWER: a, d

50. Which of the following statements are accurate? (Choose two.) a. Parameters for a function receive values when they are declared. b. When module variables are introduced in a program, they are immediately given a value. c. A nested variable can assign value to a variable outside of its scope. d. Temporary values receive their values as soon as they are introduced. ANSWER: b, d

Copyright Cengage Learning. Powered by Cognero.

Page 8


Name:

Class:

Date:

Chapter 06: Inheritance and Abstract Classes True / False 1. The easiest way to take advantage of inheritance is to use it to customize an existing class. a. True b. False ANSWER: True

2. When a class is customized using inheritance, the two classes should have a similar interface. a. True b. False ANSWER: True

3. When you use inheritance to customize a class, the existing and new class have identical behavior. a. True b. False ANSWER: False

4. A class that inherits properties from another class is called a superclass. a. True b. False ANSWER: False

5. To begin creating a subclass, copy the parent class's file and delete the methods that will not change. a. True b. False ANSWER: True

6. To ensure that inheritance occurs, you need to place the name of the subclass in parentheses of the class header. a. True b. False ANSWER: False

7. The __init__ method in the parent class is automatically called by a subclass of the parent class. a. True b. False ANSWER: False

8. When calling the __init__ method from a subclass, you need to include the self argument. a. True b. False ANSWER: True Copyright Cengage Learning. Powered by Cognero.

Page 1


Name:

Class:

Date:

Chapter 06: Inheritance and Abstract Classes 9. To distinguish a method in the parent class from a method with the same name in a subclass, prefix the method name with self. a. True b. False ANSWER: False

10. The root class of the Python hierarchy is called object. a. True b. False ANSWER: True

11. By using inheritance to create new classes, you increase code redundancy. a. True b. False ANSWER: False

12. An abstract class captures the common features and behavior of a set of related classes. a. True b. False ANSWER: True

13. An abstract class is always used to create objects in client applications. a. True b. False ANSWER: False

14. A concrete class is often a subclass of an abstract class and is used to create objects in client applications. a. True b. False ANSWER: True

15. An instance variable is considered redundant if two different classes use it and it refers to a different type of data structure in each class. a. True b. False ANSWER: False

16. An instance variable that refers to an integer in two different related classes is a likely candidate to be moved to an abstract class. a. True b. False ANSWER: True Copyright Cengage Learning. Powered by Cognero.

Page 2


Name:

Class:

Date:

Chapter 06: Inheritance and Abstract Classes 17. A set of methods that could be used on other data structures besides the one they were created for could be used in a general abstract class. a. True b. False ANSWER: True

18. When looking at a hierarchy of abstract classes, the classes trend from the more specific to the more general going from the top to the bottom of the hierarchy. a. True b. False ANSWER: False

19. The implementations of the __str__ and __eq__ methods in the AbstractCollection class can be used in both unordered and linear collections. a. True b. False ANSWER: False

20. A class that uses lists can use the methods defined in the AbstractCollection class. a. True b. False ANSWER: True

21. The __eq__ method in the AbstractCollection class compares pairs of items in two collections. a. True b. False ANSWER: True

22. A primary purpose of using inheritance is to eliminate redundant code. a. True b. False ANSWER: True

23. Programming languages such as Java include a collection framework more extensive than that of Python. a. True b. False ANSWER: True

24. When a programmer calls the iter function on a collection, the collection's iterator object is returned. a. True b. False ANSWER: True Copyright Cengage Learning. Powered by Cognero.

Page 3


Name:

Class:

Date:

Chapter 06: Inheritance and Abstract Classes 25. If a programmer calls the next function on an iterator object and there is no current item in the sequence, the next function returns the Null item. a. True b. False ANSWER: False

Multiple Choice 26. What is one of the primary purposes of using inheritance? a. to customize an existing class b. to create code redundancy c. to avoid creating an __init__ method d. to duplicate methods in an interface ANSWER: a

27. Which of the following is true about the sorted bag collection compared to the regular bag collection? a. the add method is identical in both b. the __init__ method is identical in both c. the sorted bag's in operator runs in linear time d. the items in a sorted bag must be of the same type ANSWER: d

28. When considering the ArrayBag class and the ArraySortedBag class, which of the following is true? a. the ArraySortedBag class is the parent of the ArrayBag class b. the ArraySortedBag class is a subclass of ArrayBag c. the ArrayBag class is a subclass of ArraySortedBag d. the ArrayBag class is the child class of ArraySortedBag ANSWER: b

29. How is creating a subclass of an existing class different from copying the code from the existing class to a new file? a. when subclassing, you delete all of the methods that you don’t have to change b. you don't need an __init__ method c. the name of the subclass is in parentheses of the class header d. no methods need be created or modified ANSWER: a

30. Which of the following is NOT a step in using inheritance to create a subclass? a. delete the methods that do not change b. duplicate redundant instance variables c. modify the code for methods that change d. add any new methods Copyright Cengage Learning. Powered by Cognero.

Page 4


Name:

Class:

Date:

Chapter 06: Inheritance and Abstract Classes ANSWER: b

31. What is the syntax for the calling the __init__ method in the ArrayBag class from the ArraySortedBag class? a. self.init(ArrayBag, sourceCollection) b. ArrayBag.self(__init__, sourceCollection) c. ArrayBag.__init__(self, sourceCollection) d. __init__.ArrayBag(self, sourceCollection) ANSWER: c

32. In the ArraySortedBag class, why must the self argument be passed to the __init__ method of ArrayBag? a. to ensure the add method in ArraySortedBag is called if a source collection is specified b. to ensure that ArraySortedBag calls the correct __init__ method c. to ensure that ArrayBag calls its own __init__ method d. to ensure the add method in ArrayBag is called if a source collection is specified ANSWER: a

33. What method is called when the in operator is used on a sorted bag? a. __iter__ b. __contains__ c. __init__ d. add ANSWER: b

34. In which situation is a search unnecessary when performing the add method on a sorted bag? a. when the bag is full b. when the new item is less than the last item c. when the new item is greater than the first item d. when the bag is empty ANSWER: d

35. The following code is part of the __add__ method in the ArraySortedBag class. What is the missing code? if self.isEmpty() or item >= self.items[len(self) - 1]: <missing code>

a. add.self(item) b. ArrayBag.add(item) c. ArrayBag.add(self, item) d. add.ArrayBag(self, item) Copyright Cengage Learning. Powered by Cognero.

Page 5


Name:

Class:

Date:

Chapter 06: Inheritance and Abstract Classes ANSWER: c

36. Which operator, when used with two bags, causes Python to run the __add__ method? a. = b. * c. + d. % ANSWER: c

37. What is the root class of Python's built-in class hierarchy? a. self b. list c. dict d. object ANSWER: d

38. What is a class called when the purpose of it is to eliminate redundant methods in other classes? a. concrete class b. abstract class c. subclass d. child class ANSWER: b

39. Which of the following is true about abstract classes? a. they are the same as a class interface b. the are always a subclass of a superclass c. they are not normally instantiated in client applications d. they are used as concrete classes by client applications ANSWER: c

40. Under which circumstance can an instance variable be moved to an abstract class? a. when it refers to the same type of data structure as the same instance variable in other concrete implementations of the abstract class

b. when it is unique to a particular concrete class c. when different data structure types are referenced by the variable d. when it directly modifies the underlying data structure ANSWER: a

41. Which of the following is true about the three bag classes (LinkedBag, ArrayBag, ArraySortedBag)? a. they are abstract classes b. they implement the bag interface c. the are all superclasses Copyright Cengage Learning. Powered by Cognero.

Page 6


Name:

Class:

Date:

Chapter 06: Inheritance and Abstract Classes d. LinkedBag is a subclass of ArraySortedBag ANSWER: b

42. When implementing the __init__ method in the AbstractBag class, what task should you leave out because it is the responsibility of the subclasses? a. setting the self.size variable to 0 b. adding items from the source collection c. initializing the self.items variable d. checking if a source collection exists ANSWER: c

43. What is one thing the subclasses must do to use it? a. reference the abstract class in their __init__ method. b. copy the code to the subclass file c. nothing, the abstract class is automatically included in the subclass d. import the abstract class ANSWER: d

44. In the constructor for the ArrayBag class shown below, what is the missing code? def __init__(self, sourceCollection = None): <missing code> AbstractBag.__init__(self, sourceCollection) a. items.add(self) b. self.items = Array(ArrayBag.DEFAULT_CAPACITY) c. self.items = ArrayBag.add(sourceCollection) d. add.items(self, sourceCollection) ANSWER: b

45. What would be the purpose of creating a more general abstract class called AbstractCollection? a. to group methods used by a single subclass b. to hide the details of the methods used in your abstract classes c. to create objects from a client application d. to group methods that can be used for other types of collections ANSWER: d

46. In the case of the AbstractCollection class, which of the following methods should NOT be included in this class? a. __add__ b. isEmpty c. __len__ Copyright Cengage Learning. Powered by Cognero.

Page 7


Name:

Class:

Date:

Chapter 06: Inheritance and Abstract Classes d. count ANSWER: a

47. When creating the AbstractCollection class, which methods must you modify to provide default behavior? a. __len__ and count b. __str__ and __eq__ c. isEmpty and add d. __init__ and __len__ ANSWER: b

48. When a programmer calls the next function on an iterator object, what happens if there is no current item in the sequence? a. the previous item is returned b. the compiler generates an error c. a StopIteration exception is raised d. the None item is returned ANSWER: c

49. In the following code for the ArrayBag class __contains__ method, what is the missing code? def __contains__(self, item): left = 0 right = len(self) - 1 while left <= right: midPoint = (left + right) // 2 if self.items[midPoint] == item: return True elif self.items[midPoint] > item: right = midPoint - 1 else: <missing code> return False a. right = midPoint + 1 b. left = midPoint - 1 c. right = left + 1 d. left = midPoint + 1 ANSWER: d

50. In the following code for the __add__ method in the ArraySortedBag class, what is the missing code? def __add__(self, other): result = ArraySortedBag(self) for item in other: Copyright Cengage Learning. Powered by Cognero.

Page 8


Name:

Class:

Date:

Chapter 06: Inheritance and Abstract Classes <missing code> return result a. result = result + 1 b. item.add(result) c. result.add(item) d. add.item(result) ANSWER: c

Copyright Cengage Learning. Powered by Cognero.

Page 9


Name:

Class:

Date:

Chapter 07: Simple Graphics and Image Processing True / False 1. The coordinate system for turtle graphics is the standard Cartesian system, with the origin (0, 0) at the bottom-left corner of a window. a. True b. False ANSWER: False

2. In turtle graphics, the turtle is initially facing east. a. True b. False ANSWER: True

3. In turtle graphics, the color used is initially black. a. True b. False ANSWER: True

4. In turtle graphics, the width of the line drawn when the turtle moves is initially 2 pixels. a. True b. False ANSWER: False

5. Generally, an object's state is the set of values of its attributes at any given point in time. a. True b. False ANSWER: True

6. The setPixels method of the Turtle class changes the width of the turtle in pixels to the specified value. a. True b. False ANSWER: False

7. Programmers who use objects interact with them through their interfaces. a. True b. False ANSWER: True

8. Constructors are used to create new instances of a class. a. True b. False ANSWER: True Copyright Cengage Learning. Powered by Cognero.

Page 1


Name:

Class:

Date:

Chapter 07: Simple Graphics and Image Processing 9. An attempt to manipulate a turtle whose window has been closed raises an exception. a. True b. False ANSWER: True

10. The rectangular display area on a computer screen is made up of colored dots called picture elements or pixels. a. True b. False ANSWER: True

11. The size of a pixel is determined by the size and resolution of the display. a. True b. False ANSWER: True

12. RGB stands for red, green, and black. a. True b. False ANSWER: False

13. In the RGB system, each color component can range from 0 through 127. a. True b. False ANSWER: False

14. In the RGB system, the value 255 represents the total absence of that component. a. True b. False ANSWER: False

15. The RGB system is called a true color system. a. True b. False ANSWER: True

16. A fractal object can be described using Euclidean geometry. a. True b. False ANSWER: False

17. A fractal curve is one-dimensional. a. True Copyright Cengage Learning. Powered by Cognero.

Page 2


Name:

Class:

Date:

Chapter 07: Simple Graphics and Image Processing b. False ANSWER: False

18. An N-level c-curve can be drawn with a recursive function. a. True b. False ANSWER: True

19. The ticks representing seconds on the analog clock's face represent an attempt to sample moments of time as discrete values, whereas time itself is continuous, or analog. a. True b. False ANSWER: True

20. Early recording and playback devices for images and sound were all discrete devices. a. True b. False ANSWER: False

21. A raw image file saves all of the sampled information. a. True b. False ANSWER: True

22. The GIF format uses a lossless compression scheme. a. True b. False ANSWER: False

23. The screen coordinate system for the display of an image is somewhat different from the standard Cartesian coordinate system used with Turtle graphics. a. True b. False ANSWER: True

24. The images module is a standard, open-source Python tool. a. True b. False ANSWER: False

25. Many image-processing algorithms use a nested loop structure to traverse a two-dimensional grid of pixels. a. True b. False Copyright Cengage Learning. Powered by Cognero.

Page 3


Name:

Class:

Date:

Chapter 07: Simple Graphics and Image Processing ANSWER: True

Multiple Choice 26. Programming that relies on the use of objects and methods to control complexity and solve problems is known as what type of programming? a. access-based programming b. object-based programming c. serial-based programming d. entry-based programming ANSWER: b

27. The Turtle graphics toolkit was originally developed as part of what programming language for children? a. LISP b. FORTRAN c. Logo d. CKids ANSWER: c

28. What coordinate system is utilized for the Turtle graphics toolkit? a. cartesian system b. polar system c. square system d. fractal system ANSWER: a

29. Given a Turtle object of t, what method can you use to erase all of the turtle's drawings, without changing the state? a. t.delete() b. t.clear() c. t.erase() d. t.scratch() ANSWER: b

30. The drawing of simple, two-dimensional shapes, such as rectangles, triangles, pentagons, and circles, is known as what type of graphics? a. planar graphics b. vector graphics c. geometric graphics d. targeted graphics ANSWER: b Copyright Cengage Learning. Powered by Cognero.

Page 4


Name:

Class:

Date:

Chapter 07: Simple Graphics and Image Processing 31. What type of method returns the values of an object's attributes without altering its state? a. mutator methods b. controller methods c. accessor methods d. positional methods ANSWER: c

32. What statement accurately defines what a pixel is? a. A pixel is the name for the graphical draw point of any graphics generating program. b. A pixel is the graphical equivalent of a byte in memory, and is used to store graphics data. c. A pixel is a graphical font, which is used to write image data onto a screen. d. A pixel is a colored dot, also known as a picture element, that makes up part of a display. ANSWER: d

33. What RGB value should you use to produce a blue color? a. 0, 0, 0 b. 0, 255, 0 c. 255, 255, 0 d. 0, 0, 255 ANSWER: d

34. What is the maximum number of distinct color values that can be displayed by the true color RGB system? a. 256 b. 16,384 c. 32,768 d. 16,777,216 ANSWER: d

35. What does the term "sampling" imply in relation to images? a. The mapping of analog information in a visual format to discrete values. b. The conversion of digital into analog information for display on a screen. c. The process of creating analog information from digital information, for use in computer programs. d. The utilization of a sample of data to represent a larger digital data set. ANSWER: a

36. How does digital information differ from analog information? a. Digital information can be represented as wave patterns, while analog information consists of bits. b. Digital information consists of a continuous range of values, while analog is a set of discrete values. c. Digital information consists of discrete values, while analog is a continuous range of values. d. Digital information is commonly used in basic image and sound devices, such as recorded records, while analog is used for electronic media. Copyright Cengage Learning. Powered by Cognero.

Page 5


Name:

Class:

Date:

Chapter 07: Simple Graphics and Image Processing ANSWER: c

37. What type of image compression analyzes larger regions of pixels and saves a color value that the pixels' colors approximate? a. lossless compression b. lossy compression c. summary compression d. recursive compression ANSWER: b

38. In the images module, how does the Image class represent an image? a. Using a detailed sample of the image's brightness values. b. Using a rasterized copy of the image's color values. c. Using a two-dimensional grid of RGB values. d. Using a pixel map determined by grayscale values. ANSWER: c

39. Assuming you have an images module object named i, what method can you use to change the pixel at coordinate 238, 590 to red? a. i.setPixel(238, 590, (255, 0, 0)) b. i.chgPixel(590, 238, (0, 255, 0)) c. i.modPixel(238, 590, (255, 0, 0)) d. i.Pixel(238, 590, (0, 0, 255)) ANSWER: a

40. A black-and-white photograph contains more than just the black and white colors, but various shades of gray known by what term? a. grayshade b. graymap c. graycurve d. grayscale ANSWER: d

41. Why is the conversion of an image to grayscale by simply computing the average of a pixel less than ideal? a. The conversion will still contain non-grayscale colors. b. The conversion does not take luminance into account. c. The conversion will cause some areas of the image to be invisible d. The conversion will make details that are red or green in color hard to see. ANSWER: b

42. What is the term used to describe the processing of a multi-row, multi-column grid of information using a nested loop structure? Copyright Cengage Learning. Powered by Cognero.

Page 6


Name:

Class:

Date:

Chapter 07: Simple Graphics and Image Processing a. field circuit mapping b. row-column mapping c. row-major traversal d. grid-centric retrieval ANSWER: c

43. When discussing an image, what is an image's aspect ratio? a. The ratio of the image's width to its height. b. The ratio of the image's colors to their brightness. c. The ratio of the image's bitrate to its size. d. The ratio of the image's color gamut to its bitrate. ANSWER: a

44. What effect does a higher DPI have on the sampling done by a digital camera? a. It decreases the number of samples that are taken. b. It increases the number of samples that are taken. c. It decreases the amount of time needed for each sample. d. It increases the amount of time needed for each sample. ANSWER: b

45. What Turtle method is used to move the Turtle object instance t to the center of the window, pointed east? a. t.start() b. t.home() c. t.return() d. t.restart() ANSWER: b

46. What is instantiation in Python? a. It is the process of creating an IDLE session that utilizes a graphics window. b. It is the process of calling a module mutator method. c. It is the process of calling a function that returns no object. d. It is the process of creating a class-based object. ANSWER: d

47. When instantiating a class and assigning the resulting object to a variable, what is the right side of the assignment called? a. The instantiator statement. b. The spawner statement. c. The constructor statement. d. The creator statement. ANSWER: c Copyright Cengage Learning. Powered by Cognero.

Page 7


Name:

Class:

Date:

Chapter 07: Simple Graphics and Image Processing Multiple Response 48. Which of the following classes are associated with a Turtle object? (Choose two.) a. Screen b. Canvas c. Plot d. Page ANSWER: a, b

49. Which of the following image formats are considered to be the most popular? (Choose two.) a. XCF b. GIF c. JPEG d. SVG ANSWER: b, c

50. What two Turtle methods affect the color of a Turtle drawing? (Choose two.) a. setcolor() b. pencolor() c. fillcolor() d. drawcolor() ANSWER: b, c

Copyright Cengage Learning. Powered by Cognero.

Page 8


Name:

Class:

Date:

Chapter 07: Stacks True / False 1. Access to a stack is restricted to the bottom end. a. True b. False ANSWER: False

2. Stacks adhere to a LIFO protocol. a. True b. False ANSWER: True

3. The operation for removing an item from the stack is called push. a. True b. False ANSWER: False

4. With a stack, you always access the item that has been most recently added. a. True b. False ANSWER: True

5. The operator in a postfix expression follows the operands. a. True b. False ANSWER: True

6. The operator in an infix expression follows the operands. a. True b. False ANSWER: False

7. A stack structure is a built-in part of the Python language. a. True b. False ANSWER: False

8. A Python list structure and its methods implement a stack perfectly. a. True b. False ANSWER: False

9. Stack interfaces implement a peek operation for examining the element at the top of the stack. Copyright Cengage Learning. Powered by Cognero.

Page 1


Name:

Class:

Date:

Chapter 07: Stacks a. True b. False ANSWER: True

10. The pop operation for a stack raises an error if the stack is empty. a. True b. False ANSWER: True

11. The push operation for a stack raises an error if the stack is empty. a. True b. False ANSWER: False

12. Using a stack is a good approach to determining if the use of brackets in an expression is balanced. a. True b. False ANSWER: True

13. When using a stack to determine if brackets are balanced in an expression, the stack should not be empty when you reach the end of the expression. a. True b. False ANSWER: False

14. When evaluating an arithmetic expression, first you transform it from its postfix form to its infix form. a. True b. False ANSWER: False

15. The equation 17 46 + is an example of postfix form. a. True b. False ANSWER: True

16. When converting from infix form to postfix form, parentheses are added to the equation. a. True b. False ANSWER: False

17. The first step in evaluating a postfix expression is to scan the expression from left to right. a. True Copyright Cengage Learning. Powered by Cognero.

Page 2


Name:

Class:

Date:

Chapter 07: Stacks b. False ANSWER: True

18. A token in the postfix expression evaluation algorithm is an operand or operator. a. True b. False ANSWER: True

19. Addition and subtraction have higher precedence when evaluating an infix expression. a. True b. False ANSWER: False

20. Because of their linear structure, stacks can only be implemented using linked structures. a. True b. False ANSWER: False

21. To avoid stack overflow, the stack algorithm should raise an error if an item is added to a full stack. a. True b. False ANSWER: False

22. In a linked structure stack implementation, efficient pushing and popping require adding and removing of nodes at the head of the linked sequence. a. True b. False ANSWER: True

23. The Node class for use in the linked structure stack contains three fields: data, next, and previous. a. True b. False ANSWER: False

Multiple Choice 24. Which of the following is true about stacks? a. they are analogous to a row of books on a shelf b. items are always added to the bottom c. access is restricted to just one end d. most implementations allow access to the middle ANSWER: c Copyright Cengage Learning. Powered by Cognero.

Page 3


Name:

Class:

Date:

Chapter 07: Stacks 25. What protocol are stacks said to adhere to? a. LIFO b. FIFO c. one-to-one d. many-to-one ANSWER: a

26. What is the operation that adds items to a stack? a. get b. set c. push d. pop ANSWER: c

27. Which of the following is NOT an example of a stack in everyday life? a. a spindle of blank DVDs b. a stack of plates in a cafeteria line c. a pile of napkins d. a jar of jellybeans ANSWER: d

28. Which of the following is true about a postfix expression? a. the operator is between its two operands b. the operator follows its two operands c. the operator precedes d. the expression is fully parenthesized ANSWER: b

29. Which of the following is NOT an application of stacks in computer science? a. implementation of a hash-based database search function b. managing computer memory in support of function calls c. supporting the undo feature in a text editor d. maintaining a history of visited links by a web browser ANSWER: a

30. In what way doesn't the Python list data structure accurately emulate a stack? a. the append method pushes elements onto the stack b. the pop method removes and returns the top element c. a list uses an array as the underlying data structure d. list methods allow manipulation of items at any position ANSWER: d Copyright Cengage Learning. Powered by Cognero.

Page 4


Name:

Class:

Date:

Chapter 07: Stacks 31. Which of the following is NOT an operation supported by a stack interface? a. push b. insert c. clear d. peek ANSWER: b

32. If the current state of the stack is [x, y, z] where x is the bottom of the stack and z is the top of the stack, what is the state of the stack and the value returned after a pop operation? a. the state is [x, y]; z is returned b. the state is [x, y, z]; z is returned c. the state is [y, z]; x is returned d. the state is [x, y, z]; x is returned ANSWER: a

33. When using a stack to evaluate the balance of brackets and parentheses in an expression, what is the first step? a. push opening brackets onto the stack while scanning the expression b. pop closing brackets onto the stack while scanning the expression c. push closing brackets onto the stack while scanning the expression d. pop opening brackets onto the stack while scanning the expression ANSWER: a

34. When using a stack to evaluate the balance of brackets and parentheses in an expression, what is the final step? a. at the end of the expression, if a final closing bracket is found, the brackets balance b. at the end of the expression, if the stack is empty, the brackets do not balance c. at the end of the expression, if the stack is full, the brackets balance d. at the end of the expression, if the stack is empty, the brackets balance ANSWER: d

35. In the algorithm that checks for a balanced expression, which of the following is true if a closing bracket is encountered? a. if the stack is empty, the brackets balance b. if the item on the top of the stack is a closing bracket of the same type, the brackets balance c. if the stack is empty or the item on the top of the stack is not an opening bracket of the same type, the brackets don't balance d. if the stack is empty or the item on the bottom of the stack is an opening bracket of the same type, the brackets balance ANSWER: c

36. What is the function of the peek method in a stack implementation? Copyright Cengage Learning. Powered by Cognero.

Page 5


Name:

Class:

Date:

Chapter 07: Stacks a. to return the bottom item without removing it b. to return the top item without removing it c. to return the top item and remove it from the stack d. to return the bottom item and remove it from the stack ANSWER: b

37. What is the first step in the algorithm to evaluate an arithmetic expression? a. transform the expression from postfix form to infix form b. calculate the result from the postfix expression c. calculate the result from the infix expression d. transform the expression from infix form to postfix form ANSWER: d

38. In the algorithm to evaluate a postfix expression, what does the algorithm do when an operator is encountered? a. pop the resulting value from the stack b. push the preceding operands onto the stack c. apply the operator to the two preceding operands d. push the operator onto the stack ANSWER: c

39. In the algorithm to evaluate a postfix expression, what does the algorithm do when an operand is encountered? a. pop the operand from the stack b. push the operand onto the stack c. pop the operator from the stack d. push an operator onto the stack ANSWER: b

40. If the portion of the postfix expression scanned so far is 7 6 2 +, what is the result when the operator is applied to the operands? a. 8 b. 15 c. 13 d. 9 ANSWER: a

41. If the entire postfix expression is 9 1 4 + - 2 *, what is the final value? a. 12 b. 8 c. 17 Copyright Cengage Learning. Powered by Cognero.

Page 6


Name:

Class:

Date:

Chapter 07: Stacks d. 10 ANSWER: b

42. What is the resulting postfix expression from the following infix expression? (12 + 5) * 2 - 3 a. 12 5 2 + * 3 b. 12 5 + 2 3 * c. 12 5 + 2 * 3 d. 12 5 2 + 3 - * ANSWER: c

43. What is the resulting infix expression from the following postfix expression? 17 4 - 6 + 8 * a. 17 - (4 + 6 * 8) b. 17 - (4 + 6) * 8 c. (17 - 4) + (6 * 8) d. (17 - 4 + 6) * 8 ANSWER: d

44. Which of the following begins in a predefined starting state and then moves from state to state in search of a desired ending state? a. backtracking algorithm b. memory management algorithm c. infix to postfix converter d. postfix to infix converter ANSWER: a

45. What is the function of the PVM? a. converts methods to subroutines b. executes a python program from bytecodes c. compiles Python code into assembly language d. links a Python program to imported modules ANSWER: b

46. In the following code that defines the push method for the array-based stack, what is the missing code? def push (self, item): <missing code> self.size += 1 a. self.items += 1 b. self.items[len(self)] = item c. items[size] = len(self.item) d. item = self.items[self.size + 1] Copyright Cengage Learning. Powered by Cognero.

Page 7


Name:

Class:

Date:

Chapter 07: Stacks ANSWER: b

47. What are the two fields required by the Node class in the linked implementation of a stack? a. prev, items b. prev, data c. items, next d. data, next ANSWER: d

48. In the linked implementation of a stack, what type of helper function simplifies the __iter__ method? a. binary b. sequential c. recursive d. random ANSWER: c

Subjective Short Answer 49. A tuple is an immutable collection type. ANSWER:

50. The time complexity of the postfix expression evaluation algorithm is O(n2) . ANSWER:

Copyright Cengage Learning. Powered by Cognero.

Page 8


Name:

Class:

Date:

Chapter 08: Graphical User Interrfaces True / False 1. GUI-based programs use windows that contain various components, also called window objects or gadgets. a. True b. False ANSWER: False

2. In a GUI-based program, the user can usually alter the size of a window by holding the mouse on its lowerleft corner and dragging in any direction. a. True b. False ANSWER: False

3. GUI-based programs are almost always object-oriented. a. True b. False ANSWER: True

4. The creation of a customized version of an existing class is called subclassing. a. True b. False ANSWER: True

5. Command buttons are created and placed in a window in the same manner as labels. a. True b. False ANSWER: True

6. Command buttons can display text but not images. a. True b. False ANSWER: False

7. The attributes of each window component are actually stored in a list. a. True b. False ANSWER: False

8. A method header looks very different from a function header. a. True b. False ANSWER: False Copyright Cengage Learning. Powered by Cognero.

Page 1


Name:

Class:

Date:

Chapter 08: Graphical User Interrfaces 9. As a rule of thumb, when you are defining a new class of objects, you should look around for a class that already supports some of the structure and behavior of such objects, and then subclass that class to provide the service you need. a. True b. False ANSWER: True

10. By default, a window has an empty title string and is resizable. a. True b. False ANSWER: True

11. GUI-based programs can be configured to respond to various keyboard events and mouse events. a. True b. False ANSWER: True

12. The Tkinter module supports the CMYK color system, but not the RGB color system. a. True b. False ANSWER: False

13. In the RGB system, the value #00ff00 represents the color red. a. True b. False ANSWER: False

14. Window components are laid out in the window's three-dimensional grid. a. True b. False ANSWER: False

15. The values that can be used within the sticky attribute are "T, D, L, R". a. True b. False ANSWER: False

16. The breezypythongui module's IntegerField component is a subclass of the Entry class. a. True b. False ANSWER: True

17. By default, a newly opened window shrink-wraps around its components and is resizable. Copyright Cengage Learning. Powered by Cognero.

Page 2


Name:

Class:

Date:

Chapter 08: Graphical User Interrfaces a. True b. False ANSWER: True

18. The font attribute in tkinter.Label is an object imported from tkinter.font. a. True b. False ANSWER: True

19. The addButton method returns an object of type tkinter.Button. a. True b. False ANSWER: True

20. A button has a state attribute, which can be set to "enabled" or "disabled". a. True b. False ANSWER: False

21. In order to allow a program to respond to a button click, the programmer must set the button's "response" attribute. a. True b. False ANSWER: False

22. An entry field is a box in which the user can position the mouse cursor and enter a number or a single line of text. a. True b. False ANSWER: True

23. The values of an object's instance variables make up its state. a. True b. False ANSWER: True

24. Lists of strings can be displayed in list boxes. a. True b. False ANSWER: True

25. GUI-based programs utilize file dialogs in order to allow the user to browse a computer's file system. a. True Copyright Cengage Learning. Powered by Cognero.

Page 3


Name:

Class:

Date:

Chapter 08: Graphical User Interrfaces b. False ANSWER: True

Multiple Choice 26. A GUI-based program displays a window that contains various components, also known by what specific term? a. widgets b. gadgets c. sprockets d. doodads ANSWER: a

27. In a GUI-based program, what are labels supposed to do? a. They define the title name of the program that is running. b. They are boxes within which a program can accept input. c. They are text elements that describe inputs and outputs. d. They interactive elements in the program that can be used for selections. ANSWER: c

28. Programming that is tied to user-generated actions, such as mouse clicks, is known as what type of programming? a. user-driven programming b. event-driven programming c. access-driven programming d. object-oriented programming ANSWER: b

29. What is the name of the standard GUI module for Python? a. tkinter b. PyQt5 c. breezypythongui d. Kivy ANSWER: a

30. In the breezypythongui module, what class provides the basic functionality for any window, such as the command buttons in the title bar? a. WindowFrame b. ProgFrame c. BreezyFrame d. EasyFrame ANSWER: d Copyright Cengage Learning. Powered by Cognero.

Page 4


Name:

Class:

Date:

Chapter 08: Graphical User Interrfaces 31. When using the EasyFrame class to create a window, what method specifically is used to set up any window components to display in the window? a. __name__ b. __window__ c. __main__ d. __init__ ANSWER: d

32. What happens when you make a new class a subclass of another class? a. The new class inherits the attributes and behaviors defined in the parent class. b. The new class becomes subjugated to the parent class, preventing the override of class values. c. The new class becomes a copy of the ancestor class, and functions under the ancestor class's namespace. d. The ancestor class and the new class both become global in scope. ANSWER: a

33. What is NOT one of the more important attributes of a window? a. The title string. b. The width and height in pixels. c. The resizability of the window. d. The terminal prompt. ANSWER: d

34. Other than specifying key values when performing the method call to EasyFrame, what can you use to change a window's attributes? a. You can overload the class and create an identical class. b. You can utilize the attribute dictionary. c. You can pass a tuple to the class constructor. d. You can use the setDefaults() method. ANSWER: b

35. What EasyFrame method is used to specify if a window is resizable or not? a. setEnableResize() b. chgResize() c. setWindowAttrib() d. modWindowSize() ANSWER: a

36. One of the requirements for a breezypythongui-based Python script you're writing is that you be able to use a slider bar for selecting a value from a range of values. What type of window component do you want? a. EasySlider Copyright Cengage Learning. Powered by Cognero.

Page 5


Name:

Class:

Date:

Chapter 08: Graphical User Interrfaces b. Scale c. SlideRule d. EasyRange ANSWER: b

37. What kind of statement can be used to attempt a graceful recovery from an exception? a. attempt-fail statement b. if-else statement c. try-except statement d. test-succeed statement ANSWER: c

38. What is the "self" parameter utilized for in a class definition block? a. It is used within the class and method definitions to call other methods on the same object, or to access that object's variables or data. b. It is used to define the scope of the class in relevance to the rest of the program. c. It is used to tell the Python virtual machine that the class is locally significant in the particular module or script within which it is defined. d. It is used as a shortcut rather than typing out the module name, parent classes, and subclass to which the class belongs. ANSWER: a

39. How can you associate a keyboard event and an event-handling method with a widget? a. You must name the event-handling method "onPress_". b. You must use the bind method, which expects a string containing a key event. c. You must map a shortcut in the host operating system to run the script with a specific argument. d. You must define the key's event in a YAML-based configuration file. ANSWER: b

40. When passing color values to the tkinter module in hexadecimal, what hex string represents the color red? a. #ff0000 b. #00ff00 c. #0000ff d. #ff00ff ANSWER: a

41. What scenario would be ideal for the use of a prompter box? a. You require a GUI element that restricts a user to a single choice of items out of a group of items. b. You require a GUI element to display an error message upon incorrect input. c. You require a GUI element to prompt for a user's text input. d. You require a GUI element to allow a large amount of text to be entered by the user. Copyright Cengage Learning. Powered by Cognero.

Page 6


Name:

Class:

Date:

Chapter 08: Graphical User Interrfaces ANSWER: c

42. What scenario would be ideal for the use of a check button? a. You require a GUI element that restricts a user to a single choice of items out of a group of items. b. You require a GUI element to display an error message upon incorrect input. c. You require a GUI element to prompt for a user's text input. d. You require a GUI element that can be grouped with other elements that can be selected at the same time. ANSWER: d

43. What class in the breezypythongui module provides a scrollable box for the display and selection of items? a. EasyTextField b. TextArea c. EasyListbox d. EasyIntegerField ANSWER: c

44. In the RGB system, what hexadecimal value represents the color black? a. #000000 b. #ffffff c. #ff00ff d. #00ffff ANSWER: a

45. In GUI terminology, what is the name used to describe a rectangular window component with its own grid that is useful for organizing other window components? a. layout b. superframe c. panel d. combo frame ANSWER: c

46. What argument can be specified to the two file dialog functions in order to specify the available file types that can be used? a. defaultextension b. filetypes c. fileformat d. filedata ANSWER: b

47. What attribute can be used to override the default alignment of a window component? a. align Copyright Cengage Learning. Powered by Cognero.

Page 7


Name:

Class:

Date:

Chapter 08: Graphical User Interrfaces b. sticky c. target d. orientation ANSWER: b

Multiple Response 48. What two items are included in the class header of a class defined in Python? (Choose two.) a. The class name, conventionally capitalized. b. The class arguments. c. The list of one or more parent classes. d. The required parameters. ANSWER: a, c

49. What two keyword arguments can be used to force a horizontal and/or vertical spanning of grid positions? (Choose two.) a. gridspan b. rowspan c. columnspan d. gridlock ANSWER: b, c

50. What are the two functions available in the tkinter.filedialog module used to support file access in a GUI program? a. askopenfileaccess b. askfilesystemaccess c. asksaveasfilename d. askopenfilename ANSWER: c, d

Copyright Cengage Learning. Powered by Cognero.

Page 8


Name:

Class:

Date:

Chapter 08: Queues True / False 1. Queues are linear collections. a. True b. False ANSWER: True

2. Similar to stacks, queues support a FILO protocol. a. True b. False ANSWER: False

3. A checkout line at a grocery store is an example of a queue. a. True b. False ANSWER: True

4. The two fundamental operations supported by queues are pop and insert. a. True b. False ANSWER: False

5. In a priority queue, items waiting in the queue the longest are always popped next. a. True b. False ANSWER: False

6. In computer science, process scheduling can be handled by simple or priority queues. a. True b. False ANSWER: True

7. The list data structure in Python cannot be used to emulate a queue because there is no pop method. a. True b. False ANSWER: False

8. The peek operation on a queue returns the item at the back of the queue without removing it. a. True b. False ANSWER: False

9. Performing a pop operation on an empty queue throws an exception. Copyright Cengage Learning. Powered by Cognero.

Page 1


Name:

Class:

Date:

Chapter 08: Queues a. True b. False ANSWER: True

10. An example of a computer simulation that can use queues is traffic flow on a busy highway. a. True b. False ANSWER: True

11. Simulation programs can use a range of integer values to mimic variability in the simulation. a. True b. False ANSWER: False

12. The most common type of CPU scheduling technique is called last in, first-out. a. True b. False ANSWER: False

13. The ready queue contains processes waiting to use the CPU. a. True b. False ANSWER: True

14. Each process on the ready queue is pushed onto a stack before being given a slice of CPU time. a. True b. False ANSWER: False

15. The structure of a queue lends itself to either an array implementation or a linked implementation. a. True b. False ANSWER: True

16. Both classes, LinkedStack and LinkedQueue, use a singly linked Node class to implement nodes. a. True b. False ANSWER: True

17. The add operation for a queue adds a node at the head of the structure. a. True b. False Copyright Cengage Learning. Powered by Cognero.

Page 2


Name:

Class:

Date:

Chapter 08: Queues ANSWER: False

18. The array implementation of a queue must access items at the logical beginning and the logical end. a. True b. False ANSWER: True

19. In the array implementation of a queue, the pop operation is most efficient if the front of the queue is fixed at index position 0. a. True b. False ANSWER: False

20. By using a circular array implementation, you can simultaneously achieve good running times for both add and pop. a. True b. False ANSWER: True

21. When using a circular array implementation for a queue, during the add operation, the front pointer moves ahead of the rear pointer. a. True b. False ANSWER: False

22. When using a circular array implementation for a queue, when either pointer is about to run off the end of the array, that pointer is reset to -1. a. True b. False ANSWER: False

23. When using a circular array implementation for a queue, you maintain a count of the items in the queue to determine if it is full or empty. a. True b. False ANSWER: True

24. When items are added to a priority queue, they are assigned an order of rank. a. True b. False ANSWER: True

25. When items are removed from a priority queue, items of lower priority are removed before those of higher Copyright Cengage Learning. Powered by Cognero.

Page 3


Name:

Class:

Date:

Chapter 08: Queues priority. a. True b. False ANSWER: False

Multiple Choice 26. What type of collection is a queue? a. linear b. parallel c. random d. geometric ANSWER: a

27. Which protocol is supported by queues? a. last-in first-out b. last-in last-out c. first-in first-out d. first-in last-out ANSWER: c

28. What are the two fundamental operations of a queue? a. insert, push b. insert, pop c. push, add d. add, pop ANSWER: d

29. Which of the following is true about a standard queue? a. the item that has been waiting the shortest is popped next b. the items are popped in LIFO order c. the item that has been waiting the longest is popped next d. removals are done from the rear of the queue ANSWER: c

30. Which example best represents a queue? a. print jobs sent to a printer b. a pickup game of football c. items selected via a random number generator d. people exiting a sporting event ANSWER: a Copyright Cengage Learning. Powered by Cognero.

Page 4


Name:

Class:

Date:

Chapter 08: Queues 31. Which of the following is NOT true of a priority queue? a. higher-priority items are popped before those of lower priority b. items of equal priority are popped in LIFO order c. items of equal priority are popped according to which item arrived first d. higher-priority items can jump ahead of lower-priority items ANSWER: b

32. How would you use a Python list method to remove and return an item at the front of the queue? a. peek(len(queue)-1) b. peek(1) c. pop(len(queue)-1) d. pop(0) ANSWER: d

33. What is the precondition to using the pop method on a queue? a. the queue must not be empty b. the queue must be full c. the queue must not be full d. the queue must first be resized ANSWER: a

34. What is the returned value and the state of the queue after the operation is executed? Current queue state: x a z b q.peek() a. b, x a z b b. x, a z b c. x, x a z b d. b, x a z ANSWER: c

35. Which of the following is NOT an important factor to consider by a manager of a supermarket trying to schedule checkout cashiers? a. the frequency with which new customers arrive b. the number of checkout cashiers available c. the number of items in a customer's shopping cart d. the number of aisles in the supermarket ANSWER: d

36. What is one reason that it is difficult to devise formulas to answer simple questions about a supermarket checkout system? a. the variability of essential factors Copyright Cengage Learning. Powered by Cognero.

Page 5


Name:

Class:

Date:

Chapter 08: Queues b. the regularity in which customers arrive c. because customers always purchase the same number of items d. because the same number of customers are there at all times of the day ANSWER: a

37. In the supermarket simulation, which of the following would be a property of a Cashier object? a. assigns customers to cashiers b. a queue of customer objects c. a variable to track when service is received d. generates new customer objects ANSWER: b

38. What happens to processes on the ready queue in a round-robin CPU scheduling scheme? a. they are pushed and put in the priority queue b. they are popped and allocated memory c. they are pushed to the end of the queue d. they are popped and given a slice of CPU time ANSWER: d

39. Which type of computer activity would likely be assigned to the priority queue? a. a background process that defragments the disk b. sending email c. mouse movement d. a background process that releases unused memory blocks ANSWER: c

40. In a linked implementation of a queue, what does the add operation do? a. adds a node to the head b. adds a node to the tail c. inserts a node in the middle d. creates a new instance of the queue ANSWER: b

41. What is the initial value of the front and rear instance variables in the linked queue? a. -1 b. 0 c. None d. 1 ANSWER: c

42. In the following code for the add method for a linked queue implementation, what is the missing code? Copyright Cengage Learning. Powered by Cognero.

Page 6


Name:

Class:

Date:

Chapter 08: Queues def add(self, newItem): newNode = Node(newItem, None) if self.isEmpty(): self.front = newNode else: self.rear.next = newNode <missing code> self.size += 1 a. self.rear = newNode b. self.rear -= 1 c. self.rear.prev = None d. self.front = self.next ANSWER: a

43. In the following code for the pop method for a linked queue implementation, what is the missing code? def pop(self): oldItem = self.front.data self.front = self.front.next if self.front is None: self.rear = None <missing code> return oldItem a. self.rear -= 1 b. self.front = self.rear c. self.size -= 1 d. self.size += 1 ANSWER: c

44. What is the solution to achieving good performance for both the add and pop methods in the array implementation of a queue? a. using a front pointer that advanced through the array b. using a fixed front pointer to index position 0 c. using an insert function instead of add d. using a circular array implementation ANSWER: d

45. Which of the following is NOT true of a priority queue? a. when items are added, they are assigned an order of rank b. items of higher priority are removed before those of lower priority c. items of higher priority are removed in FIFO order Copyright Cengage Learning. Powered by Cognero.

Page 7


Name:

Class:

Date:

Chapter 08: Queues d. items of equal priority are removed in FIFO order ANSWER: c

46. What can you do if items in a priority queue cannot use the comparison operators? a. use a wrapper class b. remove them from the queue c. remove them in FIFO order d. put them in the back of the queue ANSWER: a

47. In the following code for the __eq__ method for the Comparable class, what is the missing code? def __eq__(self, other): if self is other: return True if type(self) != type(other): <missing code> return self.priority == other.priority

a. return type(other) b. return other c. return False d. return self.priority ANSWER: c

48. What must occur when a wrapped item is accessed with the peek or pop method in a priority queue? a. it must be added to the priority queue b. it must be unwrapped c. it must be compared to the next item d. it must be discarded ANSWER: b

49. In a priority queue, what does the add method do when handling a new item and the new item is greater than or equal to the item at the rear? a. it adds the item to the front b. it puts the item in a wrapper c. it adds the item to the rear d. it increases the size of the queue ANSWER: c

50. In the linked priority queue, what is the time and space analysis for the add method? a. O(n2) b. exponential Copyright Cengage Learning. Powered by Cognero.

Page 8


Name:

Class:

Date:

Chapter 08: Queues c. logarithmic d. O(n) ANSWER: d

Copyright Cengage Learning. Powered by Cognero.

Page 9


Name:

Class:

Date:

Chapter 09: Design with Classes True / False 1. Python programmers typically capitalize their own class names to distinguish them from variable names. a. True b. False ANSWER: True

2. If the parenthesized parent class name is omitted from the class definition, the new class is automatically made a subclass of self. a. True b. False ANSWER: False

3. A method automatically returns the value None when it includes no return statement. a. True b. False ANSWER: True

4. The attributes of an object are represented as instance datum. a. True b. False ANSWER: False

5. The scope of an instance variable is the entire module. a. True b. False ANSWER: False

6. The function call str(s) is equivalent to the method call s.__str__(). a. True b. False ANSWER: True

7. Python has a built-in type for rational numbers called rational. a. True b. False ANSWER: False

8. To reduce a rational number to its lowest terms, you first compute the greatest common divisor (GCD) of the numerator and the denominator, using Euclid's algorithm. a. True b. False ANSWER: True Copyright Cengage Learning. Powered by Cognero.

Page 1


Name:

Class:

Date:

Chapter 09: Design with Classes 9. The code x % y is actually shorthand for the code __mod__(x, y). a. True b. False ANSWER: False

10. To overload an arithmetic operator, you just define a new method using the appropriate method name. a. True b. False ANSWER: True

11. Operator overloading is an example of an abstraction mechanism. a. True b. False ANSWER: True

12. The Python interpreter picks out equality from the other comparisons by looking for an __equals__ method when it encounters the == and != operators. a. True b. False ANSWER: False

13. A class variable is visible to all instances of a class and does not vary from instance to instance. a. True b. False ANSWER: True

14. In general, you should use class variables only for symbolic constants or to maintain data held in common by all objects of a class. a. True b. False ANSWER: True

15. For data that are owned by individual objects, you must use class variables. a. True b. False ANSWER: False

16. Any object can be pickled before it is saved to a file, and then unpickled as it is loaded from a file into a program. a. True b. False ANSWER: True Copyright Cengage Learning. Powered by Cognero.

Page 2


Name:

Class:

Date:

Chapter 09: Design with Classes 17. If the statements in the try clause raise no exceptions, the except clause is skipped and control proceeds to the end of the try-except statement. a. True b. False ANSWER: True

18. Most object-oriented languages require the programmer to master the following techniques: data encapsulation, inheritance, and abstraction. a. True b. False ANSWER: False

19. Inheritance allows several different classes to use the same general method names. a. True b. False ANSWER: False

20. Inheritance allows a class to automatically reuse and extend the code of similar but more general classes. a. True b. False ANSWER: True

21. Although Python is considered an object-oriented language, its syntax does not enforce data encapsulation. a. True b. False ANSWER: True

22. Objects in the natural world and objects in the world of artifacts can be classified using inheritance hierarchies. a. True b. False ANSWER: True

23. It is not usual to bother subclassing unless the two classes share a substantial amount of abstract behavior. a. True b. False ANSWER: True

24. Unlike other object-oriented languages, Python does not support polymorphic methods. a. True b. False ANSWER: False Copyright Cengage Learning. Powered by Cognero.

Page 3


Name:

Class:

Date:

Chapter 09: Design with Classes 25. The str method is a good example of a polymorphic method that appears throughout Python's system of classes. a. True b. False ANSWER: False

Multiple Choice 26. At the top, or root of the class hierarchy is the most abstract class. What is the name of this class? a. root b. object c. parentClass d. Main ANSWER: b

27. What method is known as a class's constructor, because it is run automatically when a user instantiates the class? a. __start__ b. __build__ c. __main__ d. __init__ ANSWER: d

28. What is the __str__ method used for? a. It builds and returns a string representation of an object's state. b. It is used to determine if a class attribute is a string. c. It is used to initiate string values during instantiation. d. It converts a string attribute within a class. ANSWER: a

29. In Python, when does an object reach the end of its life? a. When its timeout value has expired. b. When it has been terminated by the destroy method. c. When it has passed the last statement that uses it. d. When it can no longer be referred to by the program that created it. ANSWER: d

30. What is the process in which the Python virtual machine recycles its storage known as? a. garbage collection b. trash expunging c. data dumping Copyright Cengage Learning. Powered by Cognero.

Page 4


Name:

Class:

Date:

Chapter 09: Design with Classes d. tombstoning ANSWER: a

31. How could you overload the addition operator in the Python language? a. You create a def statement with an asterisk, then specify math.__add__ as the method name. b. You create a new class with the same name as the arithmetic class, and define the __add__ method. c. You declare a new method with the same name, __add__, and define the method. d. You create a Python script named __add__.py, and then define the new method in that script, then import it. ANSWER: c

32. If you wanted to overload the greater than or equal operator, what method name should you define? a. __gte__ b. __gt__ c. __ge__ d. __geq__ ANSWER: c

33. In the context of Python objects, what does the pickling process do? a. It preserves objects by storing them in memory. b. It preserves objects by storing them to a file. c. It preserves objects by creating a sqlite database. d. It preserves objects by adding them to the calling Python script file. ANSWER: b

34. What function do you use to save an object utilizing the pickle module? a. pickle.save b. pickle.jar c. pickle.dump d. pickle.store ANSWER: c

35. You are utilizing the pickle.load function to load objects into a program from a file. However, your program raises an exception as soon as the end of the file is reached. What must you do? a. Use an if-else statement to check if the load function is at the end of the file. b. Use a nested loop to run the pickle.load function line by line. c. Use a try-except statement to catch the exception and continue with the program. d. Use the pickle.len() function to determine the size of the file, then pass the size to the pickle.load() function using the size key. ANSWER: c

36. When the pickle.load function reaches the end of a file, what type of exception is raised? Copyright Cengage Learning. Powered by Cognero.

Page 5


Name:

Class:

Date:

Chapter 09: Design with Classes a. IOError b. EOFError c. DataError d. FileError ANSWER: b

37. What statement is an accurate description of the concept of polymorphism in object-oriented programming? a. Polymorphism is the restricting of the manipulation of an object's state by external users to a set of method calls. b. Polymorphism is allowing a class to automatically reuse and extend the code of a similar but more general class. c. Polymorphism is the use of code that is capable of making changes to itself during the execution process. d. Polymorphism is allowing the several different classes to use the same general method names. ANSWER: d

38. What statement is an accurate description of the concept of inheritance in object-oriented programming? a. Inheritance is the restricting of the manipulation of an object's state by external users to a set of method calls. b. Inheritance is allowing a class to automatically reuse and extend the code of a similar but more general class. c. Inheritance is the use of code that is capable of making changes to itself during the execution process. d. Inheritance is allowing the several different classes to use the same general method names. ANSWER: b

39. What type of programming is defined by the term "imperative programming"? a. Programming such that classes can be defined for objects and reused to define similar objects. b. Programming that involves the use of input and output statements, assignment statements, and control statements for selection and iteration. c. Programming that uses cooperating subprograms to solve problems. d. Programming that views a program as a set of cooperating functions. ANSWER: b

40. What type of programming is defined by the term "procedural programming"? a. Programming utilizing cooperative subprograms to solve problems. b. Programming using input and output statements, assignment statements, and control statements for selection and iteration. c. Programming such that classes can be defined for objects and reused to define similar objects. d. Programming using a set of cooperating functions rather than relying on assignment. ANSWER: a Copyright Cengage Learning. Powered by Cognero.

Page 6


Name:

Class:

Date:

Chapter 09: Design with Classes 41. What type of programming is defined by the term "functional programming"? a. Programming utilizing cooperative subprograms to solve problems. b. Programming using input and output statements, assignment statements, and control statements for selection and iteration. c. Programming such that classes can be defined for objects and reused to define similar objects. d. Programming using a set of cooperating functions rather than relying on assignment. ANSWER: d

42. The attributes of an object are represented as what type of variables? a. state variables b. substance variables c. instance variables d. self variables ANSWER: c

43. What can be used to describe and document the analysis and design of complex software systems? a. Class Diagraming Language b. Programming Structural Language c. Direct Modeling Language d. Unified Modeling Language ANSWER: d

44. What concept within object-oriented programming involves the restriction of the manipulation of an object's state by external users to a set of method calls? a. inheritance b. polymorphism c. data encapsulation d. data modeling ANSWER: c

45. What effect does using the model/view pattern of design have? a. It divides the roles and responsibilities of the system between data management and user interface display. b. It combines the roles and responsibilities of the system between data management and user interface display. c. It involves the user in the defining of how data will be modeled by a program. d. It involves the creation of a model GUI environment, and then involves the creation of views for the user to choose from. ANSWER: a

46. Regarding class variables, what statement is accurate? a. A class variable is only visible to a single instance of a class. Copyright Cengage Learning. Powered by Cognero.

Page 7


Name:

Class:

Date:

Chapter 09: Design with Classes b. A class variable is visible only to methods inside a class. c. A class variable is visible to all instances of a class, but can vary from instance to instance. d. A class variable is visible to all instances of a class, and does not vary from instance to instance. ANSWER: d

47. As a rule of thumb, when should you include an __eq__ method in a class? a. Always, because the comparison for equality is not compatible with classes. b. Whenever a comparison for equality uses criterion other than object identity. c. Only when you need to be able to make a comparison based on object identity. d. Only if you plan to export the class as part of a module. ANSWER: b

Multiple Response 48. What are the two parts of a rational number? (Choose two.) a. dominator b. denominator c. numerator d. terminator ANSWER: b, c

49. What are the two access modes that are used when opening a file for input and output when pickling? (Choose two.) a. r b. rb c. w d. wb ANSWER: b, d

50. What two terms are used for the methods that are used to observe or modify the state of an object, respectively? a. accessors b. ingressors c. modifiers d. mutators ANSWER: a, d

Copyright Cengage Learning. Powered by Cognero.

Page 8


Name:

Class:

Date:

Chapter 09: Lists True / False 1. A list supports manipulation of items at only the head and tail within a linear collection. a. True b. False ANSWER: False

2. Items in a list must be sorted to make sense. a. True b. False ANSWER: False

3. The items in a list are logically contiguous, but need not be physically contiguous in memory. a. True b. False ANSWER: True

4. Linked implementations of lists use physical positions in an array to represent logical order. a. True b. False ANSWER: False

5. List positions are usually counted from 0 to the length of the list plus 1. a. True b. False ANSWER: False

6. There are two broad categories of list operations discussed in most textbooks on data structures: index-based and content-based. a. True b. False ANSWER: True

7. Because a list is ordered linearly, you can refer unambiguously to an item in a list via its relative position from the head of the list. a. True b. False ANSWER: True

8. The head of a list is at index 1 and the tail is at index n which is the length of the list. a. True b. False ANSWER: False Copyright Cengage Learning. Powered by Cognero.

Page 1


Name:

Class:

Date:

Chapter 09: Lists 9. A list is a concrete data structure with a specific and unvarying implementation based on a single block of physical memory. a. True b. False ANSWER: False

10. The list method remove(item) is an example of a content-based operation. a. True b. False ANSWER: True

11. Unlike a simple iterator, a list iterator supports movement to previous positions, directly to the first position, and directly to the last position. a. True b. False ANSWER: True

12. Initially, when a list iterator is opened on a non-empty list, the cursor's position is immediately after the first item in the list. a. True b. False ANSWER: False

13. A traversal with a list iterator begins by moving the cursor to the first position or to the last position. a. True b. False ANSWER: True

14. The object heap is an area of the disk drive from which the Python virtual machine allocates segments of various sizes for all new data objects. a. True b. False ANSWER: False

15. A disk's surface is divided into concentric tracks, and each track is further subdivided into sectors. a. True b. False ANSWER: True

16. In the array implementation of a list, the index-based operation __getitem__ uses the subscript operator on the array variable. a. True Copyright Cengage Learning. Powered by Cognero.

Page 2


Name:

Class:

Date:

Chapter 09: Lists b. False ANSWER: True

17. For a linked implementation of a list, a singly linked structure allows movement to the next node or the previous node. a. True b. False ANSWER: False

18. The sentinel node points to the first data node and the last data node. a. True b. False ANSWER: True

19. The basic building block of a doubly linked structure is a node with two pointers: head, which points left; and tail, which points right. a. True b. False ANSWER: False

20. The __init__ method of a doubly linked list creates a node with no data. a. True b. False ANSWER: True

21. A list iterator is an object attached to a list that provides positional operations on that list. a. True b. False ANSWER: True

22. In the implementation of the lister iterator on a doubly linked list, the method hasNext returns False if the cursor is less than the backing store's length. a. True b. False ANSWER: False

23. A Lisp list is a recursive data structure. a. True b. False ANSWER: True

24. Recursive list processing became one of the building blocks of a movement in software development called abstract programming. Copyright Cengage Learning. Powered by Cognero.

Page 3


Name:

Class:

Date:

Chapter 09: Lists a. True b. False ANSWER: False

25. The index-based function get returns the ith element of a given list. a. True b. False ANSWER: True

Multiple Choice 26. Which of the following is NOT an example of a list? a. a recipe b. a jar of marbles c. words on a document d. a file on a disk ANSWER: b

27. Which of the following is true about lists? a. items must be sorted b. items must be physically contiguous c. the order of items is unimportant d. items are logically contiguous ANSWER: d

28. What is each numeric position in a list called? a. index b. pointer c. tail d. vector ANSWER: a

29. What is true about how lists are indexed? a. indices increase in both movement directions b. indices decrease to the left and increase to the right c. indices decrease in both movement directions d. indices decrease to the right and increase to the left ANSWER: b

30. Which of the following is NOT one of the three broad categories of list operations discussed in Chapter 9? a. index-based b. content-based Copyright Cengage Learning. Powered by Cognero.

Page 4


Name:

Class:

Date:

Chapter 09: Lists c. position-based d. hash-based ANSWER: d

31. Why can you refer to an item in a list via its relative position from the head of the list using an index? a. because it has a circular structure b. because it uses round-robin c. because it is ordered linearly d. because it's arranged in a hierarchy ANSWER: c

32. What are the values of a list index at the head and tail of the list, respectively? a. 0, n-1 b. 1, n c. 0, n d. n-1, 1 ANSWER: a

33. What is the typical argument to a content-based list operation? a. an index b. an item c. a list instance d. an array ANSWER: b

34. How does position-based operations allow the programmer to navigate through a list? a. by incrementing the head pointer b. by decrementing the tail pointer c. by moving the cursor d. by changing the backing store ANSWER: c

35. How do a list iterator and a for loop differ? a. a list iterator allows movement directly to the last position b. a for loop allows movement directly to the first position c. a for loop allows movement to previous positions d. a list iterator only allows sequential movement through the list ANSWER: a

36. Where is the cursor positioned when a list iterator is opened on a non-empty list? a. at the position of the length of the list minus 1 Copyright Cengage Learning. Powered by Cognero.

Page 5


Name:

Class:

Date:

Chapter 09: Lists b. immediately after the first item c. it is undefined d. immediately before the first item ANSWER: d

37. Which of the following list operations is a mutator that works at the currently established position in the list iterator? a. previous b. first c. remove d. hasPrevious ANSWER: c

38. If a list contains the items x y z and the cursor is currently undefined, what happens when hasNext() is executed? a. a value of True is returned b. a value of False is returned c. a value of False is returned and the cursor is positioned before the first item d. a value of True is returned and the cursor is positioned after the last item ANSWER: b

39. Which of the following is an area of memory from which the Python virtual machine allocates segments of various sizes for all new data objects. a. call stack b. virtual memory c. object heap d. memory partition ANSWER: c

40. With respect to memory, what happens when an object is no longer needed? a. the garbage collector returns the object's space to the free list b. the disk block is marked as unused c. the size of the array holding the object is reduced by 1 d. the data block is marked as deleted and is unavailable to other objects ANSWER: a

41. Which of the following is NOT true about a file system's directory? a. it occupies the first few tracks on the disk b. it contains an entry for each file c. each file entry holds the address of the sector containing file data d. the directory is organized as a linear structure Copyright Cengage Learning. Powered by Cognero.

Page 6


Name:

Class:

Date:

Chapter 09: Lists ANSWER: d

42. In the following code for the __iter__ method in the ArrayList class, what is the missing code? def __iter__(self): cursor = 0 while cursor < len(self): yield self.items[cursor] <missing code> a. self.items[cursor] = self.item[cursor-1] b. cursor += 1 c. cursor -= 1 d. self.items[cursor+1] = self.item[cursor] ANSWER: b

43. Which structure is the ideal one to support a list iterator? a. array b. circular array c. doubly linked d. singly linked ANSWER: c

44. What is the extra node needed to easily manipulate a doubly linked structure? a. mid b. next c. tail d. sentinel ANSWER: d

45. Which of the following is NOT a type of precondition when implementing a list iterator? a. the next operation cannot be run if hasNext returns False b. consecutive mutator methods are required c. a next operation must be run before each mutation d. mutations cannot be run on the list itself ANSWER: b

46. In the __init__ method for the ArrayListIterator class, what is the missing code? def __init__(self, backingStore): self.backingStore = backingStore self.modCount = backingStore.getModCount() <missing code> Copyright Cengage Learning. Powered by Cognero.

Page 7


Name:

Class:

Date:

Chapter 09: Lists a. self.first() b. self.last() c. self.next() d. self.previous() ANSWER: a

47. When the first method is run on the list iterator, what happens? a. the cursor is reset to 0 b. the list is cleared c. the cursor is set to -1 d. the list is instantiated ANSWER: a

48. In what type of programming did recursive list processing become an important building block? a. procedural programming b. object-oriented programming c. sequential programming d. functional programming ANSWER: d

49. What does the rest function do on a Lisp-like list? a. returns the list cursor to the head position b. returns all the data items in the list c. returns a list of items after the first one d. returns the list cursor to its previous position ANSWER: c

50. What is the missing code in the contains method for a Lisp-like list? def contains(item, lyst): if isEmpty(lyst): return False elif item == first(lyst): <missing code> else: return contains(item, rest(lyst)) a. return True b. return contains(item-1) c. return False d. return first(lyst) ANSWER: a Copyright Cengage Learning. Powered by Cognero.

Page 8


Name:

Class:

Date:

Chapter 09: Lists

Copyright Cengage Learning. Powered by Cognero.

Page 9


Name:

Class:

Date:

Chapter 10: Multithreading, Networks, and Client/Server Programming True / False 1. Time-sharing systems are still in widespread use in the form of Web servers, e-mail servers, print servers, and other kinds of servers on networked systems. a. True b. False ANSWER: True

2. The late 1960s and early 1970s saw the rise of networked systems. a. True b. False ANSWER: False

3. Few modern computers use threads to represent processes. a. True b. False ANSWER: False

4. In Python, a thread is an object like any other in that it can hold data, be run with methods, be stored in data structures, and be passed as parameters to methods. a. True b. False ANSWER: True

5. The process of saving or restoring a thread's state is called a scheduling switch. a. True b. False ANSWER: False

6. When a thread's run method has executed its last instruction, the thread dies as a process but continues to exist as an object. a. True b. False ANSWER: True

7. A thread object can die if it raises an exception that is not handled. a. True b. False ANSWER: True

8. The most common way to create a thread is to define a class that extends the class threading.Runnable. a. True b. False Copyright Cengage Learning. Powered by Cognero.

Page 1


Name:

Class:

Date:

Chapter 10: Multithreading, Networks, and Client/Server Programming ANSWER: False

9. A thread's block method is invoked automatically by start. a. True b. False ANSWER: False

10. Because an IDLE itself runs in a thread, it is not generally a good idea to test a multithreaded application in that environment. a. True b. False ANSWER: True

11. Threads cannot share data between them. a. True b. False ANSWER: False

12. Producer/consumer threads can suffer from synchronization problems. a. True b. False ANSWER: True

13. The notify() method of the Condition class lets all threads waiting on the lock know that it's available. a. True b. False ANSWER: False

14. The release() method of the Condition class relinquishes the lock, leaving it to be acquired by others. a. True b. False ANSWER: True

15. To properly handle functions that may raise exceptions, you can embed these function calls in a try-catch statement. a. True b. False ANSWER: False

16. When developing a network application, the programmer can first try it out on a local host—that is, on a standalone computer that may or may not be connected to the Internet. a. True b. False Copyright Cengage Learning. Powered by Cognero.

Page 2


Name:

Class:

Date:

Chapter 10: Multithreading, Networks, and Client/Server Programming ANSWER: True

17. Clients connect to servers via objects known as channels. a. True b. False ANSWER: False

18. A port serves as a channel through which several clients can exchange data with the same server or with different servers. a. True b. False ANSWER: True

19. Ports are usually specified by IP addresses. a. True b. False ANSWER: False

20. You cannot create and open several sockets on the same port of a host computer. a. True b. False ANSWER: False

21. A socket resembles a file object, in that the programmer opens it, receives data from it, and closes it when finished. a. True b. False ANSWER: True

22. A socket is bound to an address (host, port) by running its bind method. a. True b. False ANSWER: True

23. The Python function time.currenttime returns a string representing the day/time. a. True b. False ANSWER: False

24. A server can send data to a client using a socket's put method. a. True b. False ANSWER: False Copyright Cengage Learning. Powered by Cognero.

Page 3


Name:

Class:

Date:

Chapter 10: Multithreading, Networks, and Client/Server Programming 25. When working with sockets, it is important to synchronize the sending and the receiving of messages between the client and the server. a. True b. False ANSWER: True

Multiple Choice 26. The procedure by which a process's state is saved before being swapped out of the CPU, then is restored to the state when the process is about to execute, is known as what term? a. processing handling b. context switching c. state cycling d. priority slicing ANSWER: b

27. The discipline of building hardware architectures, operating systems, and specialized algorithms for running a program on a cluster of processors is known by what term? a. multi-computing b. resource sharing c. process distributing d. parallel computing ANSWER: d

28. In order to execute code in a thread as a process, what must be done? a. The thread's class must implement a run method. b. The thread's class must implement an exec method. c. The thread must include the "process" class as a parent. d. The thread must be told to execute using the exec=yes key. ANSWER: a

29. After the creation of a thread, what makes a thread "ready"? a. The calling of the start method. b. The calling of the ready method. c. The instantiation of the thread, followed by the use of the "begin" function. d. The creation of the thread itself places it in a "ready" state. ANSWER: a

30. A thread that is waiting for user input is most likely in what state? a. A time-out state. b. A sleeping state. Copyright Cengage Learning. Powered by Cognero.

Page 4


Name:

Class:

Date:

Chapter 10: Multithreading, Networks, and Client/Server Programming c. A blocking state. d. A wait state. ANSWER: c

31. In the event that a thread loses access to the CPU, such as via a time-out, sleep, block, or wait state, what happens when the thread is ready to resume execution? a. The thread is moved to the front of the ready-queue. b. The thread is moved to the rear of the ready-queue. c. The thread is given a chance to execute as soon as the running process enters a wait state. d. The thread is given a random interval to check if it is the thread's turn to execute, or if the processor is available. ANSWER: b

32. What thread method can be used to test if the thread is dead or not? a. isDead() b. isAlive() c. isActive() d. isQueued() ANSWER: b

33. What kind of problem occurs in a producer/consumer relationship in which the consumer attempts to access data that are not there, or accesses the same data more than once? a. procedural problems b. communication problems c. coordination problems d. synchronization problems ANSWER: d

34. What is the purpose of a condition object in a threaded application? a. The condition object functions as a lock on a resource. b. The condition object provides a similar function to if-else in threads. c. The condition object provides a try-except function in threads. d. The condition object functions as a timer for the ready-queue. ANSWER: a

35. What does the socket module function gethostname() do? a. It returns the IP number of the computer whose IP name is passed to the function. b. It returns the IP address of the host computer running the Python interpreter. c. It returns the IP name of the host computer running the Python interpreter. d. It returns the name of the IP address passed to it. ANSWER: c Copyright Cengage Learning. Powered by Cognero.

Page 5


Name:

Class:

Date:

Chapter 10: Multithreading, Networks, and Client/Server Programming 36. Using the "gethostbyname('localhost')" function of the socket module will return what IP address? a. 10.0.0.1 b. 127.0.0.1 c. 169.254.1.1 d. 192.168.1.1 ANSWER: b

37. What statement accurately describes the role of a socket? a. A socket is an object that serves as a communication link between a single server process and a single client process. b. A socket is a named pipe that is used to pass communications one way to a remote location. c. A socket is a unique computer resource that provides access to hardware. d. A socket is a communications channel within the TCP/IP stack that communicates only with the localhost. ANSWER: a

38. You are designing a script that needs to get the current date and time as a string. What function can you use for this? a. time.ptime b. time.ctime c. time.today d. time.now ANSWER: b

39. What is the socket bind method used for? a. It binds the socket to an address. b. It binds the socket to a port. c. It binds the socket to a listening pipe. d. It binds the socket to the localhost. ANSWER: a

40. In order to utilize the socket module's recv method, what must you pass as an argument? a. The source IP address the information will be coming from. b. The destination port you will receive information on. c. The maximum size in bytes of the data to be read from the socket. d. The address family used by the network socket. ANSWER: c

41. After using the socket.recv method, what type of data is returned? a. An object of type bytes. b. A list object containing lines of data separated by carriage returns. c. A string containing all data that was received. Copyright Cengage Learning. Powered by Cognero.

Page 6


Name:

Class:

Date:

Chapter 10: Multithreading, Networks, and Client/Server Programming d. A Boolean value indicating whether the receive was successful. ANSWER: a

42. You have just captured data using the socket.recv method into a variable named client_data. What can you use to convert client_data to a string? a. codecs.decode(client_data, "string") b. socket.decode(client_data, type="string") c. codecs.decode(client_data, 'ascii') d. network.data(client_data, %s) ANSWER: c

43. Assuming that a socket has been created with a name of server, what effect does the server.listen(10) have? a. The socket will listen for a maximum of 10 minutes, and then close. b. The socket will allow a maximum of 10 connections, then close. c. The socket will accept a maximum of 10 concurrent connections. d. The socket will listen until the integer "10" is seen in the data stream. ANSWER: c

44. When a client connects to a server, what does the socket accept method return? a. A string containing the client's IP address. b. A list containing the client's IP address and port. c. A tuple containing the client's socket and its address information. d. An object of type bytes containing the client's IP address. ANSWER: c

45. A program starting another program or a new process is known by what term? a. spawning b. forking c. cloning d. generating ANSWER: b

46. Which of the following is an example of time slicing? a. A running process is automatically moved to the rear of the ready queue after a few milliseconds of run time. b. A process is put to sleep as a result of the sleep method, and moves to the rear of the ready queue. c. A process is waiting for input from a user and is moved to the rear of the ready queue. d. A process is waiting for a condition to become true, and is moved to the rear of the ready queue. ANSWER: a

Multiple Response Copyright Cengage Learning. Powered by Cognero.

Page 7


Name:

Class:

Date:

Chapter 10: Multithreading, Networks, and Client/Server Programming 47. What two thread condition methods can be used to release a lock? (Choose two.) a. notify() b. release() c. notifyAll() d. wait() ANSWER: b, d

48. What two Python data structures are already thread-safe, because they provide automatic support for synchronizing multiple readers and writers? (Choose two.) a. tuples b. strings c. lists d. dictionaries ANSWER: c, d

49. What two items must be passed in a tuple to the socket module's connect method in order to connect a socket? (Choose two.) a. The target host's IP address. b. The protocol type that will be used. c. The operating system used by the host. d. A valid port number. ANSWER: a, d

50. What two items must be given to the socket function in order to create a socket object? a. The IP address to be used. b. The socket family that will be used. c. The socket type that will be used. d. The socket port that will be used. ANSWER: b, c

Copyright Cengage Learning. Powered by Cognero.

Page 8


Name:

Class:

Date:

Chapter 10: Trees True / False 1. With trees, each item, including the first and last, have a distinct successor. a. True b. False ANSWER: False

2. In a tree, the root item has no parent item. a. True b. False ANSWER: True

3. In a tree, an interior node is a node that has no children. a. True b. False ANSWER: False

4. The height of an empty tree is -1. a. True b. False ANSWER: True

5. A parse tree describes the syntactic structure of a sentence in terms of its component parts. a. True b. False ANSWER: True

6. A file system is similar to a binary search tree. a. True b. False ANSWER: False

7. An access, an insertion, or a removal of a node in a vine-like tree with N nodes and a height of N - 1 would be linear in the worst case. a. True b. False ANSWER: True

8. The maximum amount of work that it takes to access a given node in a full binary tree is O(N). a. True b. False ANSWER: False Copyright Cengage Learning. Powered by Cognero.

Page 1


Name:

Class:

Date:

Chapter 10: Trees 9. The inorder traversal algorithm visits a tree's root node and then traverses the left subtree and the right subtree in a similar manner. a. True b. False ANSWER: False

10. The preorder traversal algorithm traverses the left subtree, visits the root node, and traverses the right subtree. a. True b. False ANSWER: False

11. A min-heap is a binary tree in which each node is less than or equal to both of its children. a. True b. False ANSWER: True

12. The heap sort algorithm builds a heap from a set of data and then repeatedly removes the leaf item and adds it to the end of a list. a. True b. False ANSWER: False

13. An expression tree is never empty. a. True b. False ANSWER: True

14. In the replace method for a binary search tree interface, None is returned if the first argument cannot be found. a. True b. False ANSWER: True

15. You should use a postorder iteration method for the tree's __iter__ method to enable the user to create a clone of the tree with the same shape as the original. a. True b. False ANSWER: False

16. Two trees are considered equal if they contain the same items in the same positions. a. True b. False Copyright Cengage Learning. Powered by Cognero.

Page 2


Name:

Class:

Date:

Chapter 10: Trees ANSWER: True

17. When a linked binary search tree is instantiated, the self.root variable is set to self. a. True b. False ANSWER: False

18. Because the recursive search algorithm doesn't require a parameter for a tree node, you can define it as a top-level method. a. True b. False ANSWER: False

19. The level order traversal guides the visits to items from left to right through the levels of the tree, much like reading lines of text in a document. a. True b. False ANSWER: True

20. A grammar in a programming language consists of a vocabulary, syntax rules, and a list of operators. a. True b. False ANSWER: False

21. Syntax rules specify how sentences in the language should be interpreted. a. True b. False ANSWER: False

22. One of the types of symbols used by an EBNF is metasymbols. a. True b. False ANSWER: True

23. Array-based binary trees are the easiest to define and implement. a. True b. False ANSWER: False

24. The peek method in a heap implementation returns the bottom most item in the heap. a. True b. False ANSWER: False Copyright Cengage Learning. Powered by Cognero.

Page 3


Name:

Class:

Date:

Chapter 10: Trees 25. The number of comparisons required for a removal in an array-based heap is at most log2n, so the pop operation is O(logn). a. True b. False ANSWER: True

Multiple Choice 26. In a tree, which of the following is true? a. all items have a distinct predecessor and successor b. each item can have multiple children c. each item can have multiple parents d. the root has exactly one parent ANSWER: b

27. Which of the following is the topmost node in a tree and does not have a parent? a. root b. child c. leaf d. interior node ANSWER: a

28. Which of the following is described as a node's parent, its parent's parent, and so on up to the root? a. descendant b. path c. depth d. ancestor ANSWER: d

29. Which of the following is true about a binary tree? a. each node has at most two children b. each node has only one child c. child nodes can have multiple parents d. the root node must have only one child ANSWER: a

30. What kind of tree would be useful in analyzing the syntax of a sentence? a. binary search tree b. sorting tree c. parse tree d. linear tree Copyright Cengage Learning. Powered by Cognero.

Page 4


Name:

Class:

Date:

Chapter 10: Trees ANSWER: c

31. Which is true about binary search trees? a. they cannot support logarithmic insertions b. they can support logarithmic searches c. they don't work well for sorted collections d. each node in the right subtree of a given node is less than that node ANSWER: b

32. What is the number of nodes in a full binary tree with a height of 4? a. 23 b. 19 c. 31 d. 47 ANSWER: c

33. What is the formula for determining the number of nodes in a full binary tree where H is the height of the tree? a. 2H - 1 + 1 b. 2H + 1 c. 2H + 1 d. 2H + 1 - 1 ANSWER: d

34. What is the height of a full binary tree with 63 nodes? a. 5 b. 8 c. 6 d. 7 ANSWER: a

35. Which type of binary tree traversal traverses the left subtree, visits, the root node, and traverses the right subtree? a. postorder traversal b. inorder traversal c. preorder traversal d. unordered traversal ANSWER: b

36. Which type of binary tree traversal visits the tree's root node, the left subtree and then the right subtree? a. postorder traversal Copyright Cengage Learning. Powered by Cognero.

Page 5


Name:

Class:

Date:

Chapter 10: Trees b. inorder traversal c. preorder traversal d. unordered traversal ANSWER: c

37. Which type of binary tree traversal traverses the left subtree, traverses the right subtree, and then visits the root node? a. postorder traversal b. inorder traversal c. preorder traversal d. unordered traversal ANSWER: a

38. Which of the following is NOT a common application for a binary tree? a. heap b. expression tree c. binary search tree d. stack ANSWER: d

39. Which of the following is true about a max-heap? a. each node is less than or equal to its children b. the largest nodes are nearer to the root c. the largest items are in the leaves d. the smallest item is in the root node ANSWER: b

40. When the shape of a BST approaches that of a perfectly balanced binary tree, what is the worst case performance characteristic of searches and insertions? a. O(logn) b. On c. O(n) d. O(log2n) ANSWER: a

41. What operator causes the __contains__ method to run in the binary search tree implementation? a. = b. is c. + d. in ANSWER: d Copyright Cengage Learning. Powered by Cognero.

Page 6


Name:

Class:

Date:

Chapter 10: Trees 42. What type of traversal occurs in the binary search tree's __iter__ method? a. sequential b. postorder c. preorder d. inorder ANSWER: c

43. In the following code for the __init__ method for the linked binary search tree, what is the missing code? def __init__(self, sourceCollection = None): <missing code> AbstractCollection.__init__(sourceCollection) a. self.root = sourceCollection b. self.root = None c. sourceCollection.__init__(AbstractCollection) d. self.leaf = root ANSWER: b

44. In the following code for the find method, what is the missing code? def find(self, item): def recurse(node): if node is None: return None elif item == node.data: <missing code> elif item < node.data: return recurse(node.left) else: return recurse(node.right) return recurse(self.root) a. return node.data b. return self.data c. return recurse(node.root) d. return node.root ANSWER: a

45. In the code for the inorder method for a binary search tree, what is the missing code? def inorder(self): lyst = list() def recurse(node): if node != None: Copyright Cengage Learning. Powered by Cognero.

Page 7


Name:

Class:

Date:

Chapter 10: Trees <missing code> lyst.append(node.data) recurse(node.right) recurse(self.root) return iter(lyst) a. recurse(node.root) b. return(node.data) c. recurse(node.left) d. return iter(self.root) ANSWER: c

46. Which traversal type guides visits to items in the tree from left to right through the levels of the tree? a. level order b. inorder c. preorder d. postorder ANSWER: a

47. Which of the following is not a part of a grammar? a. vocabulary b. semantic rules c. syntax rules d. method rules ANSWER: d

48. Which symbol type is NOT found in an EBNF? a. terminal symbols b. metasymbols c. hypersymbols d. nonterminal symbols ANSWER: c

49. Which of the following carries out the actions specified by a sentence? a. interpreter b. parser c. recognizer d. compiler ANSWER: a

50. In the code for the add method in the implementation of a heap, what is the missing code? def add(self, item): Copyright Cengage Learning. Powered by Cognero.

Page 8


Name:

Class:

Date:

Chapter 10: Trees self.size += 1 self.heap.append(item) curPos = len(self.heap) - 1 while curPos > 0: parent = (curPos - 1) // 2 parentItem = self.heap[parent] if parentItem <= item: <missing code> else: self.heap[curPos] = self.heap[parent] self.heap[parent] = item curPos = parent a. curPos += 1 b. break c. self.heap[curPos] = item d. parent = curpos ANSWER: b

Copyright Cengage Learning. Powered by Cognero.

Page 9


Name:

Class:

Date:

Chapter 11: Searching, Sorting, and Complexity Analysis True / False 1. Algorithms describe processes that run on real computers with finite resources. a. True b. False ANSWER: True

2. The time() function of the time module can be used to track the running time of a program. a. True b. False ANSWER: True

3. An algorithm coded in Python usually runs slightly faster than the same algorithm coded in C. a. True b. False ANSWER: False

4. When you count instructions to estimate the efficiency of an algorithm, you count the instructions in the executable machine language program. a. True b. False ANSWER: False

5. Some algorithms require more memory as the problem size gets larger. a. True b. False ANSWER: True

6. Algorithms with linear behavior do less work than algorithms with quadratic behavior for most problem sizes n. a. True b. False ANSWER: True

7. As the problem size gets larger, the performance of an algorithm with the higher order of complexity becomes worse more quickly. a. True b. False ANSWER: True

8. Logarithmic complexity is better than constant but worse than linear complexity. a. True b. False Copyright Cengage Learning. Powered by Cognero.

Page 1


Name:

Class:

Date:

Chapter 11: Searching, Sorting, and Complexity Analysis ANSWER: False

9. An order of complexity that is worse than polynomial is called quadratic. a. True b. False ANSWER: False

10. Whenever the amount of work of an algorithm is expressed as a polynomial, we focus on one term as dominant. a. True b. False ANSWER: True

11. In asymptotic analysis, the value of a polynomial asymptotically approaches or approximates the value of its largest term as n becomes very large. a. True b. False ANSWER: True

12. The constant of proportionality involves the terms and coefficients that are usually ignored during big-O analysis. a. True b. False ANSWER: True

13. When analyzing an algorithm, one must be careful to determine that any instructions do not hide a loop that depends on a variable problem size. a. True b. False ANSWER: True

14. Python's minimum function returns the minimum or smallest item in a list. a. True b. False ANSWER: False

15. Python's is operator is implemented as a method named __contains__ in the list class. a. True b. False ANSWER: False

16. Sequential search is also called polynomial search. a. True Copyright Cengage Learning. Powered by Cognero.

Page 2


Name:

Class:

Date:

Chapter 11: Searching, Sorting, and Complexity Analysis b. False ANSWER: False

17. The performance of some algorithms depends on the placement of the data that are processed. a. True b. False ANSWER: True

18. In general, we worry more about average and best-case performances than about worst-case performances. a. True b. False ANSWER: False

19. A binary search is necessary for data that are not arranged in any particular order. a. True b. False ANSWER: False

20. Binary search is less efficient than linear search. a. True b. False ANSWER: False

21. The first two numbers in the Fibonacci sequence are 1 and 2. a. True b. False ANSWER: False

22. O(n log n) running times are better than O(n^2) running times. a. True b. False ANSWER: True

23. Selection sort starts at the beginning of the list and compares pairs of data items as it moves down to the end. a. True b. False ANSWER: False

24. Bubble sort's worst-case behavior for exchanges is greater than linear. a. True b. False ANSWER: True Copyright Cengage Learning. Powered by Cognero.

Page 3


Name:

Class:

Date:

Chapter 11: Searching, Sorting, and Complexity Analysis 25. Although recursive Fibonacci is elegant in its design, there is a less beautiful but much faster version that uses a loop to run in linear time. a. True b. False ANSWER: True

Multiple Choice 26. Of the techniques that can be used to determine the efficiency of an algorithm, which is based on a calculated average of run time? a. benchmarking b. instruction counting c. set analyzing d. process profiling ANSWER: a

27. Which of the following is an example of a linear algorithm? a. An algorithm in which work grows exponentially in relation to the size of the problem. b. An algorithm in which work grows as a power of three each time the problem size increases. c. An algorithm in which work grows in direct proportion to the size of the problem. d. An algorithm in which work grows at a rate of n^k, where k is a constant greater than 1. ANSWER: c

28. Which of the following is an example of a quadratic algorithm? a. An algorithm in which work grows as a square of the problem size. b. An algorithm in which work grows as a power of three each time the problem size increases. c. An algorithm in which work grows in direct proportion to the size of the problem. d. An algorithm in which work grows at a rate of n^k, where k is a constant greater than 1. ANSWER: a

29. In terms of order of complexity, what is the best kind of performance to have? a. linear b. quadratic c. constant d. logarithmic ANSWER: c

30. What function can you use to record the start and end times of a block of code, and then use the difference between the resulting values to determine the elapsed time in seconds? a. time.ctime() b. time.time() Copyright Cengage Learning. Powered by Cognero.

Page 4


Name:

Class:

Date:

Chapter 11: Searching, Sorting, and Complexity Analysis c. time.count() d. time.epoch() ANSWER: b

31. What is the dominant term when evaluating the amount of work in an algorithm? a. When expressed as time vs. work performed, the dominant term is the area where the least amount of time is expended. b. When expressed as a matrix of related problems, the problem that is most significant becomes the dominant term. c. When expressed as a quadratic function, the dominant term is the statement in the algorithm where the fastest work is performed. d. When expressed as a polynomial, the dominant term of an algorithm is the area where the most work is performed. ANSWER: d

32. What does the "O" in big-O notation stand for? a. The "O" stands for "on the order of," which is a reference to the order of complexity of the work of the algorithm. b. The "O" stands for "Organization of," which is a reference to the organization of complex functions at work in the algorithm. c. The "O" stands for "on the ontology of," which is a reference to the structure of the algorithm itself. d. The "O" stands for "on the openness of," which is a reference to the ability to discern from code how the algorithm functions. ANSWER: a

33. Python's in operator is implemented as a method by what name in the list class? a. __in__ b. __contains__ c. __present__ d. __within__ ANSWER: b

34. What statement accurately describes the strategy utilized by the bubble sort algorithm? a. The bubble sort algorithm repeatedly swaps elements that are out of order in a list until they are completely sorted. b. The bubble sort algorithm repeatedly swaps the smallest element in an unsorted portion of a list with an element at the start of the unsorted portion. c. The bubble sort algorithm repeatedly inserts the i-th element into its proper place in the first i items in the list. d. The bubble sort algorithm partitions a list around a pivot item and sorts the resulting sublists. ANSWER: a

35. What statement accurately describes the strategy utilized by the selection sort algorithm? Copyright Cengage Learning. Powered by Cognero.

Page 5


Name:

Class:

Date:

Chapter 11: Searching, Sorting, and Complexity Analysis a. The selection sort algorithm repeatedly swaps elements that are out of order in a list until they are completely sorted. b. The selection sort algorithm repeatedly swaps the smallest element in an unsorted portion of a list with an element at the start of the unsorted portion. c. The selection sort algorithm repeatedly inserts the i-th element into its proper place in the first i items in the list. d. The selection sort algorithm partitions a list around a pivot item and sorts the resulting sublists. ANSWER: b

36. What statement accurately describes the strategy utilized by the insertion sort algorithm? a. The insertion sort algorithm repeatedly swaps elements that are out of order in a list until they are completely sorted. b. The insertion sort algorithm repeatedly swaps the smallest element in an unsorted portion of a list with an element at the start of the unsorted portion. c. The insertion sort algorithm repeatedly inserts the i-th element into its proper place in the first i items in the list. d. The insertion sort algorithm partitions a list around a pivot item and sorts the resulting sublists. ANSWER: c

37. What statement accurately describes the strategy utilized by the quicksort algorithm? a. The quicksort algorithm repeatedly swaps elements that are out of order in a list until they are completely sorted. b. The quicksort algorithm repeatedly swaps the smallest element in an unsorted portion of a list with an element at the start of the unsorted portion. c. The quicksort algorithm repeatedly inserts the i-th element into its proper place in the first i items in the list. d. The quicksort algorithm partitions a list around a pivot item and sorts the resulting sublists. ANSWER: d

38. Of the numerous sorting algorithms, what algorithm employs a recursive, divide-and-conquer strategy that breaks a list in two at the middle point and recursively sorts the lists? a. quicksort b. insertion sort c. bubble sort d. merge sort ANSWER: d

39. What is NOT one of the three Python functions that are associated with the merge sort algorithm? a. mergeSort b. mergeSortHelper c. merge d. mergeSplit Copyright Cengage Learning. Powered by Cognero.

Page 6


Name:

Class:

Date:

Chapter 11: Searching, Sorting, and Complexity Analysis ANSWER: d

40. The insertion, bubble, and selection sort algorithms are all examples of algorithms that have what big-O notation run times? a. O(n log n) b. O(n^n) c. O(n**2) d. O(n**3) ANSWER: c

41. What type of analysis involves analyzing a polynomial wherein its value approaches or approximates that of its dominant term, as the size of the problem gets very large? a. quadratic analysis b. logarithmic analysis c. asymptotic analysis d. asynchronous analysis ANSWER: c

42. How does the constant of proportionality for an algorithm differ from focusing on the dominant term in bigO analysis? a. The constant of proportionality involves terms and coefficients that are usually ignored during big-O analysis. b. The constant of proportionality attempts to calculate the computational cost of N = NP problems. c. The constant of proportionality focuses on the dominant term's effects on other parts of the algorithm, rather than focusing solely on the dominant term. d. The constant of proportionality involves the creation of a benchmark for items that contribute to the dominant term. ANSWER: a

43. What programming technique involves saving intermediate values when they are computed so they can be reused when they are needed again? a. memoization b. prioritization c. amortization d. memorization ANSWER: a

44. What would the constant k value in an O(k^n) algorithm be for the Fibonacci sequence? a. 0.83 b. 1.63 c. 3.14 d. 5.24 Copyright Cengage Learning. Powered by Cognero.

Page 7


Name:

Class:

Date:

Chapter 11: Searching, Sorting, and Complexity Analysis ANSWER: b

45. When choosing an algorithm, faster run times can often be achieved at the expense of what other resource? a. hard drive space b. processing power c. active memory d. interrupt requests ANSWER: c

46. The process of determining the running time and memory cost of an algorithm by reading the code and creating a mathematical formula expressing this cost is known by what term? a. pattern analysis b. complexity analysis c. cost analysis d. micro analysis ANSWER: b

47. What statement regarding the development of fast algorithms is accurate? a. As a rule, any reduction in the order of magnitude of complexity is preferable to a tweak in code that reduces the constant of proportionality. b. As a rule, any reduction in the constant of proportionality is preferable to a tweak that reduces the order of magnitude in complexity. c. As a rule, any reduction in the lines of code required to make an algorithm function is desirable to that of faster run times. d. As a rule, any reduction in the use of memory required by an algorithm is preferred over a tweak that improves run times. ANSWER: a

Multiple Response 48. What two terms are used to refer to a search in which each value in a sequence is examined until a target value is found or the end of the sequence is reached? a. sequential search b. modular search c. linear search d. binary search ANSWER: a, c

49. When performing a thorough analysis of an algorithm's complexity, what two cases are of the most concern in general? (Choose two.) a. best case b. worst case Copyright Cengage Learning. Powered by Cognero.

Page 8


Name:

Class:

Date:

Chapter 11: Searching, Sorting, and Complexity Analysis c. average case d. mediocre case ANSWER: b, c

50. What are the two major problems with the benchmark technique of measuring algorithm efficiency? a. Different hardware platforms have different processing speeds, meaning the running times will differ. b. A benchmark test does not account for differences in the size of data sets. c. The test cannot be performed without modifying the code for which the benchmark will be performed on. d. It can be impractical to determine the running time for algorithms with very large data sets. ANSWER: a, d

51. When using the counting instructions method of measuring efficiency, what are the two classes of instructions you must distinguish between? (Choose two.) a. Instructions that perform assignment operations that can be combined. b. Instructions that are repeated more than once in the course of the algorithm. c. Instructions that execute the same number of times regardless of the problem size. d. Instructions whose execution count varies with the problem size. ANSWER: c, d

Copyright Cengage Learning. Powered by Cognero.

Page 9


Name:

Class:

Date:

Chapter 11: Sets and Dictionaries True / False 1. Much like a list, a set contains items that are in a particular order. a. True b. False ANSWER: False

2. With a set, the difference and subset operations are not symmetric. a. True b. False ANSWER: True

3. The __sub__ method of the set class returns a set containing items in s1 that are not in s2. a. True b. False ANSWER: True

4. If s1 and s2 are sets, the expression s1.issubset(s2) returns True if s2 is a subset of s1. a. True b. False ANSWER: False

5. A set is similar to a bag, but it contains unique data items and additional methods. a. True b. False ANSWER: True

6. Python supports multiple inheritance, so a class can have more than one parent class. a. True b. False ANSWER: True

7. The AbstractSet class is a subclass of AbstractCollection because AbstractSet introduces new instance variables for data. a. True b. False ANSWER: False

8. The AbstractSet class is a subclass of AbstractBag. a. True b. False ANSWER: False Copyright Cengage Learning. Powered by Cognero.

Page 1


Name:

Class:

Date:

Chapter 11: Sets and Dictionaries 9. In Python's dict type, values are inserted or replaced at a given location using the index operator {}. a. True b. False ANSWER: False

10. The dictionary constructor has two optional collection arguments: a collection of keys and a collection of corresponding values. a. True b. False ANSWER: True

11. The entries in a dictionary consist of a key, a value, and an index. a. True b. False ANSWER: False

12. In the Entry class for a dictionary, comparisons are done using the value item in each entry. a. True b. False ANSWER: False

13. Array-based implementations of sets and dictionaries do not perform well. a. True b. False ANSWER: True

14. A hashing function acts on a given key by returning its absolute position in an array. a. True b. False ANSWER: False

15. If a hashing function runs in constant time, insertions, accesses, and removals of the associated keys are O(1). a. True b. False ANSWER: True

16. Two keys that hash to the same index is called a collision. a. True b. False ANSWER: True

17. To reduce the probability of collisions with hashes, you can decrease the array length. Copyright Cengage Learning. Powered by Cognero.

Page 2


Name:

Class:

Date:

Chapter 11: Sets and Dictionaries a. True b. False ANSWER: False

18. As the density, or number of keys relative to the length of an array decreases, so does the probability of hashing collisions. a. True b. False ANSWER: True

19. A small load factor and an array length that is a prime number increases the chances for a hashing collision. a. True b. False ANSWER: False

20. Two strings that are anagrams will return a unique integer value when the sum of the ASCII values is calculated. a. True b. False ANSWER: False

21. The standard Python hash function always returns a unique positive integer. a. True b. False ANSWER: False

22. In the hashing implementation of a set, self.index refers to the index of the chain in which the node was just located, or is -1 otherwise. a. True b. False ANSWER: True

23. In the hashing implementation of a set, the Bag class is used to represent an item and a pointer to the next item in a chain. a. True b. False ANSWER: False

24. In the hashing implementation of a dictionary, the data field of each node in a chain contains an Entry object. a. True b. False ANSWER: True Copyright Cengage Learning. Powered by Cognero.

Page 3


Name:

Class:

Date:

Chapter 11: Sets and Dictionaries 25. The data in sets and dictionaries are ordered by position by default. a. True b. False ANSWER: False

Multiple Choice 26. Which of the following is true about sets? a. the items in a set are arranged in order b. the difference and subset operations on a set are symmetric c. there are no duplicate items in a set d. there is no standard set class in Python ANSWER: c

27. Which of the following is a subset of Set A if Set A is {19 4 26 8}? a. None of the choices are subsets of Set A b. {19 4 26 8 0} c. {4 8 19 26 44} d. {} ANSWER: d

28. For a given set s, which method returns True if item is in s, or False otherwise. a. s.__contains__(item) b. s.__iter__(item) c. s = set() d. S1.__sub__(s2) ANSWER: a

29. What is the value of set S after the following operations? S = set([3, 9, 6]) S.add(6) S.add(4) S.remove(6) a. {3 9 6 4} b. {3 9 4} c. {3 9 6} d. {3 4 6 9} ANSWER: b

30. What strategy for implementing sets attempts to approximate random access into an array for insertions, Copyright Cengage Learning. Powered by Cognero.

Page 4


Name:

Class:

Date:

Chapter 11: Sets and Dictionaries removals, and searches? a. indexing b. linking c. hashing d. keying ANSWER: c

31. The simplest implementations of sets are subclasses of which other class? a. bags b. queues c. stacks d. lists ANSWER: a

32. Which method is specific to a set compared to a bag? a. remove b. __str__ c. add d. __sub__ ANSWER: d

33. In the code for the __sub__ method for the AbstractSet class, what is the missing code? def __sub__(self, other): difference = type(self)() for item in self: if not item in other: <missing code> return difference a. difference.remove(item) b. intersection.add(item) c. difference.add(item) d. return(item) ANSWER: c

34. Which method in the interface for a dictionary collection returns an iterator on the key/value pairs in the dictionary? a. keys() b. entries() c. pairs() d. values() ANSWER: b Copyright Cengage Learning. Powered by Cognero.

Page 5


Name:

Class:

Date:

Chapter 11: Sets and Dictionaries 35. In the code for the __init__ method in the Entry class or a dictionary, what is the missing code? def __init__(self, key, value): <missing code> self.value = value a. key = self.key b. self.key = key c. value = self.key d. self.key = value ANSWER: b

36. In the implementation of the AbstractDict class, which four methods have the same implementation for all dictionaries? a. keys, values, __add__, __eq__ b. entries, values, __init__, __str__ c. keys, values, entries, get d. get, __add__, keys, __init__ ANSWER: c

37. In the code for the __iter__ method for the ArrayDict class, what is the missing code? def __iter__(self): cursor = 0 while cursor < len(self): yield self.items[cursor].key <missing code> a. return(self.items[cursor]) b. cursor -= 1 c. return(self.items[key]) d. cursor += 1 ANSWER: d

38. What is the performance value of the array-based implementations of sets and dictionaries? a. O(n2) b. O(n) c. On d. O(1) ANSWER: b

39. For a key value of 93 and a hashing function of key % 46, what is the index into the array? Copyright Cengage Learning. Powered by Cognero.

Page 6


Name:

Class:

Date:

Chapter 11: Sets and Dictionaries a. 1 b. 2 c. 46 d. 47 ANSWER: a

40. For key values of 84 and 108 and a hashing function of key % 12, what is the result? a. indexes of 7 and 9 b. indexes of 0 and 1 c. a collision d. indexes of 12 and 14 ANSWER: c

41. What happens when two keys map to the same index after a hashing function has been applied? a. the array is lengthened b. a collision occurs c. the second item is mapped to the next cell d. the hash is reapplied with a random value ANSWER: b

42. In the code for the keysToIndexes function, what is the missing code? def keysToIndexes(keys, n): return <missing code> a. list(map(lambda key: key % n, keys)) b. list(map(lambda key: keys, key % n )) c. map(list(lambda key: key % n, keys)) d. map(list(lambda key % n: keys, key)) ANSWER: a

43. Referring to the keysToIndexes function, what is the result of the following statement? keysToIndexes([39, 18, 4, 51, 6, 28], 9) a. [4, 1, 5, 7, 6, 2] b. [3, 0, 4, 6, 6, 1] c. [2, 0, 3, 5, 5, 0] d. [8, 3, 6, 0, 1, 4] ANSWER: b

44. Referring to the keysToIndexes function, what is the result of the following statement? keysToIndexes([39, 18, 4, 51, 6, 28], 17) a. [6, 2, 5, 1, 7, 12] Copyright Cengage Learning. Powered by Cognero.

Page 7


Name:

Class:

Date:

Chapter 11: Sets and Dictionaries b. [7, 3, 6, 2, 8, 13] c. [4, 2, 3, 1, 5, 10] d. [5, 1, 4, 0, 6, 11] ANSWER: d

45. Which statement is true when considering a hashing strategy and the density of the keys/array length relationship? a. as the density decreases, the probability of collisions decreases b. as the density increases, the probability of collisions decreases c. as the density decreases, the probability of collisions increases d. as the density increases, the probability of collisions stays the same ANSWER: a

46. Which of the following is the best array length to reduce the probability of collisions given the set [8, 6, 18, 9, 14, 23]? a. 9 b. 8 c. 11 d. 12 ANSWER: c

47. When considering an insertion into a set using a hash function and linear probing, which of the following is defined as the position where the item should go if the has function works perfectly? a. absolute index b. probe index c. zero index d. home index ANSWER: d

48. In which collision-avoidance hashing strategy are the items stored in an array of linked lists in which each item's key locates the bucket where the item is to be inserted? a. clustering b. chaining c. quadratic probing d. linear probing ANSWER: b

49. In the algorithm for the __contains__ method of the hashing implementation of sets, what is the first step in the algorithm? a. set foundNode to table[index] b. set priorNode to foundNode c. set index to the home index of the item Copyright Cengage Learning. Powered by Cognero.

Page 8


Name:

Class:

Date:

Chapter 11: Sets and Dictionaries d. set foundNode to foundNode.next ANSWER: c

50. What strategy does the hashing implementation of a dictionary use? a. a binary search tree b. quadratic probing c. linear probing/bucket d. bucket/chaining ANSWER: d

Copyright Cengage Learning. Powered by Cognero.

Page 9


Name:

Class:

Date:

Chapter 12: Graphs True / False 1. An example of a process or model that can be graphed is the links between pages on the Internet. a. True b. False ANSWER: True

2. A graph is a set of edges and vertices such that each edge connects two vertices. a. True b. False ANSWER: True

3. On a weighted graph, the vertices are labeled with numbers. a. True b. False ANSWER: False

4. In a connected graph, there must be an edge from each vertex to every other vertex. a. True b. False ANSWER: False

5. In a complete graph with six vertices, the degree of a vertex is five. a. True b. False ANSWER: True

6. A simple path in a graph is one in which a path passes through the same vertex at least twice. a. True b. False ANSWER: False

7. In an undirected graph, two or more edges connect the same pair of vertices. a. True b. False ANSWER: False

8. In a digraph, each edge has a source vertex and destination vertex. a. True b. False ANSWER: True

9. In a DAG, there are no cycles. Copyright Cengage Learning. Powered by Cognero.

Page 1


Name:

Class:

Date:

Chapter 12: Graphs a. True b. False ANSWER: True

10. The adjacency matrix representation of a graph stores graph information in an array of lists. a. True b. False ANSWER: False

11. In an adjacency matrix, a 1 is used to represent an edge between two vertices. a. True b. False ANSWER: True

12. The adjacency list supports finding all the vertices adjacent to a given vertex more efficiently than the adjacency matrix. a. True b. False ANSWER: True

13. When you traverse a graph, there is always a single direct link from one item to any other item. a. True b. False ANSWER: False

14. The depth-first traversal of a graph uses a queue as the collection in the generic algorithm. a. True b. False ANSWER: False

15. A a depth-first traversal cannot be implemented recursively. a. True b. False ANSWER: False

16. A spanning tree has the fewest number of edges possible while still retaining a connection between all the vertices in the component. a. True b. False ANSWER: True

17. Repeated application of finding the minimum spanning tree for all the components in a graph yields a minimum spanning forest for a graph. Copyright Cengage Learning. Powered by Cognero.

Page 2


Name:

Class:

Date:

Chapter 12: Graphs a. True b. False ANSWER: True

18. A topological order assigns a rank to each edge such that the vertices go from lower- to higher-ranked edges. a. True b. False ANSWER: False

19. To find the shortest path, you can use a weighted graph and sum the edge of the weights between two vertices. a. True b. False ANSWER: True

20. Dijkstra's algorithm consists of two steps: the initialization step and the execution step. a. True b. False ANSWER: False

21. In Python, you need to define infinity as a long integer. a. True b. False ANSWER: False

22. All graphs, except weighted graphs, are collections of vertices connected by edges. a. True b. False ANSWER: False

23. A graph has a single length attribute, similar to the lists, queues, and stacks. a. True b. False ANSWER: False

24. In the implementation of a graph, the len function returns the number of the graph's vertices. a. True b. False ANSWER: True

25. Removing a vertex also entails removing any edges connecting it to other vertices. a. True Copyright Cengage Learning. Powered by Cognero.

Page 3


Name:

Class:

Date:

Chapter 12: Graphs b. False ANSWER: True

Multiple Choice 26. Which of the following is NOT a process for which a graph can serve as a model? a. a road map between hotels in a town b. a line at a movie theater c. the paths that data can travel in a network d. the routes between rooms in a building ANSWER: b

27. Which of the following is true about graphs? a. graphs consist of vertices and nodes b. the edges between vertices are always labeled c. an adjacency is when one vertex has a path to another vertex d. the length of a path is the number of edges on the path ANSWER: d

28. What makes a graph complete? a. when there is an edge from each vertex to all other vertices b. when there is a path from each vertex to all other vertices c. when there is a path between at least half the vertices d. when there are two or more edges between vertices ANSWER: a

29. Which term best describes a neighbor? a. a path exist between vertices b. a vertex is reachable from another vertex c. two vertices have consecutive labels d. two vertices are adjacent ANSWER: d

30. The number of edges connected to a vertex describes which of the following? a. a complete graph b. the neighbor of a vertex c. the degree of a vertex d. whether a graph is connected ANSWER: c

31. If vertex Penguins can reach vertex Capitals and vertex Capitals can reach vertex Islanders, but none of them can reach vertices Sharks or Ducks, what can you say about the set of vertices Penguins, Capitals, and Copyright Cengage Learning. Powered by Cognero.

Page 4


Name:

Class:

Date:

Chapter 12: Graphs Islanders? a. the set is a connected component b. the set describes a complete graph c. the vertices in the set are all adjacent to each other d. the set describes a connected graph ANSWER: a

32. In graph terms, what is a path that begins and ends at the same vertex? a. a simple path b. an undirected path c. a cycle d. a directed path ANSWER: c

33. Which of the following is true about an undirected graph? a. a graph-processing algorithm can move in only one direction along an edge that connects two vertices b. their edges do not indicate direction c. there can be multiple edges connecting any two vertices d. there is a source vertex and a destination vertex ANSWER: b

34. What are edges called that emanate from a given source vertex? a. incident edges b. directed edges c. destination edges d. cyclical edges ANSWER: a

35. Which of the following is NOT true about an adjacency matrix? a. it stores information about the graph in a grid b. the grid cell contains a 0 if there is no edge between vertices c. a graph with four vertices contains 16 cells d. it can be represented by an array of lists ANSWER: d

36. In a complete undirected graph with five vertices how many cells will contain a value of 1 in an adjacency matrix? a. 15 b. 10 c. 25 Copyright Cengage Learning. Powered by Cognero.

Page 5


Name:

Class:

Date:

Chapter 12: Graphs d. 125 ANSWER: c

37. In a complete undirected graph consisting of 3 vertices, how many total adjacencies will there be? a. 2 b. 6 c. 9 d. 4 ANSWER: b

38. What is the performance behavior of a linked adjacency list for determining whether an edge exists between two vertices? a. constant time b. O(N2) where N is the number of vertices c. linear with the length of the list d. logarithmic with the total number of vertices ANSWER: c

39. Which of the following is true about graph traversals? a. a single path to each item is assumed b. all algorithms are nonrecursive c. the algorithm should find the shortest path to a given item d. the type of collection used is irrelevant to the traversal algorithm ANSWER: c

40. In a breadth-first traversal of a graph, what type of collection is used in the generic algorithm? a. queue b. set c. stack d. heap ANSWER: a

41. In the pseudocode for the dfs function for partitioning the vertices in a graph into disjointed components, what is the missing pseudocode statement? dfs(graph, v, s): mark v as visited s.add(v) for each vertex, w, adjacent to v: if w is unvisited: <missing pseudocode> a. s.add(w) Copyright Cengage Learning. Powered by Cognero.

Page 6


Name:

Class:

Date:

Chapter 12: Graphs b. dfs(graph, v, s) c. s.add(v) d. dfs(graph, w, s) ANSWER: d

42. In a component with n vertices, how many edges are in the spanning tree? a. n b. n2 c. n + 1 d. n - 1 ANSWER: d

43. What is the minimum sum of all weights in a spanning tree of a weighted graph? a. spanning forest b. minimum spanning tree c. shortest path spanning tree d. topological spanning tree ANSWER: b

44. What can be described as the assignment of a rank to each vertex in a graph such that the edges go from lower-to higher-ranked vertices? a. directed acyclic graph b. sparse graph c. topological order d. shortest-path problem ANSWER: c

45. The smallest sum of edge weights between two vertices describes which of the following? a. the shortest path b. topological order c. topological sort d. maximum spanning tree ANSWER: a

46. What is the output of Dijkstra's algorithm? a. a three-dimensional array b. a two-dimensional grid c. a source vertex d. the number of vertices in the graph ANSWER: b Copyright Cengage Learning. Powered by Cognero.

Page 7


Name:

Class:

Date:

Chapter 12: Graphs 47. Which of the following is NOT true after the initialization step in Dijkstra's algorithm? a. the cells in the included list are all False, except for the cell that corresponds to the row of the source vertex in the results grid b. the distance in a row's distance cell is either 0, infinity, or a positive number c. the shortest path from the source to a vertex is found and the vertex's cell is marked in the included list d. the vertex in a row's parent cell is either the source vertex or undefined ANSWER: c

48. In the LinkedDirectedGraph class, which of the following methods is an iterator? a. incidentEdges b. getEdge c. containsEdge d. sizeEdges ANSWER: a

49. In the following code to add an edge in the LinkedDirectedGraph class, what is the missing code? def addEdge(self, fromLabel, toLabel, weight): fromVertex = self.getVertex(fromLabel) <missing code> fromVertex.addEdgeTo(toVertex, weight) self.edgeCount += 1 a. self.getVertex(toLabel) = fromVertex b. fromVertex.addEdgeTo(fromVertex, weight) c. self.weight += 1 d. toVertex = self.getVertex(toLabel) ANSWER: d

50. In the __init__ method code for the LinkedVertex class, what is the missing code? def __init__(self, label): self.label = label self.edgeList = list() <missing code> a. self.size += 1 b. self.mark = False c. return iter(result) d. result = self.label ANSWER: b

Copyright Cengage Learning. Powered by Cognero.

Page 8


Turn static files into dynamic content formats.

Create a flipbook
Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.