Introduction to Computer Science I Spring 2014 Mid-term exam Solutions



Similar documents
We will learn the Python programming language. Why? Because it is easy to learn and many people write programs in Python so we can share.

Exercise 1: Python Language Basics

CS 1133, LAB 2: FUNCTIONS AND TESTING

CSCE 110 Programming I Basics of Python: Variables, Expressions, and Input/Output

Python Loops and String Manipulation

Python Lists and Loops

Python Programming: An Introduction to Computer Science

Introduction to Python

CS177 MIDTERM 2 PRACTICE EXAM SOLUTION. Name: Student ID:

Chapter 2 Writing Simple Programs

Programming Exercises

Exercise 4 Learning Python language fundamentals

Visual Logic Instructions and Assignments

Lexical analysis FORMAL LANGUAGES AND COMPILERS. Floriano Scioscia. Formal Languages and Compilers A.Y. 2015/2016

Chapter 3 Writing Simple Programs. What Is Programming? Internet. Witin the web server we set lots and lots of requests which we need to respond to

Computer Science 217

Crash Dive into Python

Crash Dive into Python

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

[1] Learned how to set up our computer for scripting with python et al. [3] Solved a simple data logistics problem using natural language/pseudocode.

Welcome to Introduction to programming in Python

A simple algorithm with no simple verication

Computers. An Introduction to Programming with Python. Programming Languages. Programs and Programming. CCHSG Visit June Dr.-Ing.

Python for Rookies. Example Examination Paper

Command Scripts Running scripts: include and commands

Webforms on a Drupal 7 Website 3/20/15

Writing Control Structures

VISUAL GUIDE to. RX Scripting. for Roulette Xtreme - System Designer 2.0

First Bytes Programming Lab 2

Moving from CS 61A Scheme to CS 61B Java

Algorithm Design and Recursion

Exercise 0. Although Python(x,y) comes already with a great variety of scientic Python packages, we might have to install additional dependencies:

Problem Solving Basics and Computer Programming

River Dell Regional School District. Computer Programming with Python Curriculum

Concepts and terminology in the Simula Programming Language

Practice Questions. CS161 Computer Security, Fall 2008

Introduction to Python

Introduction to: Computers & Programming: Review for Midterm 2

CS106A, Stanford Handout #38. Strings and Chars

GCE Computing. COMP3 Problem Solving, Programming, Operating Systems, Databases and Networking Report on the Examination.

Area and Perimeter: The Mysterious Connection TEACHER EDITION

GCE. Computing. Mark Scheme for January Advanced Subsidiary GCE Unit F452: Programming Techniques and Logical Methods

Chapter 1: Key Concepts of Programming and Software Engineering

PHP Debugging. Draft: March 19, Christopher Vickery

Lecture 3: Finding integer solutions to systems of linear equations

Opposites are all around us. If you move forward two spaces in a board game

Introduction to Python

Introduction to Computers and Programming. Testing

Basics of I/O Streams and File I/O

Object Oriented Software Design

CS 106 Introduction to Computer Science I

Introduction to Programming with Python Session 3 Notes

CRASH COURSE PYTHON. Het begint met een idee

CSC 221: Computer Programming I. Fall 2011

2! Multimedia Programming with! Python and SDL

Data Integrator. Pervasive Software, Inc B Riata Trace Parkway Austin, Texas USA

MOC 20461C: Querying Microsoft SQL Server. Course Overview

Object Oriented Software Design

Computer Science for San Francisco Youth

Answers to the Try It Yourself Sections

University of Hull Department of Computer Science. Wrestling with Python Week 01 Playing with Python

CS 241 Data Organization Coding Standards

Programming and Software Development CTAG Alignments

Computer Programming I

COSC Introduction to Computer Science I Section A, Summer Question Out of Mark A Total 16. B-1 7 B-2 4 B-3 4 B-4 4 B Total 19

Introduction to: Computers & Programming: Input and Output (IO)

Understanding DPI and Pixel Dimensions

6.170 Tutorial 3 - Ruby Basics

What to Expect on the Compass

Curriculum Map. Discipline: Computer Science Course: C++

Square Roots and Other Radicals

Translating to Java. Translation. Input. Many Level Translations. read, get, input, ask, request. Requirements Design Algorithm Java Machine Language

Introduction to Python for Text Analysis

Test Case Design Techniques

Chapter 2: Algorithm Discovery and Design. Invitation to Computer Science, C++ Version, Third Edition

EE282 Computer Architecture and Organization Midterm Exam February 13, (Total Time = 120 minutes, Total Points = 100)

Part A: Fill in the blanks below with whole numbers greater than 1 that will make the number sentences true.

Oracle Database: SQL and PL/SQL Fundamentals

Name Spaces. Introduction into Python Python 5: Classes, Exceptions, Generators and more. Classes: Example. Classes: Briefest Introduction

WESTMORELAND COUNTY PUBLIC SCHOOLS Integrated Instructional Pacing Guide and Checklist Computer Math

14:440:127 Introduction to Computers for Engineers. Notes for Lecture 06

Sources: On the Web: Slides will be available on:

Assignment 2: Option Pricing and the Black-Scholes formula The University of British Columbia Science One CS Instructor: Michael Gelbart

Perl in a nutshell. First CGI Script and Perl. Creating a Link to a Script. print Function. Parsing Data 4/27/2009. First CGI Script and Perl

AP Computer Science A 2012 Scoring Guidelines

SHELL INDUSTRIAL APTITUDE BATTERY PREPARATION GUIDE

CSC 241 Introduction to Computer Science I

Introduction to Programming with Python. A Useful Reference.

Project 2: Bejeweled

Oracle SQL. Course Summary. Duration. Objectives

A Concrete Introduction. to the Abstract Concepts. of Integers and Algebra using Algebra Tiles

Machine Learning Final Project Spam Filtering

TRAINING MANUAL. Executing Reports. Formatting Options. Copyright 2004 University of San Diego. All rights reserved.

Calculator. Introduction. Requirements. Design. The calculator control system. F. Wagner August 2009

The programming language C. sws1 1

In this Chapter you ll learn:

G10 Data Setting Command

Basic Lisp Operations

Transcription:

Introduction to Computer Science I Spring 2014 Mid-term exam Solutions 1. Question: Consider the following module of Python code... def thing_one (x): y = 0 if x == 1: y = x x = 2 if x == 2: y = -x x = 3 elif x == 3: y = 2 * x x = 2 * y else: y = x print( x = + str(x)) print( y = + str(y)) def thing_two (l, v): for i in range(len(l)): l[i] += v v = v - 1 def main (): thing_one(7) thing_one(3) thing_one(1) l = [20, 40, 30] v = 6 thing_two(l, v) print( l = + str(l)) print( v = + str(v)) if name == main : main() What output is printed when this module is run? 1

Answer: The output produced is... x = 7 y = 7 x = 12 y = 6 x = 3 y = -2 l = [26, 45, 34] v = 6 Discussion: The great majority of people got the first four lines of the output that is, the first two pairs of lines that show the output for the function calls, thing_one(7) and thing_one(3). It was downhill from there. The call thing_one(1) required a careful reading of the conditional statements in that function. Specifically, notice that there are two distinct conditional statements in that function: first, an if-then statement; second, an immediately subsequence if-then-elif-then-else multi-part statement. The key here was to observe that each of these statements will be applied by Python in sequence. That is, with a paramater of x = 1, the condition on the first statement will be True. As a consequence, the then-branch will assign y = 1 and then x = 2. Many people stopped there in determining the ultimate value of x and y, but doing so was incorrect. The next conditional statement would be executed next. Since x = 2 at that point, the leading if -condition would be True, triggering that statement s then-branch. Consequently, y = 2, followed by x = 3. It is these values that are then printed. Sadly, the evaluation of thing_two wasn t much better for most people. Let s begin by tracking the values of l and v and their changes as the code progresses. To do so, we have to remember the effect of scope. That is, the spaces named l and v in main are different from the parameters named l and v in thing_two. Let s call the former l m and v m (m for main), and the latter l t and v t (t for thing_two). After all of the calls to thing_one, we see that main will assign l m = [20, 40, 30], and v m = 6. When main performs the the function call to thing_two, the arguments l m and v m are passed to thing_two such that the called function s parameters are assigned l t = l m = [20, 40, 30] and v t = v m = 6. The function thing_two will loop through the indices of l t 0, 1, and 2. The steps that occur within the body of this loop are performed indeed, they could only be performed on l t and v t. Thus, as the loop iterates, the values will change in the following sequence: 2

i l t v t before loop [ 20, 40, 30 ] 6 0 [ 20, 40, 36 ] 5 1 [ 20, 45, 36 ] 4 2 [ 24, 45, 36 ] 3 When the loop is complete and thing_two is about to return, its local variables have the values on the last row of this table. The program then returns from this function call, resuming within main where it had left off, leaving the final two print calls to be performed. To determine what these calls will print, we must keep in mind the relationships between the local variables within main that were used as arguments to the call to thing_two, and the local variables within thing_two that were defined as parameters. First, notice that v m and v t are two different spaces. When v m was passed as an argument to provide an initial valuable for the parameter v t, any changes to that parameter by thing_two change only the local space. That is, updates to v t do not change v m at all. The call to print at the end of main is printing a copy of v m, which remains unchanged with the value of 6. However, l m and l t are another story. Remember that the spaces named by these variables do not contain a list; rather, each space points to a list. The difference is a critical one here. When thing_two is called, the pointer contained in l m is passed as an argument, thus initializing l t with a copy of that pointer. In other words, l m and l t point to the same list. Since lists are mutable, then the changes in the values of the list that occur as thing_two executes are modifications to that one list. When thing_two completes its work and returns, l m still points to that very same list and its modified contents. When main calls print to show l, it is printing the list to which l m refers, which is the same list that thing_two modified through its pointer l t. This question was challenging in that you had to understand Python s rules about variables, scope, arguments, parameters, and simple values vs. pointers to lists/strings. However, as always, if you could draw the data, the outcome was clear. 3

2. Questions: Provide short answers (no more than a few sentences) to each of the following questions: (a) In Python, strings are immutable while lists are mutable. difference? What is the (b) How does the // operator differ from the / operator? Give an example of where // would be needed. (c) United Airlines will only allow carry-on bags that are no more than 22 inches long, 14 inches wide, and 9 inches deep. Assuming that variables named length, width, and depth have already been assigned values, write an expression combining the three that evaluates to True if bag fits within those limits, and False otherwise. Answers: (a) One a string is created, it cannot be changed. Characters cannot be added, removed, or altered; any seeming modification of a string (e.g., slices or append operations) cause a modification to be carried out on a duplicate. In contrast, lists can be extended, shortened, or its elements altered. (b) Both operators perform division, but / produces a real-valued result, while // produces only an integer result. Specifically, any fractional result from integer division is discarded, truncating the result. We often use integer division when computing list indices, which cannot be fractional. (c) length <= 22 and width <= 14 and depth <= 9 Discussion: (a) While most stated something resembling the correct intuition behind this difference one is changeable, the other is not the devil is sometimes in the details. Specifically, it was important to remember that each string and list are not directly stored in a space named by a variable; rather, the variable spaces point to a string or list. The difference is critical when describing just what is changeable (or not): the variable s space; or the string/list itself. It is the latter to which these terms refer. For the former, the pointer in each variable s space is always changeable, for each can be made to point to a different string or list. (b) Most of the answers here were again mostly on the mark. There was the occassional inversion of the two operators, as well as a few who confused // with the modulus/remainder operator, %, but otherwise the description of the two were correct. Some people did not read the question carefully regarding the requested example. Specifically, the example was either forgotten completed, or more often, the example was just a demonstion of how the two would calculate differing results given the same input values (e.g., 5 / 2 = 2.5 vs. 5 // 2 = 2. Of course, the question clearly asks 4

for an example situation in which integer division would be desirable or necessary. (c) Far and away the most common mistake was the failure to provide only an expression, and the question specified. Some wrote conditional statements, others complete functions, adding superfluous material beyond the desired expression itself. A less common mistake was to take the product of the length, width, and depth, and thus test the total volume of the bag, rather than the length of each dimension. 5

3. Question: Write a function named print_big_v (size), where size indicates the size of the pattern that the function will print. Specifically, this function is called with 6 as the argument for size, then it should print the following: \/ That is, the big V, made up of forward and backward slash characters, should be 6 rows tall. Answer: def print_big_v (size): for i in range(size): front_spaces = * i middle_spaces = * (2 * (size - i - 1)) print(front_spaces + \\ + middle_spaces + / ) Discussion: Answers for this problem were largely good, and a number of valid approaches were taken (of which the code above is just one). There were two common errors: (a) No leading spaces: Some forgot to have their function print any spaces before the \ character on each line. Whoops. (b) Insufficient middle spaces: Many printed some spaces between the left and right arms of the big V, but not enough of them. Usually, there was an expression to print a number of spaces tied to the row number a valid approach but off by a factor of two. There were a number of less common but more profound errors, including a surprising number of people who used an extra inner loop, often using the same variable as the outer loop as a counter. None of these made much sense, and I can only assujme that they are the result of some rote repetition of a pattern seen on a sample problem. If you made this mistake, be certain that you know why it was wrong, and how to approach this type of problem correctly. 6

4. Question: Write a function named extract_lesser (l, v) that, from a list of numbers l finds all of the values less than v, puts them into a new list, and returns that new list. Answer: def extract_lesser (l, v): less_list = [] for num in l: if num < v: less_list.append(num) return less_list Discussion: Again there were a number of valid approaches to this problem. Most commonly, people looped over the indices of l (with a loop something like: for i in range(len(l)):, but then compared i < v in the next step, confusing the use of i as a position, not a value itself. Others tried to keep track of the next available position in the new list (above, less_list) and assign that position directly. Such approaches are not valid ways to append a value to an existing list, and would crash the program; either the append() method or the use of concatenation is necessary too append an item to the end of the existing list. A few others printed the final result rather than returning it. Be sure that you know that difference between returning and printing! 7