Introduction to Computer Programming for Non-Majors

Size: px
Start display at page:

Download "Introduction to Computer Programming for Non-Majors"

Transcription

1 Introduction to Computer Programming for Non-Majors CSC 2301, Fall 2016 Review Chap Instructor: Long Ma The Department of Computer Science

2 Chapter 11 Data Collections understand the use of lists (arrays) to represent a collection of related data. be familiar with the functions and methods available for manipulating Python lists. write programs that use lists to manage a collection of information. -2-

3 Example Problem: Simple Statistics Many programs deal with large collections of similar information. Words in a document Students in a course Data from an experiment Customers of a business Graphics objects drawn on the screen Cards in a deck -3-

4 Lists and Arrays Python lists are ordered sequences of items. For instance, a sequence of n numbers might be called S: S = s 0, s 1, s 2, s 3,, s n-1 Specific values in the sequence can be referenced using subscripts. -4-

5 Lists and Arrays Suppose the sequence is stored in a variable s. We could write a loop to calculate the sum of the items in the sequence like this: sum = 0 for i in range(n): sum = sum + s[i] Almost all computer languages have a sequence structure like this, sometimes called an array. -5-

6 Lists and Arrays A list or array is a sequence of items where the entire sequence is referred to by a single name (i.e. s) and individual items can be selected by indexing (i.e. s[i]). In other programming languages, arrays are generally a fixed size, meaning that when you create the array, you have to specify how many items it can hold. e.g. lst = [None] * 5 e.g. x = numpy.zeros((3,4)) Arrays are generally also homogeneous, meaning they can hold only one data type. a = numpy.ndarray((5,),int) -6-

7 Lists and Arrays Python lists are dynamic. They can grow and shrink on demand. Python lists are also heterogeneous, a single list can hold arbitrary data types. Python lists are mutable sequences of arbitrary objects. -7-

8 Sequence Operations, also can be applied to List Operator <seq> + <seq> <seq> * <int-expr> <seq>[] len(<seq>) <seq>[:] for <var> in <seq>: <expr> in <seq> Meaning Concatenation Repetition Indexing Length Slicing Iteration Membership (Boolean) -8-

9 List Operations The membership operation can be used to see if a certain value appears anywhere in a sequence. >>> lst = [1,2,3,4] >>> 3 in lst True The summing example from earlier can be written like this: sum = 0 for x in s: sum = sum + x -9-

10 List Operations Unlike strings, lists are mutable: >>> lst = [1,2,3,4] >>> lst[3] 4 >>> lst[3] = "Hello >>> lst [1, 2, 3, 'Hello'] >>> lst[2] = 7 >>> lst [1, 2, 7, 'Hello'] A list of identical items can be created using the repetition operator. This command produces a list containing 50 zeroes: zeroes = [0] *

11 List Operations Lists are often built up one piece at a time using append. nums = [] x = eval(input('enter a number: ')) while x >= 0: nums.append(x) x = eval(input('enter a number: ')) Here, nums is being used as an accumulator, starting out empty, and each time through the loop a new value is tacked on. -11-

12 List Operations Method <list>.append(x) <list>.sort() <list>.reverse() Meaning Add element x to end of list. Sort (order) the list. A comparison function may be passed as a parameter. Reverse the list. <list>.index(x) Returns index of first occurrence of x. <list>.insert(i, x) Insert x into list at index i. <list>.count(x) <list>.remove(x) <list>.pop(i) Returns the number of occurrences of x in list. Deletes the first occurrence of x in list. Deletes the ith element of the list and returns its value. -12-

13 List Operations >>> lst = [3, 1, 4, 1, 5, 9] >>> lst.append(2) >>> lst [3, 1, 4, 1, 5, 9, 2] >>> lst.sort() >>> lst [1, 1, 2, 3, 4, 5, 9] >>> lst.reverse() >>> lst [9, 5, 4, 3, 2, 1, 1] >>> lst.index(4) 2 >>> lst.insert(4, "Hello") >>> lst [9, 5, 4, 3, 'Hello', 2, 1, 1] >>> lst.count(1)s 2 >>> lst.remove(1) >>> lst [9, 5, 4, 3, 'Hello', 2, 1] >>> lst.pop(3) 3 >>> lst [9, 5, 4, 'Hello', 2, 1] -13-

14 List Operations Most of these methods don t return a value they change the contents of the list in some way. Lists can grow by appending new items, and shrink when items are deleted. Individual items or entire slices can be removed from a list using the del operator. del isn t a list method, but a built-in operation that can be used on list items. -14-

15 List Operations >>> mylist=[34, 26, 0, 10] >>> del mylist[1] >>> mylist [34, 0, 10] >>> del mylist[1:3] >>> mylist [34] >>> li = [1,2,3,3] >>> del(li) >>> li Traceback (most recent call last): File "<stdin>", line 1, in <module>nameerror: name 'li' is not defined >>> -15-

16 List Operations Basic list principles: A list is a sequence of items stored as a single object. Items in a list can be accessed by indexing, and sublists can be accessed by slicing. Lists are mutable; individual items or entire slices can be replaced through assignment statements. Lists support a number of convenient and frequently used methods. Lists will grow and shrink as needed. -16-

17 Lists of Objects All of the list examples we ve looked at so far have involved simple data types like numbers and strings. We can also use lists to store more complex data types, like our student information from chap.10. Our grade processing program read through a file of student grade information and then printed out information about the student with the highest GPA. A common operation on data like this is to sort it, perhaps alphabetically, perhaps by credit-hours, or even by GPA. -17-

18 Lists of Objects Let s write a program that sorts students according to GPA using our Sutdent class from the last chapter. Get the name of the input file from the user Read student information into a list Sort the list by GPA Get the name of the output file from the user Write the student information from the list into a file -18-

19 Lists of Objects Let s begin with the file processing. The following code reads through the data file and creates a list of students. def readstudents(filename): infile = open(filename, 'r') students = [] for line in infile: students.append(makestudent(line)) infile.close() return students We re using the makestudent from the gpa program, so we ll need to remember to import it. -19-

20 Lists of Objects Let s also write a function to write the list of students back to a file. Each line should contain three pieces of information, separated by tabs: name, credit hours, and quality points. def writestudents(students, filename): # students is a list of Student objects outfile = open(filename, 'w') for s in students: print((s.getname(),s.gethours(),s.getqpoints(), sep="\t", file=outfile) outfile.close() -20-

21 Lists of Objects Using the functions readstudents and writestudents, we can convert our data file into a list of students and then write them back to a file. All we need to do now is sort the records by GPA. In the statistics program, we used the sort method to sort a list of numbers. How does Python sort lists of objects? -21-

22 Lists of Objects To make sorting work with our objects, we need to tell sort how the objects should be compared. Can supply a function to produce the key for an object using: <list>.sort(key=<somefunc>) To sort by GPA, we need a function that takes a Student as parameter and returns the student's GPA. def use_gpa(astudent): return astudent.gpa() -22-

23 Lists of Objects We can now sort the data by calling sort with the key function as a keyword parameter. data.sort(key=use_gpa) Notice that we didn t put () s after the function name. This is because we don t want to call use_gpa, but rather, we want to send use_gpa to the sort method. -23-

24 Lists of Objects Actually, defining use_gpa was unnecessary. The gpa method in the Student class is a function that takes a student as a parameter (formally, self) and returns GPA. Can use it: data.sort(key=student.gpa) -24-

25 Lists of Objects # gpasort.py # A program to sort student information into GPA order. from gpa import Student, makestudent def readstudents(filename): infile = open(filename, 'r') students = [] for line in infile: students.append(makestudent(line)) infile.close() return students def main(): print ("This program sorts student grade information by GPA") filename = input("enter the name of the data file: ") data = readstudents(filename) data.sort(student.gpa) filename = input("enter a name for the output file: ") writestudents(data, filename) print("the data has been written to", filename) if name == ' main ': main() def writestudents(students, filename): outfile = open(filename, 'w') for s in students: print(s.getname(), s.gethours(), s.getqpoints(), sep="\t", file=outfile) outfile.close() -25-

26 Chap.12 Objectives To understand the process of object-oriented design. To be able to read and understand object-oriented programs. To understand the concepts of encapsulation, polymorphism and inheritance as they pertain to object-oriented design and programming. -26-

27 The Process of OOD Most modern computer applications are designed using a data-centered view of computing called objectoriented design (OOD). The essence of OOD is describing a system in terms of black boxes and their interfaces. -27-

28 The Process of OOD The component providing the service should NOT have to consider how the service is used This separation of concerns makes the design of complex systems possible. In top-down design, functions serve the role of the black box. Client programs can use the functions as long as it understands what the function does. How the function accomplishes its task is encapsulated within the function. -28-

29 The Process of OOD In OOD, the black boxes are objects. The magic behind the objects is in the class definitions. Once a class definition is written, we can ignore how the class works and rely on the external interface, its methods. We ve seen this when using the graphics library we were able to draw a circle without having to know any of the nitty-gritty details encapsulated in class definitions for GraphWin and Circle. -29-

30 The Process of OOD Breaking a large problem into a set of cooperating classes reduces the complexity. Each class stands on its own! OOD is the process of finding and defining a useful set of classes for a given problem. -30-

31 The Process of OOD Here are some guidelines for OOD: Look for object candidates Define a set of objects that will be helpful in solving the problem. Start with a consideration of the problem statement objects are usually described by nouns. Identify instance variables Once you think of some possible objects, think of the kinds of information each object will need to do its job. Some object attributes will have primitive data types(string, number), while others may be complex types that suggest other useful objects/classes. -31-

32 The Process of OOD Think about interfaces Consider the verbs in the problem statement; they describe actions to be done. List the methods that the class will require. Remember all of the manipulation of the object s data should be done through the methods you provide. -32-

33 The Process of OOD Design iteratively Bounce back and forth between designing new classes and adding methods to existing classes. Make progress wherever progress needs to be made. -33-

34 The Process of OOD Refine the nontrivial methods Use top-down design and stepwise refinement to flesh out the details of the more difficult methods. As you re programming, you may discover that some new interactions with other classes are needed, and you may need to add new methods to other classes. Sometimes you may discover a need for a brand-new kind of object that calls for the definition of another class. -34-

35 The Process of OOD Try out alternatives Good design involves a lot of trial and error! Well-designed programs are not the result of a first try. Keep it simple stupid At each step in the design, try to find the simplest approach that will solve the problem. Don t design in extra complexity until it is clear that a more complex approach is absolutely necessary. -35-

36 Object Oriented (OO) Concepts The OO approach helps us to produce complex software that is more reliable and cost-effective. OO is comprised of three principles: Encapsulation Polymorphism Inheritance -36-

37 Encapsulation As you ll recall, objects combine data and operations. This packaging of data with a set of operations that can be performed on the data is called encapsulation. Encapsulation provides a convenient way to compose complex problems that corresponds to our intuitive view of how the world works world is made up of interacting objects. -37-

38 Encapsulation From a design standpoint, encapsulation separates the concerns of what vs. how. The implementation of an object is independent of its use. The implementation can change, but as long as the interface is preserved, the object will not break. Encapsulation allows us to isolate major design decisions, especially ones subject to change. -38-

39 Encapsulation Another advantage is that it promotes code reuse. It allows to package up general components that can be used from one program to the next. The DieView and Button classes are good examples of this. Encapsulation alone makes a system object-based. To be object-oriented, we must also have the properties of polymorphism and inheritance. -39-

40 Polymorphism Literally, polymorphism means many forms. What an object does in response to a message (a method call) depends on the type or class of the object. With polymorphism, a given line in a program may invoke a completely different method from one moment to the next. Suppose you had a list of graphics objects to draw on the screen a mixture of Circle, Rectangle, Polygon, etc. -40-

41 Polymorphism You could draw all the items with this simple code: for obj in objects: obj.draw(win) When obj is a circle, it executes the draw method from the circle class, then from rectangle class etc. Polymorphism gives object-oriented systems the flexibility for each object to perform an action just the way that it should be performed for that object. -41-

42 Inheritance The idea behind inheritance is that a new class can be defined to borrow behavior from another class. The new class (the one doing the borrowing) is called a subclass, and the other (the one being borrowed from) is called a superclass. This is an idea our examples have not included. -42-

43 Inheritance Say we re building an employee management system. We might have a class called Employee that contains general information common to all employees. There might be a method called homeaddress that returns an employee s home address. -43-

44 Inheritance Each subclass could have its own monthlypay function, since pay is computed differently for each class of employee. Inheritance has two benefits: We can structure the classes of a system to avoid duplication of operations, e.g. there is one homeaddress method for HourlyEmployee and SalariedEmployee. New classes can be based on existing classes, promoting code reuse. -44-

45 Inheritance We could have used inheritance to build the DieView class. Our first DieView class did not provide a way to change the appearance of the die. Rather than modifying the original class definition, we could have left the original alone and created a new subclass called ColorDieView. -45-

46 Inheritance A ColorDieView is just like DieView, except it has an additional method! class ColorDieView(DieView): def setvalue(self, value): self.value = value DieView.setValue(self, value) def setcolor(self, color): self.foreground = color self.setvalue(self.value) -46-

47 Inheritance The first line (class ColorDieView(DieView): ) says that we are defining a new class ColorDieView that is based on (i.e. is a subclass of) DieView. Inside the new class we define two methods. The second method, setcolor, adds the new operation. To make it work, setvalue also needed to be slightly modified. -47-

48 Inheritance The setvalue method in ColorDieView redefines or overrides the definition of setvalue that was provided in the DieView class. The setvalue method in the new class first stores the value and then relies on the setvalue method of the superclass DieView to actually draw the pips. -48-

49 Inheritance The normal approach to set the value, self.setvalue(value), would refer to the setvalue method of the ColorDieView class, since self is an instance of ColorDieView. To call the superclass s setvalue method, it s necessary to put the class name where the object would normally go: DieView.setValue(self,value) -49-

50 Inheritance DieView.setValue(self,value) The actual object to which the method is applied is sent as the first parameter. -50-

51 Inheritance class Person(object): pass class Child(Person): pass May = Child() Peter = Person() print(isinstance(may,person)) print(isinstance(peter,child)) print(issubclass(child,person)) # True # False # True -51-

52 Inheritance class Person(object): def init (self,name,sex): self.name = name self.sex = sex def print_title(self): if self.sex == "male": print("man") elif self.sex == "female": print("woman") class Child(Person): Pass May = Child("May","female") Peter =Person("Peter","male") print(may.name,may.sex, Peter.name,Peter.sex) May.print_title() Peter.print_title() -52-

53 Inheritance & polymorphism class Animal: def init (self, name): # Constructor of the class self.name = name def talk(self): # Abstract method, defined by convention only raise NotImplementedError("Subclass must implement abstract method") class Cat(Animal): def talk(self): return 'Meow!' class Dog(Animal): def talk(self): return 'Woof! Woof!' animals = [Cat('Missy'), Cat('Mr.Mistoffelees'), Dog('Lassie')] for animal in animals: print animal.name + ': ' + animal.talk() # prints the following: # Missy: Meow! # Mr. Mistoffelees: Meow! # Lassie: Woof! Woof! -53-

54 Questions Thank You!

Introduction to Computer Programming for Non-Majors

Introduction to Computer Programming for Non-Majors Introduction to Computer Programming for Non-Majors CSC 2301, Fall 2016 Chapter 11 Part 1 Instructor: Long Ma The Department of Computer Science Chapter 11 Data Collections Objectives: To understand the

More information

Introduction to Computer Programming for Non-Majors

Introduction to Computer Programming for Non-Majors Introduction to Computer Programming for Non-Majors CSC 2301, Fall 2015 Chapter 11 Part 1 The Department of Computer Science Objectives Chapter 11 Data Collections To understand the use of lists (arrays)

More information

Introduction to Computer Programming for Non-Majors

Introduction to Computer Programming for Non-Majors Introduction to Computer Programming for Non-Majors CSC 2301, Fall 2015 Chapter 12 Object-Oriented Design The Department of Computer Science Objectives To understand the process of object-oriented design.

More information

Introduction to Computer Programming for Non-Majors

Introduction to Computer Programming for Non-Majors Introduction to Computer Programming for Non-Majors CSC 2301, Fall 2014 Chapter 12 Object-Oriented Design The Department of Computer Science Objectives To understand the process of object-oriented design.

More information

Introduction to Computer Programming for Non-Majors

Introduction to Computer Programming for Non-Majors Introduction to Computer Programming for Non-Majors CSC 2301, Fall 2014 Chapter 10 Part 3 & Chapter 11 Part 1 The Department of Computer Science Widgets One very common use of objects is in the design

More information

Lecture Data Collections. Richard E Sarkis CSC 161: The Art of Programming

Lecture Data Collections. Richard E Sarkis CSC 161: The Art of Programming Lecture Data Collections Richard E Sarkis CSC 161: The Art of Programming Class Administrivia Agenda To understand the use of lists (arrays) to represent a collection of related data. To be familiar with

More information

Object-oriented design

Object-oriented design Object-oriented design Michael Mandel Lecture 11 Methods in Computational Linguistics I The City University of New York, Graduate Center https://github.com/ling78100/lectureexamples/blob/master/lecture11final.ipynb

More information

List OperaYons. Python Programming, 2/e 2

List OperaYons. Python Programming, 2/e 2 People s Daily With today s announcement, Kim joins the ranks of The Onion s prior Sexiest Man Alive winners, including: 2011: Bashar al- Assad 2010: Bernie Madoff 2009: Charles and David Koch (co- winners)

More information

Outline: Data collections (Ch11)

Outline: Data collections (Ch11) Data collections Michael Mandel Lecture 9 Methods in Computational Linguistics I The City University of New York, Graduate Center https://github.com/ling78100/lectureexamples/blob/master/lecture09final.ipynb

More information

Introduction to Computer Programming for Non-Majors

Introduction to Computer Programming for Non-Majors Introduction to Computer Programming for Non-Majors CSC 2301, Fall 2016 Chapter 10 Part 1 Instructor: Long Ma The Department of Computer Science Top-Down Design 2 In top-down design, a complex problem

More information

Lecture Object-Oriented Design. Richard E Sarkis CSC 161: The Art of Programming

Lecture Object-Oriented Design. Richard E Sarkis CSC 161: The Art of Programming Lecture Object-Oriented Design Richard E Sarkis CSC 161: The Art of Programming Class Administrivia Objectives To understand the process of object-oriented design To be able to read and understand object-oriented

More information

Introduction to Python

Introduction to Python Introduction to Python Reading assignment: Perkovic text, Ch. 1 and 2.1-2.5 Python Python is an interactive language. Java or C++: compile, run Also, a main function or method Python: type expressions

More information

mith College Computer Science Week 13 CSC111 Fall 2015 (Lab 12, Homework 12) Dominique Thiébaut

mith College Computer Science Week 13 CSC111 Fall 2015 (Lab 12, Homework 12) Dominique Thiébaut mith College Computer Science Week 13 CSC111 Fall 2015 (Lab 12, Homework 12) Dominique Thiébaut dthiebaut@smith.edu This Week: Two Concepts Lists of Lists Class Inheritance Lists of Lists (Chapter 11 Designing

More information

Introduction Programming Using Python Lecture 8. Dr. Zhang COSC 1437 Fall 2017 Nov 30, 2017

Introduction Programming Using Python Lecture 8. Dr. Zhang COSC 1437 Fall 2017 Nov 30, 2017 Introduction Programming Using Python Lecture 8 Dr. Zhang COSC 1437 Fall 2017 Nov 30, 2017 Chapter 12 Inheritance and Class Design Review Suppose you will define classes to model circles, rectangles, and

More information

Example: Class MSDie Introduction to Graphs and NetworkX

Example: Class MSDie Introduction to Graphs and NetworkX Example: Class MSDie Introduction to Graphs and NetworkX Monday, March 30, 2009 1 Be careful whose random number generator you trust http://xkcd.com/221/ 2 1 Reminders Sample exam questions have been posted

More information

CMSC201 Computer Science I for Majors

CMSC201 Computer Science I for Majors CMSC201 Computer Science I for Majors Lecture 25 Classes All materials copyright UMBC and Dr. Katherine Gibson unless otherwise noted Run time Last Class We Covered Run time of different algorithms Selection,

More information

Intro. Scheme Basics. scm> 5 5. scm>

Intro. Scheme Basics. scm> 5 5. scm> Intro Let s take some time to talk about LISP. It stands for LISt Processing a way of coding using only lists! It sounds pretty radical, and it is. There are lots of cool things to know about LISP; if

More information

Overview of OOP. Dr. Zhang COSC 1436 Summer, /18/2017

Overview of OOP. Dr. Zhang COSC 1436 Summer, /18/2017 Overview of OOP Dr. Zhang COSC 1436 Summer, 2017 7/18/2017 Review Data Structures (list, dictionary, tuples, sets, strings) Lists are enclosed in square brackets: l = [1, 2, "a"] (access by index, is mutable

More information

Data Structures (list, dictionary, tuples, sets, strings)

Data Structures (list, dictionary, tuples, sets, strings) Data Structures (list, dictionary, tuples, sets, strings) Lists are enclosed in brackets: l = [1, 2, "a"] (access by index, is mutable sequence) Tuples are enclosed in parentheses: t = (1, 2, "a") (access

More information

Python Lists and for Loops. Learning Outcomes. What s a List 9/19/2012

Python Lists and for Loops. Learning Outcomes. What s a List 9/19/2012 Python Lists and for Loops CMSC 201 Fall 2012 Instructor: John Park Lecture Section 01 Discussion Sections 02-08, 16, 17 1 Learning Outcomes Be aware that multiple items can be stored in a list. Become

More information

A new data type: Lists. March 5, 2018 Sprenkle - CSCI Ø How can we convert from the numerical representa9on to the character?

A new data type: Lists. March 5, 2018 Sprenkle - CSCI Ø How can we convert from the numerical representa9on to the character? Objec9ves A new data type: Lists March 5, 2018 Sprenkle - CSCI111 1 Review How can we convert between characters and their numerical representa9on? Ø How can we convert from the numerical representa9on

More information

Java Object Oriented Design. CSC207 Fall 2014

Java Object Oriented Design. CSC207 Fall 2014 Java Object Oriented Design CSC207 Fall 2014 Design Problem Design an application where the user can draw different shapes Lines Circles Rectangles Just high level design, don t write any detailed code

More information

CS2304: Python for Java Programmers. CS2304: Sequences and Collections

CS2304: Python for Java Programmers. CS2304: Sequences and Collections CS2304: Sequences and Collections Sequences In Python A sequence type in python supports: The in membership operator. The len() function. Slicing like we saw with strings, s[1:3]. And is iterable (for

More information

Lesson 10A OOP Fundamentals. By John B. Owen All rights reserved 2011, revised 2014

Lesson 10A OOP Fundamentals. By John B. Owen All rights reserved 2011, revised 2014 Lesson 10A OOP Fundamentals By John B. Owen All rights reserved 2011, revised 2014 Table of Contents Objectives Definition Pointers vs containers Object vs primitives Constructors Methods Object class

More information

Admin. How's the project coming? After these slides, read chapter 13 in your book. Quizzes will return

Admin. How's the project coming? After these slides, read chapter 13 in your book. Quizzes will return Recursion CS 1 Admin How's the project coming? After these slides, read chapter 13 in your book Yes that is out of order, but we can read it stand alone Quizzes will return Tuesday Nov 29 th see calendar

More information

Outline. Outline. 1 Chapter 2: Data Abstraction

Outline. Outline. 1 Chapter 2: Data Abstraction Outline Outline 1 Chapter 2: Data Abstraction From Data Type to ADT Values A value is a unit of information used in a program. It can be associated with a constant or variable (a name) by an assignment

More information

Final Exam(sample), Fall, 2014

Final Exam(sample), Fall, 2014 Final Exam(sample), Fall, 2014 Date: Dec 4 th, 2014 Time: 1.25 hours (1.00 a.m. 2:15 p.m.) Total: 100 points + 20 bonus Problem 1 T/F 2 Choice 3 Output Points 16 16 48 4 Programming 20 5 Bonus 20 Total

More information

CS112 Lecture: Defining Classes. 1. To describe the process of defining an instantiable class

CS112 Lecture: Defining Classes. 1. To describe the process of defining an instantiable class CS112 Lecture: Defining Classes Last revised 2/3/06 Objectives: 1. To describe the process of defining an instantiable class Materials: 1. BlueJ SavingsAccount example project 2. Handout of code for SavingsAccount

More information

Introduction to Computer Programming for Non-Majors

Introduction to Computer Programming for Non-Majors Introduction to Computer Programming for Non-Majors CSC 2301, Fall 2015 Chapter 8 Part 1 The Department of Computer Science Chapter 8 Loop Structures and Booleans 2 Objectives To understand the concepts

More information

All programs can be represented in terms of sequence, selection and iteration.

All programs can be represented in terms of sequence, selection and iteration. Python Lesson 3 Lists, for loops and while loops Suffolk One, Ipswich, 4:30 to 6:00 Tuesday Jan 28 Nicky Hughes All programs can be represented in terms of sequence, selection and iteration. 1 Computational

More information

At full speed with Python

At full speed with Python At full speed with Python João Ventura v0.1 Contents 1 Introduction 2 2 Installation 3 2.1 Installing on Windows............................ 3 2.2 Installing on macos............................. 5 2.3

More information

About the Final. Saturday, 7-10pm in Science Center 101. Closed book, closed notes. Not on the final: graphics, file I/O, vim, unix

About the Final. Saturday, 7-10pm in Science Center 101. Closed book, closed notes. Not on the final: graphics, file I/O, vim, unix CS 21 Final Review About the Final Saturday, 7-10pm in Science Center 101 Closed book, closed notes Not on the final: graphics, file I/O, vim, unix Expect Questions That Ask You To: Evaluate Python expressions

More information

Introduction to Object-Oriented Programming

Introduction to Object-Oriented Programming Polymorphism 1 / 19 Introduction to Object-Oriented Programming Today we ll learn how to combine all the elements of object-oriented programming in the design of a program that handles a company payroll.

More information

CSI33 Data Structures

CSI33 Data Structures Outline Department of Mathematics and Computer Science Bronx Community College September 6, 2017 Outline Outline 1 Chapter 2: Data Abstraction Outline Chapter 2: Data Abstraction 1 Chapter 2: Data Abstraction

More information

Exam 1 Format, Concepts, What you should be able to do, and Sample Problems

Exam 1 Format, Concepts, What you should be able to do, and Sample Problems CSSE 120 Introduction to Software Development Exam 1 Format, Concepts, What you should be able to do, and Sample Problems Page 1 of 6 Format: The exam will have two sections: Part 1: Paper-and-Pencil o

More information

Sequence types. str and bytes are sequence types Sequence types have several operations defined for them. Sequence Types. Python

Sequence types. str and bytes are sequence types Sequence types have several operations defined for them. Sequence Types. Python Python Sequence Types Sequence types str and bytes are sequence types Sequence types have several operations defined for them Indexing Python Sequence Types Each element in a sequence can be extracted

More information

Abstract Data Types. CS 234, Fall Types, Data Types Abstraction Abstract Data Types Preconditions, Postconditions ADT Examples

Abstract Data Types. CS 234, Fall Types, Data Types Abstraction Abstract Data Types Preconditions, Postconditions ADT Examples Abstract Data Types CS 234, Fall 2017 Types, Data Types Abstraction Abstract Data Types Preconditions, Postconditions ADT Examples Data Types Data is stored in a computer as a sequence of binary digits:

More information

PLEASE HAND IN UNIVERSITY OF TORONTO Faculty of Arts and Science

PLEASE HAND IN UNIVERSITY OF TORONTO Faculty of Arts and Science PLEASE HAND IN UNIVERSITY OF TORONTO Faculty of Arts and Science AUGUST EXAMINATIONS CSC 108H1Y Instructor: Daniel Zingaro Duration three hours PLEASE HAND IN Examination Aids: None. Student Number: Last

More information

Lists, loops and decisions

Lists, loops and decisions Caltech/LEAD Summer 2012 Computer Science Lecture 4: July 11, 2012 Lists, loops and decisions Lists Today Looping with the for statement Making decisions with the if statement Lists A list is a sequence

More information

Software Paradigms (Lesson 3) Object-Oriented Paradigm (2)

Software Paradigms (Lesson 3) Object-Oriented Paradigm (2) Software Paradigms (Lesson 3) Object-Oriented Paradigm (2) Table of Contents 1 Reusing Classes... 2 1.1 Composition... 2 1.2 Inheritance... 4 1.2.1 Extending Classes... 5 1.2.2 Method Overriding... 7 1.2.3

More information

Initial Coding Guidelines

Initial Coding Guidelines Initial Coding Guidelines ITK 168 (Lim) This handout specifies coding guidelines for programs in ITK 168. You are expected to follow these guidelines precisely for all lecture programs, and for lab programs.

More information

Loop structures and booleans

Loop structures and booleans Loop structures and booleans Michael Mandel Lecture 7 Methods in Computational Linguistics I The City University of New York, Graduate Center https://github.com/ling78100/lectureexamples/blob/master/lecture07final.ipynb

More information

6.001 Notes: Section 8.1

6.001 Notes: Section 8.1 6.001 Notes: Section 8.1 Slide 8.1.1 In this lecture we are going to introduce a new data type, specifically to deal with symbols. This may sound a bit odd, but if you step back, you may realize that everything

More information

ECE 364 Software Engineering Tools Lab. Lecture 3 Python: Introduction

ECE 364 Software Engineering Tools Lab. Lecture 3 Python: Introduction ECE 364 Software Engineering Tools Lab Lecture 3 Python: Introduction 1 Introduction to Python Common Data Types If Statements For and While Loops Basic I/O Lecture Summary 2 What is Python? Python is

More information

Algorithm Design and Recursion. Search and Sort Algorithms

Algorithm Design and Recursion. Search and Sort Algorithms Algorithm Design and Recursion Search and Sort Algorithms Objectives To understand the basic techniques for analyzing the efficiency of algorithms. To know what searching is and understand the algorithms

More information

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming Intro to Programming Unit 7 Intro to Programming 1 What is Programming? 1. Programming Languages 2. Markup vs. Programming 1. Introduction 2. Print Statement 3. Strings 4. Types and Values 5. Math Externals

More information

Unit E Step-by-Step: Programming with Python

Unit E Step-by-Step: Programming with Python Unit E Step-by-Step: Programming with Python Computer Concepts 2016 ENHANCED EDITION 1 Unit Contents Section A: Hello World! Python Style Section B: The Wacky Word Game Section C: Build Your Own Calculator

More information

CMSC201 Computer Science I for Majors

CMSC201 Computer Science I for Majors CMSC201 Computer Science I for Majors Lecture 08 Lists Constants Last Class We Covered More on while loops Sentinel loops Boolean flags 2 Any Questions from Last Time? 3 Today s Objectives To learn about

More information

Introduction to Computer Programming for Non-Majors

Introduction to Computer Programming for Non-Majors Introduction to Computer Programming for Non-Majors CSC 2301, Fall 2016 Mid-term Review Instructor: Long Ma The Department of Computer Science Basic Model of a Computer Input CPU Control Unit Arithmetic

More information

Python Evaluation Rules

Python Evaluation Rules Python Evaluation Rules UW CSE 160 https://courses.cs.washington.edu/courses/cse160/15sp/ Michael Ernst and Isaac Reynolds mernst@cs.washington.edu April 1, 2015 Contents 1 Introduction 2 1.1 The Structure

More information

CS107 Handout 37 Spring 2007 May 25, 2007 Introduction to Inheritance

CS107 Handout 37 Spring 2007 May 25, 2007 Introduction to Inheritance CS107 Handout 37 Spring 2007 May 25, 2007 Introduction to Inheritance Handout written by Julie Zelenski, updated by Jerry. Inheritance is a language property most gracefully supported by the object-oriented

More information

Object-Oriented Design (OOD) and C++

Object-Oriented Design (OOD) and C++ Chapter 2 Object-Oriented Design (OOD) and C++ At a Glance Instructor s Manual Table of Contents Chapter Overview Chapter Objectives Instructor Notes Quick Quizzes Discussion Questions Projects to Assign

More information

Python Programming: An Introduction to Computer Science

Python Programming: An Introduction to Computer Science Python Programming: An Introduction to Computer Science Chapter 7 Decision Structures Python Programming, 2/e 1 Objectives æ To understand the programming pattern simple decision and its implementation

More information

Outline: Search and Recursion (Ch13)

Outline: Search and Recursion (Ch13) Search and Recursion Michael Mandel Lecture 12 Methods in Computational Linguistics I The City University of New York, Graduate Center https://github.com/ling78100/lectureexamples/blob/master/lecture12final.ipynb

More information

CMSC 201 Fall 2016 Lab 09 Advanced Debugging

CMSC 201 Fall 2016 Lab 09 Advanced Debugging CMSC 201 Fall 2016 Lab 09 Advanced Debugging Assignment: Lab 09 Advanced Debugging Due Date: During discussion Value: 10 points Part 1: Introduction to Errors Throughout this semester, we have been working

More information

The Big Python Guide

The Big Python Guide The Big Python Guide Big Python Guide - Page 1 Contents Input, Output and Variables........ 3 Selection (if...then)......... 4 Iteration (for loops)......... 5 Iteration (while loops)........ 6 String

More information

Collections. Lists, Tuples, Sets, Dictionaries

Collections. Lists, Tuples, Sets, Dictionaries Collections Lists, Tuples, Sets, Dictionaries Homework notes Homework 1 grades on canvas People mostly lost points for not reading the document carefully Didn t play again Didn t use Y/N for playing again

More information

There are four numeric types: 1. Integers, represented as a 32 bit (or longer) quantity. Digits sequences (possibly) signed are integer literals:

There are four numeric types: 1. Integers, represented as a 32 bit (or longer) quantity. Digits sequences (possibly) signed are integer literals: Numeric Types There are four numeric types: 1. Integers, represented as a 32 bit (or longer) quantity. Digits sequences (possibly) signed are integer literals: 1-123 +456 2. Long integers, of unlimited

More information

So far, we have seen two different approaches for using computing to solve problems:

So far, we have seen two different approaches for using computing to solve problems: Chapter 10 Objects By the word operation, we mean any process which alters the mutual relation of two or more things, be this relation of what kind it may. This is the most general definition, and would

More information

MUTABLE LISTS AND DICTIONARIES 4

MUTABLE LISTS AND DICTIONARIES 4 MUTABLE LISTS AND DICTIONARIES 4 COMPUTER SCIENCE 61A Sept. 24, 2012 1 Lists Lists are similar to tuples: the order of the data matters, their indices start at 0. The big difference is that lists are mutable

More information

JAVA MOCK TEST JAVA MOCK TEST II

JAVA MOCK TEST JAVA MOCK TEST II http://www.tutorialspoint.com JAVA MOCK TEST Copyright tutorialspoint.com This section presents you various set of Mock Tests related to Java Framework. You can download these sample mock tests at your

More information

File Input/Output. Learning Outcomes 10/8/2012. CMSC 201 Fall 2012 Instructor: John Park Lecture Section 01. Discussion Sections 02-08, 16, 17

File Input/Output. Learning Outcomes 10/8/2012. CMSC 201 Fall 2012 Instructor: John Park Lecture Section 01. Discussion Sections 02-08, 16, 17 CMSC 201 Fall 2012 Instructor: John Park Lecture Section 01 1 Discussion Sections 02-08, 16, 17 Adapted from slides by Sue Evans et al. 2 Learning Outcomes Become familiar with input and output (I/O) from

More information

Introduction to Computer Programming for Non-Majors

Introduction to Computer Programming for Non-Majors Introduction to Computer Programming for Non-Majors CSC 2301, Fall 2014 Chapter 10 Part 2 The Department of Computer Science Cannonball Program Specification Let s try to write a program that simulates

More information

Data Structures I: Linked Lists

Data Structures I: Linked Lists Lab 4 Data Structures I: Linked Lists Lab Objective: Analyzing and manipulating data are essential skills in scientific computing. Storing, retrieving, and rearranging data take time. As a dataset grows,

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

Introduction to Python! Lecture 2

Introduction to Python! Lecture 2 .. Introduction to Python Lecture 2 Summary Summary: Lists Sets Tuples Variables while loop for loop Functions Names and values Passing parameters to functions Lists Characteristics of the Python lists

More information

CS-202 Introduction to Object Oriented Programming

CS-202 Introduction to Object Oriented Programming CS-202 Introduction to Object Oriented Programming California State University, Los Angeles Computer Science Department Lecture III Inheritance and Polymorphism Introduction to Inheritance Introduction

More information

TAIL RECURSION, SCOPE, AND PROJECT 4 11

TAIL RECURSION, SCOPE, AND PROJECT 4 11 TAIL RECURSION, SCOPE, AND PROJECT 4 11 COMPUTER SCIENCE 61A Noveber 12, 2012 1 Tail Recursion Today we will look at Tail Recursion and Tail Call Optimizations in Scheme, and how they relate to iteration

More information

Comp 151. More on working with Data

Comp 151. More on working with Data Comp 151 More on working with Data 1 Admin Questions on project? Did you see the project yet? Quiz coming next week 2 working with lots of data sometimes working with one piece of data at a time is fine

More information

CS Summer 2013

CS Summer 2013 CS 1110 - Summer 2013 intro to programming -- how to think like a robot :) we use the Python* language (www.python.org) programming environments (many choices): Eclipse (free from www.eclipse.org), or

More information

Lecture. Loops && Booleans. Richard E Sarkis CSC 161: The Art of Programming

Lecture. Loops && Booleans. Richard E Sarkis CSC 161: The Art of Programming Lecture Loops && Booleans Richard E Sarkis CSC 161: The Art of Programming Class Administrivia Agenda (In-)definite loops (for/while) Patterns: interactive loop and sentinel loop Solve problems using (possibly

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

CS112 Lecture: Defining Instantiable Classes

CS112 Lecture: Defining Instantiable Classes CS112 Lecture: Defining Instantiable Classes Last revised 2/3/05 Objectives: 1. To describe the process of defining an instantiable class 2. To discuss public and private visibility modifiers. Materials:

More information

6. Data Types and Dynamic Typing (Cont.)

6. Data Types and Dynamic Typing (Cont.) 6. Data Types and Dynamic Typing (Cont.) 6.5 Strings Strings can be delimited by a pair of single quotes ('...'), double quotes ("..."), triple single quotes ('''...'''), or triple double quotes ("""...""").

More information

Programming I. Course 9 Introduction to programming

Programming I. Course 9 Introduction to programming Programming I Course 9 Introduction to programming What we talked about? Modules List Comprehension Generators Recursive Functions Files What we talk today? Object Oriented Programming Classes Objects

More information

Module 04: Lists. Topics: Lists and their methods Mutating lists Abstract list functions Readings: ThinkP 8, 10. CS116 Fall : Lists

Module 04: Lists. Topics: Lists and their methods Mutating lists Abstract list functions Readings: ThinkP 8, 10. CS116 Fall : Lists Module 04: Lists Topics: Lists and their methods Mutating lists Abstract list functions Readings: ThinkP 8, 10 1 Consider the string method split >>> name = "Harry James Potter" >>> name.split() ['Harry',

More information

CMSC 201 Computer Science I for Majors

CMSC 201 Computer Science I for Majors CMSC 201 Computer Science I for Majors Lecture 02 Intro to Python Syllabus Last Class We Covered Grading scheme Academic Integrity Policy (Collaboration Policy) Getting Help Office hours Programming Mindset

More information

Introduction to OOP. Procedural Programming sequence of statements to solve a problem.

Introduction to OOP. Procedural Programming sequence of statements to solve a problem. Introduction to OOP C++ - hybrid language improved and extended standard C (procedural language) by adding constructs and syntax for use as an object oriented language. Object-Oriented and Procedural Programming

More information

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

CS 1110 Final, December 8th, Question Points Score Total: 100 CS 1110 Final, December 8th, 2016 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

More information

Introduction to Computer Programming for Non-Majors

Introduction to Computer Programming for Non-Majors Introduction to Computer Programming for Non-Majors CSC 2301, Fall 2014 Chapter 5 Part 3 & Review The Department of Computer Science Multi-Line Strings -2-1 Files: Multi-line Strings A file is a sequence

More information

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

GIS 4653/5653: Spatial Programming and GIS. More Python: Statements, Types, Functions, Modules, Classes GIS 4653/5653: Spatial Programming and GIS More Python: Statements, Types, Functions, Modules, Classes Statement Syntax The if-elif-else statement Indentation and and colons are important Parentheses and

More information

Recall. Key terms. Review. Encapsulation (by getters, setters, properties) OOP Features. CSC148 Intro. to Computer Science

Recall. Key terms. Review. Encapsulation (by getters, setters, properties) OOP Features. CSC148 Intro. to Computer Science CSC148 Intro. to Computer Science Lecture 3: designing classes, special methods, composition, inheritance, Stack, Sack Amir H. Chinaei, Summer 2016 Office Hours: R 10-12 BA4222 ahchinaei@cs.toronto.edu

More information

CMPT 120 Lists and Strings. Summer 2012 Instructor: Hassan Khosravi

CMPT 120 Lists and Strings. Summer 2012 Instructor: Hassan Khosravi CMPT 120 Lists and Strings Summer 2012 Instructor: Hassan Khosravi All of the variables that we have used have held a single item One integer, floating point value, or string often you find that you want

More information

Access Intermediate

Access Intermediate Access 2013 - Intermediate 103-134 Advanced Queries Quick Links Overview Pages AC124 AC125 Selecting Fields Pages AC125 AC128 AC129 AC131 AC238 Sorting Results Pages AC131 AC136 Specifying Criteria Pages

More information

Review sheet for Final Exam (List of objectives for this course)

Review sheet for Final Exam (List of objectives for this course) Review sheet for Final Exam (List of objectives for this course) Please be sure to see other review sheets for this semester Please be sure to review tests from this semester Week 1 Introduction Chapter

More information

Control Structures 1 / 17

Control Structures 1 / 17 Control Structures 1 / 17 Structured Programming Any algorithm can be expressed by: Sequence - one statement after another Selection - conditional execution (not conditional jumping) Repetition - loops

More information

CMSC201 Computer Science I for Majors

CMSC201 Computer Science I for Majors CMSC201 Computer Science I for Majors Lecture 08 Lists Constants Last Class We Covered More on while loops Sentinel loops Priming Reads Boolean flags 2 Any Questions from Last Time? 3 Today s Objectives

More information

2. The object-oriented paradigm!

2. The object-oriented paradigm! 2. The object-oriented paradigm! Plan for this section:! n Look at things we have to be able to do with a programming language! n Look at Java and how it is done there" Note: I will make a lot of use of

More information

Outline. LList: A Linked Implementation of a List ADT Iterators Links vs. Arrays In-class work. 1 Chapter 4: Linked Structures and Iterators

Outline. LList: A Linked Implementation of a List ADT Iterators Links vs. Arrays In-class work. 1 Chapter 4: Linked Structures and Iterators Chapter 4: Linked Structures and Outline 1 Chapter 4: Linked Structures and Chapter 4: Linked Structures and Using the ListNode Class Ideas about Linked List Implementation We have a pretty good feeling

More information

M301: Software Systems & their Development. Unit 4: Inheritance, Composition and Polymorphism

M301: Software Systems & their Development. Unit 4: Inheritance, Composition and Polymorphism Block 1: Introduction to Java Unit 4: Inheritance, Composition and Polymorphism Aims of the unit: Study and use the Java mechanisms that support reuse, in particular, inheritance and composition; Analyze

More information

Recursion. Genome 559: Introduction to Statistical and Computational Genomics Elhanan Borenstein

Recursion. Genome 559: Introduction to Statistical and Computational Genomics Elhanan Borenstein Recursion Genome 559: Introduction to Statistical and Computational Genomics Elhanan Borenstein The merge sort algorithm 1. Split your list into two halves 2. Sort the first half 3. Sort the second half

More information

Introduction to Computer Programming for Non-Majors

Introduction to Computer Programming for Non-Majors Introduction to Computer Programming for Non-Majors CSC 2301, Fall 2016 Chapter 2 Instructor: Long Ma The Department of Computer Science Review Install and test python Basic concept of computers Test simple

More information

Chapter 10. Object-Oriented Analysis and Modeling Using the UML. McGraw-Hill/Irwin

Chapter 10. Object-Oriented Analysis and Modeling Using the UML. McGraw-Hill/Irwin Chapter 10 Object-Oriented Analysis and Modeling Using the UML McGraw-Hill/Irwin Copyright 2007 by The McGraw-Hill Companies, Inc. All rights reserved. Objectives 10-2 Define object modeling and explain

More information

Access Intermediate

Access Intermediate Access 2010 - Intermediate 103-134 Advanced Queries Quick Links Overview Pages AC116 AC117 Selecting Fields Pages AC118 AC119 AC122 Sorting Results Pages AC125 AC126 Specifying Criteria Pages AC132 AC134

More information

Lists CS 1111 Introduction to Programming Fall 2018

Lists CS 1111 Introduction to Programming Fall 2018 Lists CS 1111 Introduction to Programming Fall 2018 [The Coder s Apprentice, 12] 1 Overview: Lists List = ordered sequence of values Mutable data type Because of the ordering, an element in a list can

More information

Project 6 Due 11:59:59pm Thu, Dec 10, 2015

Project 6 Due 11:59:59pm Thu, Dec 10, 2015 Project 6 Due 11:59:59pm Thu, Dec 10, 2015 Updates None yet. Introduction In this project, you will add a static type checking system to the Rube programming language. Recall the formal syntax for Rube

More information

CS61A Notes Week 13: Interpreters

CS61A Notes Week 13: Interpreters CS61A Notes Week 13: Interpreters Read-Eval Loop Unlike Python, the result of evaluating an expression is not automatically printed. Instead, Logo complains if the value of any top-level expression is

More information

Reviewing for the Midterm Covers chapters 1 to 5, 7 to 9. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Reviewing for the Midterm Covers chapters 1 to 5, 7 to 9. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013 Reviewing for the Midterm Covers chapters 1 to 5, 7 to 9 Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013 2 Things to Review Review the Class Slides: Key Things to Take Away Do you understand

More information

Objects and Classes. Amirishetty Anjan Kumar. November 27, Computer Science and Engineering Indian Institue of Technology Bombay

Objects and Classes. Amirishetty Anjan Kumar. November 27, Computer Science and Engineering Indian Institue of Technology Bombay Computer Science and Engineering Indian Institue of Technology Bombay November 27, 2004 What is Object Oriented Programming? Identifying objects and assigning responsibilities to these objects. Objects

More information

COEN244: Class & function templates

COEN244: Class & function templates COEN244: Class & function templates Aishy Amer Electrical & Computer Engineering Templates Function Templates Class Templates Outline Templates and inheritance Introduction to C++ Standard Template Library

More information