Question 1. tmp = Stack() # Transfer every item from stk onto tmp. while not stk.is_empty(): tmp.push(stk.pop())

Similar documents
Question 1. Part (a) Simple Syntax [1 mark] Circle add_ints(), because it is missing arguments to the function call. Part (b) Simple Syntax [1 mark]

Text Input and Conditionals

CIS192 Python Programming

CIS192 Python Programming

CIS192 Python Programming

Question 1. [15 marks]

CSCA48 Term Test 1 Seminar

What is an algorithm?

Assignment 2. CS 234 Fall 2018 Sandy Graham. Create()

Lecture 21. Programming with Subclasses

Question 1. Part (a) [2 marks] error: assignment of read-only variable x ( x = 20 tries to modify a constant) Part (b) [1 mark]

UNIVERSITY OF TORONTO Faculty of Arts and Science. Midterm 1 CSC148H1F L0201 (Liu)

Lecture 21. Programming with Subclasses

Exceptions and Design

Part III Appendices 165

CSE : Python Programming. Homework 5 and Projects. Announcements. Course project: Overview. Course Project: Grading criteria

Do not turn this page until you have received the signal to start. In the meantime, please read the instructions below carefully.

CMSC 201 Fall 2016 Lab 09 Advanced Debugging

COMP1730/COMP6730 Programming for Scientists. Exceptions and exception handling

Lecture 18. Classes and Types

What is an algorithm?

CIS192 Python Programming

Lecture 21. Programming with Subclasses

Chapter 9: Dealing with Errors

1 Classes. 2 Exceptions. 3 Using Other Code. 4 Problems. Sandeep Sadanandan (TU, Munich) Python For Fine Programmers May 16, / 19

CSCI 204 Introduction to Computer Science II. Lab 6: Stack ADT

CSC148 Recipe for Designing Classes

A Little Python Part 3

CS 1110 Final Exam Solutions May 15th, 2014

Question 1. CSC 120H1 F Midterm Test Solutions Fall 2017

ECSE 321 Assignment 2

CSC148: Week 2

CSC148, Lab #4. General rules. Overview. Tracing recursion. Greatest Common Denominator GCD

Repetition Structures

Condition-Controlled Loop. Condition-Controlled Loop. If Statement. Various Forms. Conditional-Controlled Loop. Loop Caution.

CS 11 python track: lecture 2

Fundamentals of Programming (Python) Getting Started with Programming

This homework has an opportunity for substantial extra credit, which is described at the end of this document.

CS 1110 Final Exam May 9th, 2013 SOLUTIONS

Spring 2017 CS 1110/1111 Exam 1

Classes and Objects 1

Final Exam Version A

Student Number: Lab day:

THE AUSTRALIAN NATIONAL UNIVERSITY Mid Semester Examination September COMP1730 / COMP6730 Programming for Scientists

Getting Started with Python

DEBUGGING TIPS. 1 Introduction COMPUTER SCIENCE 61A

Advanced Python. Executive Summary, Session 1

a declaration of class name, and a class docstring

CSC148 Week 2. Larry Zhang

Student Number: Comments are not required except where indicated, although they may help us mark your answers.

ENGR 102 Engineering Lab I - Computation

What is an Exception? Exception Handling. What is an Exception? What is an Exception? test = [1,2,3] test[3]

2/5/2018. Learn Four More Kinds of C Statements. ECE 220: Computer Systems & Programming. C s if Statement Enables Conditional Execution

Chapter 2 Writing Simple Programs

Do not turn this page until you have received the signal to start.

CSCA08 Winter Week 12: Exceptions & Testing. Marzieh Ahmadzadeh, Brian Harrington University of Toronto Scarborough

CSE 160 Winter 2016: Final Exam

A Little Python Part 3

In addition to the correct answer, you MUST show all your work in order to receive full credit.

CS 111X - Fall Test 1 - KEY KEY KEY KEY KEY KEY KEY

Functions and Decomposition

CISC-235* Test #1 January 31, 2018

CS 211 Programming Practicum Fall 2018

New York University School of Continuing and Professional Studies Management and Information Technology. Advanced Python. Homework, Session 5

Slide Set 15 (Complete)

Name: utorid: U of T

Class extension and. Exception handling. Genome 559

Python 2 Conditionals and loops Matthew Egbert CS111

UNIVERSITY OF TORONTO Faculty of Arts and Science

NESTED IF STATEMENTS AND STRING/INTEGER CONVERSION

ECS Baruch Lab 3 Spring 2019 Name

CSE 160 Winter 2016: Final Exam

Credit: The lecture slides are created based on previous lecture slides by Dan Zingaro.

PLEASE HAND IN UNIVERSITY OF TORONTO Faculty of Arts and Science

CS 1110 Prelim 2 November 6th, 2012

Class extension and. Exception handling. Genome 559

SCHEME AND CALCULATOR 5b

Review 3. Exceptions and Try-Except Blocks

Outline. the try-except statement the try-finally statement. exceptions are classes raising exceptions defining exceptions

CS 1301 Exam 1 Fall 2010

CS 1110 Final, December 16th, 2013

CSC 148 Lecture 3. Dynamic Typing, Scoping, and Namespaces. Recursion

CSC148 Intro. to Computer Science

Code Reuse: Inheritance

Interactive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D

Do not turn this page until you have received the signal to start.

RYERSON POLYTECHNIC UNIVERSITY DEPARTMENT OF MATH, PHYSICS, AND COMPUTER SCIENCE CPS 710 FINAL EXAM FALL 97 INSTRUCTIONS

GIS 4653/5653: Spatial Programming and GIS. More Python: Statements, Types, Functions, Modules, Classes

Loops and Conditionals. HORT Lecture 11 Instructor: Kranthi Varala

Lab 3. A Multi-Message Reader

Structure of Programming Languages Lecture 5

CS 1110 Final Exam Solutions May 2018

Interactive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D

CS 231 Data Structures and Algorithms, Fall 2016

CS-141 Exam 2 Review November 10, 2017 Presented by the RIT Computer Science Community

THE AUSTRALIAN NATIONAL UNIVERSITY Final Examination November COMP1730 / COMP6730 Programming for Scientists

Module 10A Lecture - 20 What is a function? Why use functions Example: power (base, n)

Functions in MIPS. Functions in MIPS 1

CSE : Python Programming

INF 212 ANALYSIS OF PROG. LANGS FUNCTION COMPOSITION. Instructors: Crista Lopes Copyright Instructors.

Transcription:

Note to Students: This file contains sample solutions to the term test together with the marking scheme and comments for each question. Please read the solutions and the marking schemes and comments carefully. Make sure that you understand why the solutions given here are correct, that you understand the mistakes that you made (if any), and that you understand why your mistakes were mistakes. Remember that although you may not agree completely with the marking scheme given here it was followed the same way for all students. We will remark your test only if you clearly demonstrate that the marking scheme was not followed correctly. For all remarking requests, please submit your request in writing directly to your instructor. For all other questions, please don t hesitate to ask your instructor during office hours or by e-mail. Question 1. [6 marks] Write the body of the function below to satisfy its docstring. Assume that module stack.py defines a class Stack that provides the usual methods: is_empty(), push(item), pop(). Your code must not depend on any detail of the implementation of class Stack. In other words, the only thing you can do with Stack objects is to call some of their methods. from stack import Stack def size(stk): (Stack) -> int Return the number of items on Stack stk. The contents of stk are unchanged (it s OK if the contents of stk are modified during the execution of this function, as long as everything is restored before the function returns). # Hint: Create a second Stack object to use for temporary storage. tmp = Stack() # Transfer every item from stk onto tmp. while not stk.is_empty(): tmp.push(stk.pop()) # Now, transfer every item back onto stk while counting them. # (It would be OK to count during the first loop instead.) count = 0 while not tmp.is_empty(): stk.push(tmp.pop()) count += 1 return count Idea [3 marks]: function correctly computes the number of items in stk and stk is restored to original state before function returns Syntax [3 marks]: code uses only Stack methods to work with stk and Python syntax is generally correct Page 1 of 6

error code E1 [ 1 to 5]: incorrect overall outline: need to loop to copy stk content, then loop again to restore, and count during one of the loops error code I1 [ 1]: counting not done correctly error code I2 [ 2]: did nor restore stk to its original state error code I3 [ 2]: incorrect code to copy contents of stk [common] error code S1 [ 1]: did not return a value (or not the correct value) error code S2 [ 1]: incorrect use of Stack methods [common] error code S3 [ 1]: incorrect way to create a new Stack [common] error code S4 [ 1]: treating stk as a list (for example, len(stk) or for x in stk do not work) [common] error code S5 [ 1]: overwriting stk before counting its elements [common] Question 2. [9 marks] Write classes that satisfy the following specification. Docstrings are not required. A Student has a name (an arbitrary string) and a number (an integer in the range 1000 9999). Attempting to create a Student object with a number outside of the prescribed range raises an InvalidNumberError. Student objects have only one behaviour: the string representation of a Student consists of the Student s name, followed by a colon (:) and a space, followed by the Student s number. Correction: (This was announced during the test.) Add the following at the end of the second bullet point, after InvalidNumberError: (this is a new kind of Exception that you must define in your answer). class InvalidNumberError(Exception): pass class Student: def init (self, name, number): if not (1000 <= number <= 9999): raise InvalidNumberError() self.name = name self.number = number def str (self): return "{}: {}".format(self.name, self.number) Python [2 marks]: correct Python syntax overall (for class and method definitions, etc.) Exception [2 marks]: correct definition for class InvalidNumberError Constructor [3 marks]: Student. init has appropriate parameters, sets attributes correctly, and raises InvalidNumberError correctly when it is appropriate Str [2 marks]: Student. str returns a correct string Page 2 of 6

common error: Many students wrote method repr instead of str. There was no penalty for this. error code C1: appropriate parameters for Student s init method error code C2: Student s init method sets attributes correctly error code C3: Student s init method raises InvalidNumberError correctly when appropriate common error [ 1]: printing instead of returning for method str common error [ 1]: forgetting to convert self.number to a string inside method str common error [ 1]: raising InvalidNumberError somewhere else than in the code init method common error [ 0.5]: minor errors like forgetting self. in one place (forgetting it everywhere was more serious) Question 3. [8 marks] Write the body of the function below to satisfy its docstring. Assume this function is written in the same file as your code from the previous question (so nothing needs to be imported). def create_student(): () -> Student Ask the user for a name and for a number, using the input() function, then return a new Student object with that name and number. If the user enters an invalid number, ask again (repeatedly) until a valid number is entered. # For full marks, don t test the validity of the number directly -- just # try to create a Student and handle the possible outcomes appropriately. name = input("enter the Student s name:") while True: try: number = int(input("enter the Student s number:")) return Student(name, number) except (TypeError, ValueError, InvalidNumberError): pass Input [1 mark]: correct use of input() to read information from standard input Student [2 marks]: correct syntax for creating a Student object, and correct Student object created assuming that standard input contains appropriate information Loop [1 mark]: function keeps reading input until a valid student number is entered Try [2 marks]: correct use of try...except to detect when student number is invalid Python [2 marks]: correct Python syntax overall Page 3 of 6

error code E1 [ 0.5 to 1]: forgetting to check for errors during conversion to int [common] error code E2 [ 0.5 to 1]: missing return error code E3 [ 0.5]: no convertion to int [common] error code E4 [ 1]: no loop error code E5 [ 1]: code catches exception instead of raising it error code E6 [ 2]: does not create any Student object error code E7 [ 2]: no try...except block error code E8 [ 3]: incorrect loop and/or exception handling (for example, while InvalidNumberError ) Question 4. [7 marks] Write the body of the function below to satisfy its docstring. (Hint: Recursion makes this simple!) def rec_len(l): (nested list) -> int Return the total number of non-list elements within nested list L. For example, rec_len([1, two, [[], [[3]]]]) == 3. count = 0 for x in L: if isinstance(x, list): count += rec_len(x) else: count += 1 return count Outline [3 marks]: correct outline for the answer: loop over elements of L, adding up individual elements and size of sub-lists Type [1 mark]: correct syntax to check the type of each element of L Recursion [1 mark]: correct use of recursion Python [2 marks]: correct Python syntax overall Page 4 of 6

error code E1 [ 1]: incorrect use of recursion you need to add the result to the count (return value) error code E2 [ 1]: incorrect way to compare types error code E3 [ 1]: incorrect syntax for return statement error code E4 [ 2]: you are not counting the items in L[0], but you count items within every other element in L potentially multiple times (bad combination of loops with recursion) error code E5 [ 1]: infinite recursion: calling the function on the original list error code E6 [ 1 to 2]: you are not counting the elements in L[0] error code E7 [ 1 to 2]: you are not counting the elements in L[1] error code E8 [ 1]: you need to return a value error code E9 [ 1]: you re iterating from 0 to len(list) instead of over the items in the list error code E10 [ 1]: this function returns an integer Question 5. [10 marks] Write code on the next page for a complete unittest file for function rec_len above. Include a brief (one line) docstring for each test function, to explain the purpose of the test. For full marks, you should have at least three test cases involving some nested and some non-nested inputs. import unittest from q2 import rec_len # assume rec_len is in a file named "q2.py" Page 5 of 6

class TestRecLen(unittest.TestCase): Test function rec_len. def test_0(self): Empty list. self.assertequal(rec_len([]), 0) def test_1(self): Nested but empty list. self.assertequal(rec_len([[[]], []]), 0) def test_2(self): Non-empty, non-nested list. self.assertequal(rec_len([1, two ]), 2) def test_3(self): Typical nested list. self.assertequal(rec_len([[[1]], two, [3]]), 3) if name == main : unittest.main(exit=false) unittest [2 marks]: correct syntax for creating a subclass of unittest.testcase and its individual test functions Cases [6 marks]: 2 marks for each test case; make sure cases cover a range of situations Docstrings [2 marks]: clear descriptive docstrings for each test case error code E1 [ 2]: missing at least one non-nested test case error code E2 [ 2]: missing empty test case error code E3 [ 2]: fewer than three test cases error code E4 [ 1]: docstrings unclear error code E5 [ 0.5 to 2]: incorrect syntax error code E6 [ 1]: input parameter should be a nested list error code E7 [ 1]: incorrect use of asserttrue or assertfalse error code E8 [ 1 to 2]: incorrect use of unittest.testcase: defining separate classes for each individual test case error code E9 [ 1 to 2]: missing docstrings error code E10 [ 1]: missing function calls error code E11 [ 1 to 2]: incorrect test case error code E12 [ 1]: missing class definition error code E13 [ 1]: incorrect expected value Page 6 of 6