CSCI1101& 2nd&Test&Solutions& April&17,&2015&! 1.!!The!following!statements!are!executed:!! x=[3.5, -9, 2.0, 6.7, 4, 2]

Size: px
Start display at page:

Download "CSCI1101& 2nd&Test&Solutions& April&17,&2015&! 1.!!The!following!statements!are!executed:!! x=[3.5, -9, 2.0, 6.7, 4, 2]"

Transcription

1 CSCI1101& 2nd&Test&Solutions& April&17,&2015& 1.Thefollowingstatementsareexecuted: x=[3.5, -9, 2.0, 6.7, 4, 2] y=((3, 7 ), (4,2), (2,3)) z = {1:['one','un','uno','yi'], 2:['two','deux','dos','er'], 3:['three','trois','tres', 'san']} Answerthefollowingquestionsaboutx,yandz.Insomeparts,ifthequestionasks youwhathappenswhenaparticularstatementisexecuted,therightanswermight be'itresultsinanerror'. (a)whatisthetypeofy?tuple (b)whatissum(x[:2])?f5.5frequentincorrectanswer:f3.5,becauseyouadded x[0]+x[1]+x[2]. (c)whatarelen(z), len(z[2])andlen(z[2][2])?(becareful)3,4,3the admonitiontobecarefulwasforthelastpart.sincezisadictionary,z[2]refersto theiteminthedictionarywithkey2,andsincez[2]isalist,z[2][2]referstothe thirditeminthisdictionary,whichis'dos',astringoflength3.hadzbeendefined withsquareinsteadofcurlybraces,itwouldhavebeenalist,andz[2][2]would referto'tres',withlength4. (d)whatisthevalueofxafterthefollowingstatementisexecuted? x=x+3erroryoucan'taddalistandanint.x+[3]wouldhavebeenokay,andhave value=[3.5, -9, 2.0, 6.7, 4, 2,3] (e)whatisthevalueofxafterthefollowingstatementisexecuted? x.append(3) [3.5, -9, 2.0, 6.7, 4, 2,3] Note that it is the value of x that changes, the expression x.append(3) has no value. (f)whatisthevalueofyafterexecutingthefollowingstatement?(beverycareful) y += (5,6) ((3, 7), (4, 2), (2,3),5,6) Adding two tuples just concatenates the elements of the tuples, but of course this is designed to make you write the incorrect answer ((3, 7), (4, 2), (2,3),(5,6)). (I would feel bad about this trick question if it did not come packaged with a sign

2 that in effect said 'Trick Question') If you really wanted to get ((3,7),(4,2),(2,3),(5,6)) you would write y += ((5,6),) (g)whatisthevalueofyafterexecutingthefollowingstatement? y[2]= (6,2) error Tuples, like strings, are immutable, and you cannot directly assign to one of its components. Assumeforthenextseveralquestionthatx,yandzareasgivenatthebeginningof thisproblem(inotherwords,thatthestatementsdescribedinthequestionsabove havenotbeenexecuted). (h)whatarethetypeandvalueofthefollowingexpression? [z[w[0]][2] for w in y if w[0] in z] type:listvalue:['tres','dos'] Afewpeoplegavethewrongtype,butevenifyoucan'tdecipherthelist comprehension,youshouldknowthatlistcomprehensionalwaysgivesyoualist. Sincetheonlyelementswofywithw[0]havingthevalueofakeyinzare(3,7)and (2,3),thisisequivalentto [z[3][2],z[2][2]],whichis['tres','dos'],thoughiaccepted['dos','tres']without penalty. 2.Considerthefunctionprob2definedbelow: def prob2(nums): u=[(int(math.sqrt(x)),x) for x in nums] v=[y for y in u if y[0]**2==y[1]] return [y[1] for y in v] Supposewecallprob2(x),wherexisthelist [11,11,17,9,3,5,8,11,9,14,14,2,3,13,13,6,1,8,7,6] (a)whatarethefirstthreeelementsofthelistucreatedinthefirststatementofthe function? (3,11),(3,11),(4,17)

3 (b)whatarethefirstthreeelementsofthelistvcreatedinthesecondstatementof thefunction? (3,9),(3,9),(1,1) Asitturnsout,thesearetheonlythreeelementsofv. (c)whatisthevaluereturnedbythefunction? [9,9,1] (d)giveasuccinctdescriptionofwhatprob2(nums)returnsingeneral,when numsisalistofintegers. Itreturnsalistoftheperfectsquaresinnums. SomepeoplegavemethebrainFdumponthisproblem,describingeverystepofthe programbeforegettingtothepoint. Thetextbookdescribesanumberofcommonpatternsforprocessinglists,with nameslikedecorate,filter,undecorate,map,reduce.thisonemightbecalled decorateffilterfundecorate,orsimplyacomplicatedfilteroperation.wecouldalso doitwithasinglelistcomprehension [yforyinnumsifint(math.sqrt(y))**2==y] 3.Writeafunction def columnsums(v) wherevisalistoflistsofintegers(i.e.,atwofdimensionalarray).forexample [[2,F1,3],[4,1,6],[1,1,0],[0,F4,2]] whichwethinkofasrepresentingthearray F4 2 Yourfunctionshouldreturnalistofthesumsofthesuccessivecolumns,sointhe exampleabove,thereturnvalueshouldbe[7,f1,11].yourfunctionshouldwork witharraysofanywidthandheight,butyoumayassumethatitisonlycalledwith arraysthatareproperlyformed(inthesensethatalltherowshavethesame numberofelements).

4 HereareTHREEdifferentsolutions.Theideaofthefirstoneistotraversethearray goingdowneachcolumninturn,accumulatingthecolumnsumandappendingitto thenewlist. Theideaofthesecondistosimultaneouslycomputethesumineachcolumn, initiallysettingarowof0's,thentraversingthearrayrowbyrowandaddingaswe goalong. Thethirdsolutionisthebasicallythesameideaasthefirst,usinglist comprehensionattwolevels. def columnsum1(v): height = len(v) width = len(v[0]) result=[] for col in range(width): accumsum=0 for row in range(height): accumsum+=v[row][col] result.append(accumsum) return result def columnsum2(v): height = len(v) width = len(v[0]) result=[0]*width for row in range(height): for col in range(width): result[col]+=v[row][col] return result def columnsum3(v): height = len(v) width = len(v[0]) return[sum([v[row][col] for row in range(height)]) for col in range(width)]

5 def binsearch(thelist,target): count = 0 low = 0 high = len(thelist)-1 while low<= high: mid=(low+high)/2 if thelist[mid] == target: return mid elif thelist[mid]<target: low=mid+1 else: #if you're here, then thelist[mid]>target high = mid-1 return -1 Figure&1:&&The&original&binary&search& def binsearch_new(thelist,target): low = 0 high = len(thelist)-1 while low <= high: mid=(low+high)/2 if thelist[mid] == target: return (thelist[mid],thelist[mid+1]) elif thelist[mid]<target: low=mid+1 else: high = mid-1 if low>mid: return (thelist[mid],thelist[low]) else: return (thelist[high],thelist[mid]) Figure&2:&The&modified&binary&search&

6 4.Displayedonthenextpageistheoriginalversionofthebinarysearchfunction forsearchingasortedlist,aspresentedinclass,alongwithamodifiedversion.as youmayrecall,theoriginalimplementationreturnstheindexofthetargetinthe list,ifthetargetitemispresent,andreturnsf1otherwise. Inthemodifiedversionthereturnvalueshavebeenaltered.Whattheresulting functiondoesisactuallyquiteuseful,butitsuffersfromaseriousdefect,asyou shoulddiscoverinpart(c)below. Supposethemodifiedfunctioniscalledwith [1,8,27,64,125,216,343,729,1000] asthefirstargument. (a)whatisthereturnvalueifthefunctioniscalledwith343asthesecond argument? (343,729) Intheeventtheitemisfound,thisjustreturnsthetupleconsistingoftheitemand thefollowingitem. (b)...with600asthesecondargument?? (343,729) Lookcarefullyatwhathappenswiththevalueslow,highandmidduringthesearch for600.atsomepointwehavelow=6,high=7withthetargettrappedbetween elements6and7ofthelist.inthenextstepwesetmidto6.sincethevalueistoo low,wesetlowto7.sonowlow,midandhighareall7,andweexittheloopwith high=6,low=mid=7,sothefunctionreturns(thelist[high],thelist[mid]),or (343,729). (c)...with1500asthesecondargument? error Eventuallywegetlow=high=mid=8,andsincewehavethelist[mid]<target,weset low=9andexittheloop.sincelow>mid,thefunctiontriestoreturn (thelist[mid],thelist[low]),butthelist[low]isoutoftherangeofindicesofthelist.

7 5.WerepresentacollectionofBostonFarearestaurantsasaPythondictionarydi. Hereisatypicalentry(therestaurantisrealFFFthedatacomesfromYelp). "Sandrine's" : ('Cambridge','French','$$$',3.5) Thatis,thekeyofeachentryisthenameoftherestaurant,andthevaluefieldisa tupleconsistingof:thelocation,thetypeoffood,anexpenserating(the3dollar signs),andanaverageofreviewerratings(3.5stars). (a)myfavoriterestaurantismom's)eat)at)joe's.iwouldliketoseeifothersagree withme,soiwanttowriteapythonstatementorstatementsthatwillprintoutthe starratingofthisrestaurant.thecodeyouwriteshouldnotcauseanpythonf generatederrormessageonthechancethatthisrestaurantisnotinthedatabase, butinsteadprint'restaurantnotfound'. if"mom'seatatjoe's"indi printdi["mom'seatatjoe's"][3] else: print'restaurantnotfound' Moststudentsoverthoughtthisone,andtriedtogivemeafunctionthatworkedfor ageneralrestaurantpassedasaparameter,butionlywantedabrieffragmentof code. (b)iwanttoimpresssomeonebytakingthemtoafancyitalianplaceinthenorth End.(Idon'tcareiftherestaurantisgood,Ijustwantmyguesttoseemespendinga lotofmoney.)writeastatementorstatementsthatprintsalistofthenamesofall therestaurantswithlocation'northend',foodtype'italian',andatleast4dollar signs.this)list)should)be)sorted)in)alphabetical)order. s=[rforrindiifdi[r][0]=='northend'anddi[r][1]=='italian'andlen(di[r][2])>=4] s.sort() prints Manystudentsassumed4starswasthehighestpossibleandwrote==inplaceof>=. Otherswrote"'NorthEnd'indi[r]"inplaceof"di[r]=='NorthEnd'".That'sok,butif therewereadistrictinthecitycalled'italian',itmightnotworkandsomedidnot usethelenfunctionandwrotedi[r][2]>='$$$$',whichactuallyworks Someforgotthats.sort()doesnothaveavalue,andthusprints.sort()doesnot work.

This was the second midterm from I have added a few comments in bold type, like this.

This was the second midterm from I have added a few comments in bold type, like this. This was the second midterm from 2015. I have added a few comments in bold type, like this. Solutions are provided in a separate document. Be aware, when you are reading the solutions, that they were based

More information

1. Find the type and value of each of the following expressions. Warning: several of these expressions will result in an error.

1. Find the type and value of each of the following expressions. Warning: several of these expressions will result in an error. This was the final CS1 exam given in May, 2014. I eliminated one question concerning classes and objects, and clarified a few points that were unclear in the original version. I also translated some things

More information

Review 4. Lists and Sequences

Review 4. Lists and Sequences Review 4 Lists and Sequences Overview of List Syntax x = [0, 0, 0, 0] x.append(2) 3 in x x[2] = 5 x[0] = 4 k = 3 x[k] = 2 * x[0] x[k 2] = 6 Create list of length 4 with all zeroes Append 2 to end of list

More information

Overview of List Syntax

Overview of List Syntax Lists and Sequences Overview of List Syntax x = [0, 0, 0, 0] Create list of length 4 with all zeroes x 4300112 x.append(2) 3 in x x[2] = 5 x[0] = 4 k = 3 Append 2 to end of list x (now length 5) Evaluates

More information

(i) d={'head':(1,2,1),'arm':(1,2),'hand':(1,1,2),'leg':(1,1,1),'foot':(1,2,1) sum(d['head'])

(i) d={'head':(1,2,1),'arm':(1,2),'hand':(1,1,2),'leg':(1,1,1),'foot':(1,2,1) sum(d['head']) CSCI1101 Final Exam May 6, 2015 The Final Exam from 2015. I tried to check every instance of a Python 2 idiom and change it to Python 3, but it is possible that I missed a print statement or two. In the

More information

CPTS 111, Fall 2011, Sections 6&7 Exam 3 Review

CPTS 111, Fall 2011, Sections 6&7 Exam 3 Review CPTS 111, Fall 2011, Sections 6&7 Exam 3 Review File processing Files are opened with the open() command. We can open files for reading or writing. The open() command takes two arguments, the file name

More information

Skills Quiz - Python Edition Solutions

Skills Quiz - Python Edition Solutions 'XNH8QLYHUVLW\ (GPXQG73UDWW-U6FKRRORI(QJLQHHULQJ EGR 103L Fall 2017 Skills Quiz - Python Edition Solutions Michael R. Gustafson II Name (please print): NetID (please print): In keeping with the Community

More information

Mini-Lecture 16. Nested Lists

Mini-Lecture 16. Nested Lists Mini-Lecture 16 Nested Lists Nested Lists Lists can hold any object Lists are themselves objects Therefore lists can hold other lists! a = [2, 1] b = [3, 1] c = [1, 4, b] x = [1, a, c, 5] x[1] x[2] x[2][2]

More information

CS 1301 Exam 2 Fall 2013

CS 1301 Exam 2 Fall 2013 CS 1301 Exam 2 Fall 2013 Name : Section TA: Integrity: By taking this exam, you pledge that this is your work and you have neither given nor received inappropriate help during the taking of this exam in

More information

Introduction to Python

Introduction to Python Introduction to Python EECS 4415 Big Data Systems Tilemachos Pechlivanoglou tipech@eecs.yorku.ca 2 Background Why Python? "Scripting language" Very easy to learn Interactive front-end for C/C++ code Object-oriented

More information

CS Lab 8. Part 1 - Basics of File I/O

CS Lab 8. Part 1 - Basics of File I/O CS 105 - Lab 8 Today, you will be doing a lot with files! We will start with the basics of reading and writing and then expand upon the pixel value work that you did in a previous lab by working on image

More information

Name & Recitation Section:

Name & Recitation Section: Name & Recitation Section: Due Thursday, Jan 13 at 2:10 PM in 34-101. Please print out your code files (homework 3.py, queue.py, and any code you wrote for optional problems), and staple them to the back

More information

Environment Diagrams and Recursion Fall 2017 Discussion 2: September 6, 2017 Solutions. 1 More Environment Diagrams

Environment Diagrams and Recursion Fall 2017 Discussion 2: September 6, 2017 Solutions. 1 More Environment Diagrams CS 61A Environment Diagrams and Recursion Fall 2017 Discussion 2: September 6, 2017 Solutions 1 More Environment Diagrams Recall that an environment diagram keeps track of all the variables that have been

More information

ENVIRONMENT DIAGRAMS AND RECURSION 2

ENVIRONMENT DIAGRAMS AND RECURSION 2 ENVIRONMENT DIAGRAMS AND RECURSION 2 COMPUTER SCIENCE 61A September 8, 2016 1 More Environment Diagrams Recall that an environment diagram keeps track of all the variables that have been defined and the

More information

Lecture #12: Immutable and Mutable Data. Last modified: Mon Feb 22 16:33: CS61A: Lecture #12 1

Lecture #12: Immutable and Mutable Data. Last modified: Mon Feb 22 16:33: CS61A: Lecture #12 1 Lecture #12: Immutable and Mutable Data Last modified: Mon Feb 22 16:33:22 2016 CS61A: Lecture #12 1 Listing Leaves def leaf_labels(tree): """A list of the labels of all leaves in TREE.""" Last modified:

More information

Computer Science 1 CSCI-1100 Spring Semester 2015 Exam 2 Overview and Practice Questions

Computer Science 1 CSCI-1100 Spring Semester 2015 Exam 2 Overview and Practice Questions REMINDERS Computer Science 1 CSCI-1100 Spring Semester 2015 Exam 2 Overview and Practice Questions Exam 2 will be held Monday, April 6, 2015. Most of you will take the test from 6:00-7:50PM in DCC 308.

More information

18.1. CS 102 Unit 18. Python. Mark Redekopp

18.1. CS 102 Unit 18. Python. Mark Redekopp 18.1 CS 102 Unit 18 Python Mark Redekopp 18.2 Credits Many of the examples below are taken from the online Python tutorial at: http://docs.python.org/tutorial/introduction.html 18.3 Python in Context Two

More information

Test #2 October 8, 2015

Test #2 October 8, 2015 CPSC 1040 Name: Test #2 October 8, 2015 Closed notes, closed laptop, calculators OK. Please use a pencil. 100 points, 5 point bonus. Maximum score 105. Weight of each section in parentheses. If you need

More information

python-quirc Documentation

python-quirc Documentation python-quirc Documentation Release 0.8.0 SvartalF May 27, 2012 CONTENTS 1 Install 3 1.1 Requirements............................................... 3 2 Usage 5 2.1 High-level API..............................................

More information

Lecture #11: Immutable and Mutable Data. Last modified: Sun Feb 19 17:03: CS61A: Lecture #11 1

Lecture #11: Immutable and Mutable Data. Last modified: Sun Feb 19 17:03: CS61A: Lecture #11 1 Lecture #11: Immutable and Mutable Data Last modified: Sun Feb 19 17:03:49 2017 CS61A: Lecture #11 1 Building Recursive Structures In Lecture #9, we defined map rlist and filter rlist: def map rlist(f,

More information

Statements 2. a operator= b a = a operator b

Statements 2. a operator= b a = a operator b Statements 2 Outline Note: i=i+1 is a valid statement. Don t confuse it with an equation i==i+1 which is always false for normal numbers. The statement i=i+1 is a very common idiom: it just increments

More information

Module Memory and Data Locality

Module Memory and Data Locality GPU Teaching Kit Accelerated Computing Module 4.5 - Memory and Data Locality Handling Arbitrary Matrix Sizes in Tiled Algorithms Objective To learn to handle arbitrary matrix sizes in tiled matrix multiplication

More information

(f) d={ alchemist :( a, t ), shaman : ( s, n ), wizard : ( w, z )} d[ shaman ][1]

(f) d={ alchemist :( a, t ), shaman : ( s, n ), wizard : ( w, z )} d[ shaman ][1] CSCI1101 Final Exam December 18, 2018 Solutions 1. Determine the value and type of each of the expressions below. If the question has two lines, assume that the statement in the first line is executed,

More information

Python: common syntax

Python: common syntax Lab 09 Python! Python Intro Main Differences from C++: True and False are capitals Python floors (always down) with int division (matters with negatives): -3 / 2 = -2 No variable data types or variable

More information

CSc 110 Sample Midterm Exam #1

CSc 110 Sample Midterm Exam #1 CSc 110 Sample Midterm Exam #1 1. Expressions For each expression in the left-hand column, indicate its value in the right-hand column. Be sure to list a constant of appropriate type (e.g., 7.0 rather

More information

CS240 Fall Mike Lam, Professor. Quick Sort

CS240 Fall Mike Lam, Professor. Quick Sort ??!!!!! CS240 Fall 2015 Mike Lam, Professor Quick Sort Merge Sort Merge sort Sort sublists (divide & conquer) Merge sorted sublists (combine) All the "hard work" is done after recursing Hard to do "in-place"

More information

CS 111X - Spring Final Exam - KEY

CS 111X - Spring Final Exam - KEY CS 111X - Spring 2016 - Final Exam 1/10 Computing ID: CS 111X - Spring 2016 - Final Exam - KEY Name: Computing ID: On my honor as a student, I have neither given nor received unauthorized assistance on

More information

Shell / Python Tutorial. CS279 Autumn 2017 Rishi Bedi

Shell / Python Tutorial. CS279 Autumn 2017 Rishi Bedi Shell / Python Tutorial CS279 Autumn 2017 Rishi Bedi Shell (== console, == terminal, == command prompt) You might also hear it called bash, which is the most widely used shell program macos Windows 10+

More information

Speeding up Python using Cython

Speeding up Python using Cython Speeding up Python using Cython Rolf Boomgaarden Thiemo Gries Florian Letsch Universität Hamburg November 28th, 2013 What is Cython? Compiler, compiles Python-like code to C-code Code is still executed

More information

Midterm Exam. 5. What is the character - (minus) used for in JavaScript? Give as many answers as you can.

Midterm Exam. 5. What is the character - (minus) used for in JavaScript? Give as many answers as you can. First Name Last Name CSCi 90.3 March 23, 2010 Midterm Exam Instructions: For multiple choice questions, circle the letter of the one best choice unless the question explicitly states that it might have

More information

Programming for Engineers in Python. Recitation 10

Programming for Engineers in Python. Recitation 10 Programming for Engineers in Python Recitation 10 Plan Image Processing: Segmentation using Otsu threshold selection method Morphological operators Erosion Dilation Denoising 2 Image Processing in Python

More information

Assignment 1 CSCI 3136: Principles of Programming Languages

Assignment 1 CSCI 3136: Principles of Programming Languages Assignment 1 CSCI 3136: Principles of Programming Languages Due Jan 29, 2018 Assignments are due on the due date before class and have to include this cover page. Plagiarism in assignment answers will

More information

CSCI 135 Exam #0 Fundamentals of Computer Science I Fall 2012

CSCI 135 Exam #0 Fundamentals of Computer Science I Fall 2012 CSCI 135 Exam #0 Fundamentals of Computer Science I Fall 2012 Name: This exam consists of 7 problems on the following 6 pages. You may use your single- side hand- written 8 ½ x 11 note sheet during the

More information

PIC 16, Fall Variables, Dynamically-typed, Mutable, Immutable, Functions. Michael Andrews. October 1, Department of Mathematics UCLA

PIC 16, Fall Variables, Dynamically-typed, Mutable, Immutable, Functions. Michael Andrews. October 1, Department of Mathematics UCLA PIC 16, Fall 2018 Variables, Dynamically-typed, Mutable, Immutable, Functions Michael Andrews Department of Mathematics UCLA October 1, 2018 Office hours reminder M 1:30-2:45pm (Michael) T 1-2pm (Sam),

More information

Midterm I Practice Problems

Midterm I Practice Problems 15-112 Midterm I Practice Problems Name: Section: andrewid: This PRACTICE midterm is not meant to be a perfect representation of the upcoming midterm! You are responsible for knowing all material covered

More information

The while Loop 4/6/16 4

The while Loop 4/6/16 4 Chapter 4: Loops Chapter Goals To implement while and for loops To hand-trace the execution of a program To become familiar with common loop algorithms To understand nested loops To implement programs

More information

Immutable Server Generation. The New App Deployment. AXEL

Immutable Server Generation. The New App Deployment. AXEL Immutable Server Generation The New App Deployment AXEL FONTAINE @axelfontaine axel@boxfuse.com flywaydb.org boxfuse.com about questions POLL: which level of automation are you at? Build Unit Tests Continuous

More information

CS 100 Python commands, computing concepts, and algorithmic approaches for final Fall 2015

CS 100 Python commands, computing concepts, and algorithmic approaches for final Fall 2015 CS 100 Python commands, computing concepts, and algorithmic approaches for final Fall 2015 These pages will NOT BE INCLUDED IN THE MIDTERM. print - Displays a value in the command area - Examples: - print

More information

World and Screen Spaces

World and Screen Spaces 2/2/2005 Lecture 2 3 2/2/2005 Lecture 2 4 World and Screen Spaces Lecture 2 Comp 236 Spring 2005 From last time Our world view seemed rather limited: - - A box ranging from [-,] in x, and [-,] in y Today

More information

Access VBA programming

Access VBA programming Access VBA programming TUTOR: Andy Sekiewicz MOODLE: http://moodle.city.ac.uk/ WEB: www.staff.city.ac.uk/~csathfc/acvba The DoCmd object The DoCmd object is used to code a lot of the bread and butter operations

More information

24. Sorting a List. Topics: Selection Sort. Merge Sort

24. Sorting a List. Topics: Selection Sort. Merge Sort 24. Sorting a List Topics: Selection Sort Merge Sort Our examples will highlight the interplay between functions and lists Sorting a List of Numbers Before: x --> 50 40 10 80 20 60 After: x --> 10 20 40

More information

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression Chapter 1 Summary Comments are indicated by a hash sign # (also known as the pound or number sign). Text to the right of the hash sign is ignored. (But, hash loses its special meaning if it is part of

More information

Lab 2: Booleans, Strings, Random Numbers, Recursion, Variables, Input function

Lab 2: Booleans, Strings, Random Numbers, Recursion, Variables, Input function Lab 2: Booleans, Strings, Random Numbers, Recursion, Variables, Input function Due: Mar25 (Note that this is a 2-week lab) This lab must be done using paired partners. You should choose a different partner

More information

Tool-assisted spec development

Tool-assisted spec development Typed Clojure Tool-assisted spec development Ambrose Bonnaire-Sergeant Sam Tobin-Hochstadt Spec is awesome Expressive specification language Runtime instrumentation Generative testing Documentation Parsing

More information

CPSC 217 Midterm (Python 3 version)

CPSC 217 Midterm (Python 3 version) CPSC 217 Midterm (Python 3 version) Duration: 60 minutes 7 March 2011 This exam has 81 questions and 14 pages. This exam is closed book. No notes, books, calculators or electronic devices, or other assistance

More information

STEAM Clown & Productions Copyright 2017 STEAM Clown. Page 1

STEAM Clown & Productions Copyright 2017 STEAM Clown. Page 1 What to add next time you are updating these slides Update slides to have more animation in the bullet lists Verify that each slide has stand alone speaker notes Page 1 Python 3 Running The Python Interpreter

More information

Binary Search APRIL 25 TH, 2014

Binary Search APRIL 25 TH, 2014 Binary Search APRIL 25 TH, 2014 The Search Problem One of the most common computational problems (along with sorting) is searching. In its simplest form, the input to the search problem is a list L and

More information

List comprehensions (and other shortcuts) UW CSE 160 Spring 2015

List comprehensions (and other shortcuts) UW CSE 160 Spring 2015 List comprehensions (and other shortcuts) UW CSE 160 Spring 2015 Three Ways to Define a List Explicitly write out the whole thing: squares = [0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100] Write a loop to create

More information

EE 355 Unit 17. Python. Mark Redekopp

EE 355 Unit 17. Python. Mark Redekopp 1 EE 355 Unit 17 Python Mark Redekopp 2 Credits Many of the examples below are taken from the online Python tutorial at: http://docs.python.org/tutorial/introduction.html 3 Python in Context Interpreted,

More information

CS Introduction to Computational and Data Science. Instructor: Renzhi Cao Computer Science Department Pacific Lutheran University Spring 2017

CS Introduction to Computational and Data Science. Instructor: Renzhi Cao Computer Science Department Pacific Lutheran University Spring 2017 CS 133 - Introduction to Computational and Data Science Instructor: Renzhi Cao Computer Science Department Pacific Lutheran University Spring 2017 Introduction to Python II In the previous class, you have

More information

All program statements you write should be syntactically correct. Partial credit is not guaranteed with incorrect use of syntax.

All program statements you write should be syntactically correct. Partial credit is not guaranteed with incorrect use of syntax. With Solutions in Red CS110 Introduction to Computing Fall 2012 Section 2 Exam 1 This is an open notes exam. Computers are not permitted. Your work on this exam must be your own. Answer all questions in

More information

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

THE AUSTRALIAN NATIONAL UNIVERSITY Mid Semester Examination September COMP1730 / COMP6730 Programming for Scientists THE AUSTRALIAN NATIONAL UNIVERSITY Mid Semester Examination September 2016 COMP1730 / COMP6730 Programming for Scientists Study Period: 15 minutes Time Allowed: 2 hours Permitted Materials: One A4 page

More information

CS 1110 Final, December 17th, Question Points Score Total: 100

CS 1110 Final, December 17th, Question Points Score Total: 100 CS 1110 Final, December 17th, 2014 This 150-minute exam has 8 questions worth a total of 100 points. Scan the whole test before starting. Budget your time wisely. Use the back of the pages if you need

More information

RECURSION, RECURSION, (TREE) RECURSION! 3

RECURSION, RECURSION, (TREE) RECURSION! 3 RECURSION, RECURSION, (TREE) RECURSION! 3 COMPUTER SCIENCE 61A September 18, 2013 A function is recursive if it calls itself. Below is recursive factorial function. def factorial(n): if n == 0 or n ==

More information

Python a modern scripting PL. Python

Python a modern scripting PL. Python Python a modern scripting PL Basic statements Basic data types & their operations Strings, lists, tuples, dictionaries, files Functions Strings Dictionaries Many examples originally from O Reilly Learning

More information

Absent: Lecture 3 Page 1. def foo(a, b): a = 5 b[0] = 99

Absent: Lecture 3 Page 1. def foo(a, b): a = 5 b[0] = 99 1. A function is a procedural abstract (a named body of code to perform some action and return a resulting value). The syntax of a function definition is: def functionname([parameter [, parameter]*]):

More information

CSCE 110: Programming I

CSCE 110: Programming I CSCE 110: Programming I Sample Questions for Exam #1 February 17, 2013 Below are sample questions to help you prepare for Exam #1. Make sure you can solve all of these problems by hand. For most of the

More information

Python I. Some material adapted from Upenn cmpe391 slides and other sources

Python I. Some material adapted from Upenn cmpe391 slides and other sources Python I Some material adapted from Upenn cmpe391 slides and other sources Overview Names & Assignment Data types Sequences types: Lists, Tuples, and Strings Mutability Understanding Reference Semantics

More information

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]

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] 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.

More information

This quiz is open book and open notes, but do not use a computer.

This quiz is open book and open notes, but do not use a computer. 1. /15 2. /10 3. /10 4. /18 5. /8 6. /13 7. /15 8. /9 9. /1 10. /1 Total /100 This quiz is open book and open notes, but do not use a computer. Please write your name on the top of each page. Answer all

More information

django-report-tools Documentation

django-report-tools Documentation django-report-tools Documentation Release 0.2.1 Evan Brumley Jul 20, 2017 Contents 1 Contents 3 1.1 Getting Started.............................................. 3 1.2 Charts...................................................

More information

COMP101: Final Review. With your boy(s), Mason and San

COMP101: Final Review. With your boy(s), Mason and San COMP101: Final Review With your boy(s), Mason and San COMP101 Happenings The COMP 101 final exam is still scheduled for tomorrow (December 12) at 12 pm in Genome Sciences Bldg. Seating assignments will

More information

Modularity and Reusability I. Functions and code reuse

Modularity and Reusability I. Functions and code reuse Modularity and Reusability I Functions and code reuse Copyright 2006 2009 Stewart Weiss On being efficient When you realize that a piece of Perl code that you wrote may be useful in future programs, you

More information

Guide - The limitations in screen layout using the Item Placement Tool

Guide - The limitations in screen layout using the Item Placement Tool Guide - The limitations in screen layout using the Item Placement Tool 1/8 Guide - The limitations in screen layout using the Item Placement Tool I the B1 Usability Package we have the Item Placement Tool

More information

CSCI-1200 Computer Science II Spring 2006 Lecture 10 Recursion Examples

CSCI-1200 Computer Science II Spring 2006 Lecture 10 Recursion Examples CSCI-1200 Computer Science II Spring 2006 Lecture 10 Recursion Examples Review from Lecture 9 Recursive definitions and C++ functions The mechanism of recursion using activation records Recursion vs. iteration

More information

More Loop Examples Functions and Parameters

More Loop Examples Functions and Parameters More Loop Eamples Functions and Parameters Eample: min difference Given two of numbers, compute the minimum difference among any pair of numbers, one from each. E.g., 1 = [1, 2, 3, 4], 2 = [-2, 10, 5,

More information

STA141C: Big Data & High Performance Statistical Computing

STA141C: Big Data & High Performance Statistical Computing STA141C: Big Data & High Performance Statistical Computing Lecture 3: Background in Algorithms Cho-Jui Hsieh UC Davis April 13, 2017 Time Complexity Analysis Time Complexity There are always many ways

More information

Lecture 14. Nested Lists and Dictionaries

Lecture 14. Nested Lists and Dictionaries Lecture 14 Nested Lists and Dictionaries Announcements for This Lecture Readings Today: Chapter 11 Next Week: Sec. 5.8-5.10 Prelim, Oct 12 th 7:30-9:00 Material up to TUESDAY Study guide is posted Review

More information

STA141C: Big Data & High Performance Statistical Computing

STA141C: Big Data & High Performance Statistical Computing STA141C: Big Data & High Performance Statistical Computing Lecture 2: Background in Algorithms Cho-Jui Hsieh UC Davis April 5/April 10, 2017 Time Complexity Analysis Time Complexity There are always many

More information

Lists. Lists Element Types. Creating Lists. CS 112 Lists Part II 2/22/09. Dan Fleck Spring 2009 George Mason University

Lists. Lists Element Types. Creating Lists. CS 112 Lists Part II 2/22/09. Dan Fleck Spring 2009 George Mason University Lists CS 112 Lists Part II Dan Fleck Spring 2009 George Mason University One of the sequence data types (tuples, strings, lists) Sequence: indexed from 0 to len(thelist) 1 Mutable: Able to change internal

More information

A GUI-Builder Approach to grid Graphics

A GUI-Builder Approach to grid Graphics A GUI-Builder Approach to grid Graphics Paul Murrell April 26, 2018 Grid contains a lot of support for locating, sizing, and arranging graphical components on a device and with respect to each other. However,

More information

Lessons on Python Functions

Lessons on Python Functions Lessons on Python Functions Walter Didimo [ 90 minutes ] Functions When you write a program, you may need to recall a certain block of instructions several times throughout your code A function is a block

More information

Assignment 7: functions and closure conversion

Assignment 7: functions and closure conversion Assignment 7: functions and closure conversion ECEN 4553 & 5013, CSCI 4555 & 5525 Prof. Jeremy G. Siek October 20, 2007 The main ideas for this week are: first-class functions lexical scoping of variables

More information

CSCI 4210 Operating Systems CSCI 6140 Computer Operating Systems Homework 3 (document version 1.2) Multi-threading in C using Pthreads

CSCI 4210 Operating Systems CSCI 6140 Computer Operating Systems Homework 3 (document version 1.2) Multi-threading in C using Pthreads CSCI 4210 Operating Systems CSCI 6140 Computer Operating Systems Homework 3 (document version 1.2) Multi-threading in C using Pthreads Overview This homework is due by 11:59:59 PM on Tuesday, April 10,

More information

All written answers are limited to their question boxes. Make sure all answers are easily legible.

All written answers are limited to their question boxes. Make sure all answers are easily legible. All written answers are limited to their question boxes. Make sure all answers are easily legible. 1. (1 point) Print your name and email id. 2. (2 points) What makes functions so important? Ability to

More information

Introduction to Computer Science I Spring 2010 Sample mid-term exam Answer key

Introduction to Computer Science I Spring 2010 Sample mid-term exam Answer key Introduction to Computer Science I Spring 2010 Sample mid-term exam Answer key 1. [Question:] (15 points) Consider the code fragment below. Mark each location where an automatic cast will occur. Also find

More information

Multiple Choice Questions (20 questions * 6 points per question = 120 points)

Multiple Choice Questions (20 questions * 6 points per question = 120 points) EECS 183 Fall 2014 Exam 2 Closed Book Minimal Notes Closed Electronic Devices Closed Neighbor Turn off Your Cell Phones We will confiscate all electronic devices that we see including cell phones, calculators,

More information

CSCI 101 Midterm Sample Questions

CSCI 101 Midterm Sample Questions CSCI 101 Midterm Sample Questions Note: you may bring one 8.5"x11" double-sided sheet of notes for your use during the exam (handwritten or typed). Otherwise, no notes, computers, calculators, phones or

More information

CSCI-1200 Data Structures Fall 2017 Test 1 Solutions

CSCI-1200 Data Structures Fall 2017 Test 1 Solutions CSCI-1200 Data Structures Fall 2017 Test 1 Solutions 1 Searching for Symbols in ASCII Art [ /24] In this problem we will search a large ASCII Art canvas for matches to a target pattern. For example, given

More information

Worksheet 6: Basic Methods Methods The Format Method Formatting Floats Formatting Different Types Formatting Keywords

Worksheet 6: Basic Methods Methods The Format Method Formatting Floats Formatting Different Types Formatting Keywords Worksheet 1: Introductory Exercises Turtle Programming Calculations The Print Function Comments Syntax Semantics Strings Concatenation Quotation Marks Types Variables Restrictions on Variable Names Long

More information

Last Name: First: Netid: Section. CS 1110 Final, December 17th, 2014

Last Name: First: Netid: Section. CS 1110 Final, December 17th, 2014 CS 0 Final, December 7th, 204 SOLUTION This 50-minute exam has 8 questions worth a total of 00 points. Scan the whole test before starting. Budget your time wisely. Use the back of the pages if you need

More information

Welcome to CS61A! Last modified: Thu Jan 23 03:58: CS61A: Lecture #1 1

Welcome to CS61A! Last modified: Thu Jan 23 03:58: CS61A: Lecture #1 1 Welcome to CS61A! This is a course about programming, which is the art and science of constructing artifacts ( programs ) that perform computations or interact with the physical world. To do this, we have

More information

L1/L2 NETWORK PROTOCOL TESTING

L1/L2 NETWORK PROTOCOL TESTING L1/L2 NETWORK PROTOCOL TESTING MODULE 1 : BASIC OF NETWORKING OSI Model TCP/IP Layers Service data unit & protocol data unit Protocols and standards Network What is network & Internet Network core circuit

More information

CS 303E Fall 2011 Exam 2 Solutions and Criteria November 2, Good Luck!

CS 303E Fall 2011 Exam 2 Solutions and Criteria November 2, Good Luck! CS 303E Fall 2011 Exam 2 Solutions and Criteria November 2, 2011 Name: EID: Section Number: Friday discussion time (circle one): 9-10 10-11 11-12 12-1 2-3 Friday discussion TA(circle one): Wei Ashley Answer

More information

DM550/DM857 Introduction to Programming. Peter Schneider-Kamp

DM550/DM857 Introduction to Programming. Peter Schneider-Kamp DM550/DM857 Introduction to Programming Peter Schneider-Kamp petersk@imada.sdu.dk http://imada.sdu.dk/~petersk/dm550/ http://imada.sdu.dk/~petersk/dm857/ TUPLES 2 Tuples as Immutable Sequences tuple =

More information

Prof. Noah Snavely CS Administrivia. A4 due on Friday (please sign up for demo slots)

Prof. Noah Snavely CS Administrivia. A4 due on Friday (please sign up for demo slots) Robust fitting Prof. Noah Snavely CS111 http://www.cs.cornell.edu/courses/cs111 Administrivia A due on Friday (please sign up for demo slots) A5 will be out soon Prelim is coming up, Tuesday, / Roadmap

More information

Short Introduction to Python Machine Learning Course Laboratory

Short Introduction to Python Machine Learning Course Laboratory Pattern Recognition and Applications Lab Short Introduction to Python Machine Learning Course Laboratory Battista Biggio battista.biggio@diee.unica.it Luca Didaci didaci@diee.unica.it Dept. Of Electrical

More information

Teaching London Computing

Teaching London Computing Teaching London Computing A Level Computer Science Topic 3: Advanced Programming in Python William Marsh School of Electronic Engineering and Computer Science Queen Mary University of London Aims Further

More information

Collections and Combinatorial Search

Collections and Combinatorial Search Streams Collections and Combinatorial Search We ve seen a number of immutable collections that provide powerful operations, in particular for combinatorial search. For instance, to find the second prime

More information

CS 61A Higher Order Functions and Recursion Fall 2018 Discussion 2: June 26, Higher Order Functions. HOFs in Environment Diagrams

CS 61A Higher Order Functions and Recursion Fall 2018 Discussion 2: June 26, Higher Order Functions. HOFs in Environment Diagrams CS 61A Higher Order Functions and Recursion Fall 2018 Discussion 2: June 26, 2018 1 Higher Order Functions HOFs in Environment Diagrams Recall that an environment diagram keeps track of all the variables

More information

CS216: Problem Set 1: Sequence Alignment

CS216: Problem Set 1: Sequence Alignment 1 of 5 1/18/2006 8:45 AM University of Virginia Computer Science CS216: Program and Data Representation, Spring 2006 Problem Set 1 Sequence Alignment 18 January 2006 Out: 18 January Due: Monday, 23 January

More information

Outline. tallying the votes global and local variables call by value or call by reference. of variable length using keywords for optional arguments

Outline. tallying the votes global and local variables call by value or call by reference. of variable length using keywords for optional arguments Outline 1 Histograms tallying the votes global and local variables call by value or call by reference 2 Arguments of Functions of variable length using keywords for optional arguments 3 Functions using

More information

CSCI 111 Midterm 1, version A Exam Fall Solutions 09.00am 09.50am, Tuesday, October 13, 2015

CSCI 111 Midterm 1, version A Exam Fall Solutions 09.00am 09.50am, Tuesday, October 13, 2015 QUEENS COLLEGE Department of Computer Science CSCI 111 Midterm 1, version A Exam Fall 2015 10.13.15 Solutions 09.00am 09.50am, Tuesday, October 13, 2015 Problem 1 Write a complete C++ program that does

More information

CSI33 Data Structures

CSI33 Data Structures Outline Department of Mathematics and Computer Science Bronx Community College October 10, 2018 Outline Outline 1 Chapter 6: Recursion Outline Chapter 6: Recursion 1 Chapter 6: Recursion Chapter 6: Recursion

More information

Chapter 2 Writing Simple Programs

Chapter 2 Writing Simple Programs Chapter 2 Writing Simple Programs Charles Severance Textbook: Python Programming: An Introduction to Computer Science, John Zelle (www.si182.com) Software Development Process Figure out the problem - for

More information

HIGHER-ORDER FUNCTIONS 2

HIGHER-ORDER FUNCTIONS 2 HIGHER-ORDER FUNCTIONS 2 COMPUTER SCIENCE 61A June 28, 2016 1 Higher-Order Functions A higher order function (HOF) is a function that manipulates other functions by taking in functions as arguments, returning

More information

ESC101 : Fundamental of Computing

ESC101 : Fundamental of Computing ESC101 : Fundamental of Computing End Semester Exam 19 November 2008 Name : Roll No. : Section : Note : Read the instructions carefully 1. You will lose 3 marks if you forget to write your name, roll number,

More information

"Good" vs. "Bad" Expressions. ; interp-expr FAE... -> FAE-Value

Good vs. Bad Expressions. ; interp-expr FAE... -> FAE-Value "Good" vs. "Bad" Expressions ; interp-expr FAE... -> FAE-Value 1 "Good" vs. "Bad" Expressions ; interp-expr FAE... -> FAE-Value Does interp-expr produce a value for all expressions? 2 "Good" vs. "Bad"

More information

CS 234 Python Review Part 2

CS 234 Python Review Part 2 CS 234 Python Review Part 2 Recap import function: define, return boolean, conditional, branching loop: for, range, while file: open, close, readlines string: split Classes Define blueprint for a custom

More information

MEIN 50010: Python Data Structures

MEIN 50010: Python Data Structures : Python Data Structures Fabian Sievers Higgins Lab, Conway Institute University College Dublin Wednesday, 2017-10-18 Data Structures Stacks, Queues & Deques Structures Data structures are a way of storing

More information