To Exam Info

IT 212 -- Final Review Questions

Part A: Multiple Choice Questions. Circle the letter of each correct answer.  Give an optional reason or show your work for each question.  If your answer is correct, the reason will not be considered. 5 points each.

  1. (Python) What is the output?
    x = 5;  y = 3;  x = y;  y = x;  
    print("{0:d} {1:d}\n".format(x, y)
    
    a. 3 3       b. 3 5       c. 5 3       d. 5 5
  2. (Python) Which is the correct definition of format_string for this Python statement:
    print format_string.format(name, gender, age) 
    
    a. format_string = "{0:d} {1:d} {2:d}"
    b. format_string = "{0:d} {1:s} {2:s}"
    c. format_string = "{0:s} {1:s} {2:d}"
    d. format_string = "{0:s} {1:s} {2:s}"
  3. (Python) If the deal and add_to_bottom methods of the Deck class are defined as in Project 5, which statement has the correct syntax? d is a Deck object and ph is a PokerHand object, which inherits the deal and add_to_bottom methods.
    a. ph.add_to_bottom(d.deal( ))
    b. add_to_bottom.ph(deal(d))
    c. ph.deal(d.add_to_bottom( ))
    d. add_to_bottom.ph(deal.d( ))
  4. (Python) Which of the following defines a PokerHand object with hand_type equal to TWO_PAIR?
    a. arr = [ Card.new(7, "S"), Card.new(8, "D"), 
               Card.new(8, "S"), Card.new(8, "H"),  
               Card.new(13, "D") ]
       ph = PokerHand(arr)
    
    b. arr = [ Card.new(7, "S"), Card.new(8, "D"), 
               Card.new(8, "S"), Card.new(10, "H"),  
               Card.new(13, "D") ]
       ph = PokerHand(arr)
      
    c. arr = [ Card.new(7, "S"), Card.new(8, "D"), 
               Card.new(8, "S"), Card.new(13, "H"),  
               Card.new(13, "D") ]
       ph = PokerHand(arr)
     
    d. arr = [ Card.new(8, "S"), Card.new(8, "D"), 
               Card.new(8, "S"), Card.new(13, "H"),  
               Card.new(13, "D") ]
       ph = PokerHand(arr)
    
  5. (Python) Which method is needed in the Card class so that a list a of card objects can be printed like this:
    print(a)
    # Output:
    [KS, 3D, 10H, QS, 10C]
    
    a. __print__     b. __repr__     c. str      d. __str__
  6. (Python) The MyInt class is defined as a derived class of int defined like this:
    class MyInt(int):
        def __init__(self, val):
            self = val
    
    Which of the following defines a method of the MyInt class that returns the number of digits in a MyInt object? A minus sign does not count as a digit.
    a.  def num_digits(self):
            return len(str(abs(self)))
    
    b.  def num_digits(self):
            return len(str(self.abs( )))
    
    c.  def num_digits(self):
            return self.abs( ).str( ).len( )
    
    d.  def num_digits(self):
            return str(abs(self)).len( )
    
  7. (Python) If the objects b and c are defined as
    b = sqlite3.connect('persons.db')
    c = b.cursor( )
    
    which statement is correct for adding a row to the persons table:
    a.  c.execute('insert into kids values(Alice, F, 11);')
    b.  c.execute('insert into kids values('Alice', 'F', 11);')
    c.  c.execute('insert into kids values("Alice", "F", 11);')
    d.  c.execute("insert into kids values('Alice', 'F', '11');")
    
  8. (Python) Which regular expression is accepts the string "W8922"?
    a. r"\AB\d{5}\Z"                     b. r"\ABW\d{4}\Z"
    c. r"\A(B|W)\d{4}W\Z"            d. r"\AW+\d+\Z"
  9. (Python) Which regular expression accepts any floating point constant with two digits after the decimal point (no exponent)?
    a. r"\A+?\d*.\d{2}\Z"            b. r"\A-?\d*.\d{2}\Z"
    c. r"\A-?\d.\d{2}\Z"               d. r"\A-?\d*\.\d{2}\A"
  10. (Python) What is the output?
    import re
    print(re.sub(r"[aeiou]+", "#", "bcaietwaxyzfgeouubnw"))
    
    a. bctwxyzfgbnw             b.  bcatwaxyzfgebnw 
    c. bc#tw#xyzfg#bnw        d. bc###tw#xyzfg#####bnw
  11. (Java) Which token designates a comment line?
    a. ##             b. //             c. [[             d. <<
  12. (Java) How many bytes are required for a Java int variable?
    a. 1          b. 2            c. 4            d. 8
  13. (Java) Which of the following is a properly written Java toString method?
    a. public String toString {
           return model + year;
       }
    
    b. public String toString( ) {
           return model + " " + year;
       }
    
    c. public void toString {
           return model + " " + year;
       }
    
    d. public void toString( ) {
           return model + " " + year;
       }
    
  14. Which of the following defines a String array named str?
    a. String str = new String[10];
    b. String str = new String(10);
    c. String[ ] str = new String[10];
    d. String str[ ] = new String(10);
    

Part B. Predict the Output. Construct the variable trace and predict the output. 15 points.

  1. Recall that s[i] returns the ith character (zero-based) of the string s.
    a = ["denver", "fort worth", "miami"]
    b = [1, 2, 0, 1, 0, 1]
    c = [5, 1, 2, 3, 4, 2]
    for i in range(0, 6):
        print(a[b[i]][c[i]], end="")
    
  2. # Source code file appointment.py.
    class Appointment:
        def __init__(self, the_purpose, the_location, \
            the_hour, the_minute):
            self.purpose = the_purpose
            self.location = the_location
            self.hour = the_hour
            self.minute = the_minute
    
        def __str__(self):
            return "{0:s} {1:s} {2:02d}:{3:02d}". \
                format(self.purpose, self.location, \
                       self.hour, self.minute)
                       
    # Source code file monthlyappointment.py.                   
    from appointment import Appointment
    class MonthlyAppointment(Appointment):
    
        def __init__(self, the_purpose, the_location, \
                     the_day, the_hour, the_minute):
            self.purpose = the_purpose
            self.location = the_location
            self.day = the_day
            self.hour = the_hour
            self.minute = the_minute
    
        def __str__(self):
            return "{0:s}; {1:s} {2:d} {3:02d}:{4:02d}". \
                format(self.purpose, self.location, \
                    self.day, self.hour, self.minute)
    
        def occurs_on(self, the_year, the_month, the_day):
            return self.day == the_day
            
    # Source code file onetimeappointment.py.
    from appointment import Appointment
    class OneTimeAppointment(Appointment):
    
        def __init__(self, the_purpose, the_location, \
                     the_year, the_month, the_day,
                     the_hour, the_minute):
            self.purpose = the_purpose
            self.location = the_location
            self.year = the_year
            self.month = the_month
            self.day = the_day
            self.hour = the_hour
            self.minute = the_minute
    
        def __str__(self):
            return "{0:s}; {1:s} {2:d}/{3:d}/{4:d} {5:02d}:{6:02d}". \
                format(self.purpose, self.location, \
                       self.month, self.day, self.year, \
                       self.hour, self.minute)
    
        def occurs_on(self, the_year, the_month, the_day):
            return self.year == the_year and \
                   self.month == the_month and \
                   self.day == the_day
                   
    # Source code file test1.py.
    from monthlyappointment import MonthlyAppointment
    from onetimeappointment import OneTimeAppointment
    
    appt1 = MonthlyAppointment("Staff Meeting", "Room 105", 14, 20, 30)
    appt2 = OneTimeAppointment("Poker Night", "Room 109", \
                2018, 6, 15, 20, 30)
    print(appt1)
    print(appt2)
    print(appt1.purpose, appt1.location)
    print(appt2.purpose, appt2.location)
    appt1.location = "Room 203"
    print(appt1.location)
    
    print(appt1.occurs_on(2018, 5, 15))
    print(appt1.occurs_on(2018, 5, 17))
    print(appt2.occurs_on(2018, 6, 15))
    print(appt2.occurs_on(2018, 6, 17))
    

Part C: Convert Traditional Test to Unit Test. Convert the traditional test file test1.py to a unit test file test2.py.

from monthlyappointment import MonthlyAppointment
from onetimeappointment import OneTimeAppointment
import unittest

class MyUnitTestClass(unittest.TestCase):
        
    def test_1(self):
    
        appt1 = MonthlyAppointment("Staff Meeting", "Room 105", 15, 20, 30)
        appt2 = OneTimeAppointment("Poker Night", "Room 109", \
            2018, 6, 15, 20, 30)
        
        # Sample assertEqual statement: 
        # self.assertEqual(computed, expected)
        
        
if __name__ == '__main__':
    unittest.main( )
    

Part D. Correct the Errors. 15 points.

  1. Correct the errors in these person, driver, and test modules. There are about 15 total errors.
    # Source code file person.py
    class Person:
    
        def __init_(self, the_last, the_first, the_gender)
            self.last = the_last
            self.first = the_first
            gender = the_gender
    
        def __str__(self):
            return("{0:s} {1:s} {3:s}". \
                format(self.last, self.first, self.gender)
    
    # Source code file driver.py
    from person import Person
    Class Driver < Person:
    
        def __init__(self, the_last, the_first, \
            the_gender, the_lic_num):
            self.last = the_last
            self.first = the_first
            self.gender = gender
            self.license_number = theLicNum
    
        def __str__(self):
            return super( ).str(self) + /
                "{0:s}\n".format(license_number)
    
        def __repr__( ):
            return self.license_number
    
    # Source code file test.py
    drivers = ( )
    file = open("drivers.txt")
    line = file.readline( )
    while line:
        f = line.strip(",")
        d = Driver(f[0].strip( ), f[1].strip, 
            f[2].strip( ), f[3].strip( )
    drivers.append d
    
    for d in drivers:
    if d.license_number[0] == "N" and d.gender = 'F':
        print("{0:s} {1:s}".format(d.first, d.last))
    
    # Contents of the input file drivers.csv:
    Bowman,Julia,F,J230-7842-4219
    Kern,Kendell,M,N212-3278-4839
    Kerry,Cynthia,F,N319-3283-3289
    Miller,Wayne,M,K237-2392-2139
    Johnson,Carrie,F,N329-3229-3293
    Chen,Maggie,F,N998-2918-5685
    

Part E: Find the errors in these Java programs. The equivalent Python scripts are shown for your reference.

  1. # Java program with errors. There are about 10 errors:
    import java.util.scanner;
    public class Overtime
    {
        private void static main(String[ ] args)
        {
            Scanner s = new Scanner(System.out);
            System.out.println("Enter the hours worked: ");
            double hours = Double.parseDouble(s.nextLine( ));
            System.out.println('Enter the hourly rate: ');
            double rate = Double.parseDouble(s.nextLine( ));
            if hours > 40
            {
                total_wages = (40.0 + (hours - 40.0) * 1.5) * rate;
            }
            else
            {
                total_wages = hours * rate
            }
            System.out.println('Total Wages: ', total_wages); 
    }
    
    # Python script:
    hours = input('Enter the hours worked: ')
    rate = input('Enter the hourly rate: ')
    if (hours > 40):
        total_wages = (40.0 + (hours - 40.0) * 1.5) * rate;
    else:
        total_wages = hours * rate
        
    print('Total Wages: ', total_wages)
    
  2. // Java source code. There are about 10 errors.
    import java.util.*;
    public class Magic8Ball
    {
        public static void main(String[ ] arg)
        {
            // Instantiate random number generator
            Random ranGen = Random( );
            
            // Choose random number in range [0, 6).
            int ansNum = ranGen.nextInt(6);
    
            // Choose response.
            if(ansNum == 0)
            {
                ans = "Yes -- definitely"
            }
            else if(ansNum = 1)
            {
                ans = "Most likely";
            }
            else if(ansNum == 2)
            {
                ans = "Reply hazy, try again";
            
            elif(ansNum == 3)
            {
                ans = "Cannot predict now";
            }
            else if(ansNum == 4)
            {
                ans = "Don't count on it";
            }
            else
            {
                ans = "Very doubtful";
            }
    
            # Print answer.
            System.out.println("Magic eight ball answer: ", ans, ".");
        }
    
    # Equivalent Python script
    from random import randrange
    
    ans_num = randrange(6)
    if ans_num == 0:
        ans = "Yes -- definitely"
    elif ans_num == 1:
        ans = "Most likely"
    elif ans_num == 2:
        ans = "Reply hazy, try again"
    elif ans_num == 3:
        ans = "Cannot predict now"
    elif ans_num == 4:
        ans = "Don't count on it"
    else:
        ans = "Very doubtful"
    end
       
    print("Magic eight ball answer:" + ans + ".")