1 Gentle Introduction to Programming Session 6: Lists, Course Summary.

Slides:



Advertisements
Similar presentations
Chapter 22 Implementing lists: linked implementations.
Advertisements

Overview of Data Structures and Algorithms
Compiler Construction
Wednesday, 10/2/02, Slide #1 CS 106 Intro to CS 1 Wednesday, 10/2/02  QUESTIONS (on HW02 – due at 5 pm)??  Today:  Review of parameters  Introduction.
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
Operator Overloading in C++ Systems Programming. Systems Programming: Operator Overloading 22   Fundamentals of Operator Overloading   Restrictions.
1 Programming for Engineers in Python Autumn Lecture 5: Object Oriented Programming.
1 Gentle Introduction to Programming Session 4: Arrays, Sorting, Efficiency.
1 Gentle Introduction to Programming Session 5: Sorting, Searching, Time- Complexity Analysis, Memory Model, Object Oriented Programming.
1 Gentle Introduction to Programming Session 6: Lists, Course Summary.
1 Gentle Introduction to Programming Session 5: Memory Model, Object Oriented Programming.
CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++
1 ES 314 Advanced Programming Lec 2 Sept 3 Goals: Complete the discussion of problem Review of C++ Object-oriented design Arrays and pointers.
Recursion Chapter 7. Chapter 7: Recursion2 Chapter Objectives To understand how to think recursively To learn how to trace a recursive method To learn.
1 Gentle Introduction to Programming Session 4: Arrays.
Programming Languages and Paradigms Object-Oriented Programming.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 19 Clicker Questions November 3, 2009.
Review for Midterm Chapter 1-9 CSc 212 Data Structures.
5.1 and 5.4 through 5.6 Various Things. Terminology Identifiers: a name representing a variable, class name, method name, etc. Operand: a named memory.
Data Structures Using C++ 2E Chapter 3 Pointers and Array-Based Lists.
MT311 Java Application Development and Programming Languages Li Tak Sing( 李德成 )
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Custom Templatized Data Structures.
COSC 1P03 Data Structures and Abstraction 4.1 Abstract Data Types The advantage of a bad memory is that one enjoys several times the same good things for.
CHAPTER 09 Compiled by: Dr. Mohammad Omar Alhawarat Sorting & Searching.
Information and Computer Sciences University of Hawaii, Manoa
Chapter 12 Recursion, Complexity, and Searching and Sorting
Stephen P. Carl - CS 2421 Recursion Reading : Chapter 4.
Overloading Binary Operators Two ways to overload –As a member function of a class –As a friend function As member functions –General syntax Data Structures.
 Pearson Education, Inc. All rights reserved Searching and Sorting.
Analysis of Algorithms These slides are a modified version of the slides used by Prof. Eltabakh in his offering of CS2223 in D term 2013.
1 Java: AP Curriculum Focus and Java Subset Alyce Brady.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Generics and Collections. Introduction Generics New feature of J2SE 5.0 Provide compile-time type safety Catch invalid types at compile time Generic methods.
Pointers OVERVIEW.
Chapter 1 Object Oriented Programming. OOP revolves around the concept of an objects. Objects are created using the class definition. Programming techniques.
CSC 211 Data Structures Lecture 13
Data Structures Using C++ 2E1 Inheritance An “is-a” relationship –Example: “every employee is a person” Allows new class creation from existing classes.
CSC 221: Recursion. Recursion: Definition Function that solves a problem by relying on itself to compute the correct solution for a smaller version of.
CS 361 – Chapters 8-9 Sorting algorithms –Selection, insertion, bubble, “swap” –Merge, quick, stooge –Counting, bucket, radix How to select the n-th largest/smallest.
CS 61B Data Structures and Programming Methodology July 21, 2008 David Sun.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Algorithm Analysis CS 400/600 – Data Structures. Algorithm Analysis2 Abstract Data Types Abstract Data Type (ADT): a definition for a data type solely.
MT311 Java Application Development and Programming Languages Li Tak Sing( 李德成 )
Java Methods Big-O Analysis of Algorithms Object-Oriented Programming
1 Programming for Engineers in Python Autumn Lecture 6: More Object Oriented Programming.
1 One Dimensional Arrays Chapter 11 2 "All students to receive arrays!" reports Dr. Austin. Declaring arrays scores :
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
1 Classes II Chapter 7 2 Introduction Continued study of –classes –data abstraction Prepare for operator overloading in next chapter Work with strings.
Chapter 11: Advanced Inheritance Concepts. Objectives Create and use abstract classes Use dynamic method binding Create arrays of subclass objects Use.
ICS201 Lecture 21 : Sorting King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department.
Searching CSE 103 Lecture 20 Wednesday, October 16, 2002 prepared by Doug Hogan.
Chapter 15 Running Time Analysis. Topics Orders of Magnitude and Big-Oh Notation Running Time Analysis of Algorithms –Counting Statements –Evaluating.
CS 116 Object Oriented Programming II Lecture 13 Acknowledgement: Contains materials provided by George Koutsogiannakis and Matt Bauer.
Functional Programming
Chapter 0: Introduction
Introduction to Computers Computer Generations
CS 215 Final Review Ismail abumuhfouz Fall 2014.
COP 3503 FALL 2012 Shayan Javed Lecture 15
CS 326 Programming Languages, Concepts and Implementation
Teach A level Computing: Algorithms and Data Structures
Algorithm design and Analysis
Data Structures and Algorithms
CISC/CMPE320 - Prof. McLeod
Introduction to Algorithms
Introduction to Data Structure
Compiler Construction
More Scheme CS 331.
Compiler Construction
Presentation transcript:

1 Gentle Introduction to Programming Session 6: Lists, Course Summary

2 Review Scala memory model Guest lecture by Prof. Ronitt Rubinfeld Object-oriented programming (OOP) Classes and Objects Functional Objects (Rational Numbers example)

3 Today הפתעה! (+ משובים) Finish Functional Objects Guest lecture by Dr. Lior Wolf 10:10 Course Summary ++ Lists More OOP (inheritance, hierarchy, polymorphism) Go home!

4 Object-Oriented Programming (OOP) Represent problem-domain entities using a computer language When building a software in a specific domain, describe the different components of the domain as types and variables Thus we can take another step up in abstraction

5 Class as a Blueprint A class is a blueprint of objects

6 Car Example Members: 4 wheels, steering wheel, horn, color,… Every car instance has its own Methods: drive, turn left, honk, repaint,… Constructors: Car(String color), Car(Array[Wheels], Engine,…), …

7 Rational Numbers A ration number is a number that can be expressed as a ration n/d (n,d integers, d not 0) Examples: 1/2, 2/3, 112/239, 2/1 Not an approximation

8 Specification Add, subtract, multiply, divide println should work smoothly Immutable (result of an operation is a new rational number) It should feel like native language support

9 Constructing a Rational How client programmer will create a new Rational object? Class parameters

10 Constructing a Rational The Scala compiler will compile any code placed in the class body, which isn’t part of a field or a method definition, into the primary constructor ?

11 Reimplementing toString toString method A more useful implementation of toString would print out the values of the Rational’s numerator and denominator override the default implementation

12 Usage Now we can remove the debug println…

13 Checking Preconditions Ensure the data is valid when the object is constructed Use require

14 Define “add” Method Immutable Define add:

15 Add Fields n, d are in scope in the add method Access then only on the object on which add was invoked 

16 Test Add, Access Fields

17 Self Reference (this) Define method lessThan: Define method max:

18 Auxiliary Constructors Constructors other then the primary Example: a rational number with a denominator of 1 (e.g., 5/1  5) We would like to do: new Rational(5) Auxiliary constructor first action: invoke another constructor of the same class The primary constructor is thus the single point of entry of a class

19 Revised Rational

20 Private Fields and Methods 66/42 = 11/7 To normalize divide the numerator and denominator by their greatest common divisor (gcd) gcd(66,42) = 6  (66/6)/(42/6) = 11/7 No need for Rational clients to be aware of this Encapsulation

21 Off Topic: Calculate gcd gcd(a,b) = g a = n * g b = m * g gcd(n,m)=1(otherwise g is not the gcd) a = t * b + r = t * m * g + r  g is a divisor of r gcd(a,b) = gcd(b,a%b) The Euclidean algorithm: repeat iteratively: if (b == 0) return a else repeat using a  b, b  a%b

22 Correctness Example: gcd(40,24)  gcd(24,16)  gcd(16,8)  gcd(8,0)  8 Prove: g = gcd(a,b) = gcd(b,a%b)= g1 g1 is a divisor of a (  g1 ≤ g ) There is no larger divisor of a (  g1 ≥ g ) ≤ : a = t * b + r  a = t * h * g1 + v * g1  g1 is a divisor of a ≥ : assume g > g1  a = t * b + r  g is a divisor of b and r  contradiction

23 Implementation

24 Revised Rational

25 Defining Operators Why not use natural arithmetic operators? Replace add by the usual mathematical symbol Operator precedence will be kept All operations are method calls

26 Revised Rational

27 Usage

28 Method Overloading Now we can add and multiply rational numbers! What about mixed arithmetic? r * 2 won’t work  r * new Rational(2) is not nice  Add new methods for mixed addition and multiplication Method overloading The compiler picks the correct overloaded method

29 Usage The * method invoked is determined in each case by the type of the right operand

30 Revised Rational

31 Implicit Conversions 2 * r  2.*(r)  method call on 2 (Int)  Int class contains no multiplication method that takes a Rational argument  Create an implicit conversion that automatically converts integers to rational numbers when needed

32 Companion Object

33 Revised Rational Define implicit conversion in Rational.scala, after defining object Rational

34 In Eclipse In Rational.scala: Companion object (object Rational) Rational class (class Rational) Place the main method in another file

35 Summary Customize classes so that they are natural to use fields, methods, primary constructor Method overriding Self reference (this) Define several constructors Encapsulation Define operators as method Method overloading Implicit conversions, companion object

36 Complete HomeWork Implement class Complex so it is natural to use complex numbers Examples:

37 Today הפתעה! (+ משובים) Finish Functional Objects Guest lecture by Dr. Lior Wolf 10:10 Course Summary ++ Lists More OOP (inheritance, hierarchy, polymorphism) Go home!

38 Course Description This course will provide a gentle introduction to programming using Scala for highly motivated students with little or no prior experience in programming

39 Objective Bridge the gap for students without prior programming knowledge

40 Course Description Lectures will be interactive featuring in-class exercises with lots of support You are expected to work hard!

41 Course Plan SessionMaterial 1Basic concepts in CS and programming, basic Scala 2Basic Scala (cont.), Functions 3Recursion 4Arrays, Sorting algorithms 5Object-oriented programming 6Summary, Lists, more OOP

42 Why Scala? Semester A: Scheme Semester B: Java Scala language has some features similar to Scheme and some to Java Scala is cool!

43 Summary General introduction to CS and programming Basic Scala Development tools: Interpreter Eclipse (+ debugger) Compiler, Interpreter

44 Compiler

45 Interpreter

46 How it works in Scala

47 Higher Order Functions

48 Recursion

49 Recursion and Efficiency The recursive form, however elegant, may be much less efficient The number of redundant calls grow exponentially! Fib(6) Fib(4)

50 Recursive Vs. Iterative Process Operation pending No pending operations

51 “Tail” Recursion in Scala Scala compiler translate tail-recursion to iterative execution Thus, the functions-stack is not growing

52 Arrays Array: sequential block of memory that holds variables of the same type Array can be declared for any type The array variable itself holds the address in memory of beginning of sequence foreach, filter, map,… s ……

53 Arrays - Example

54 Stack, Queue Stack – מחסנית Applications: Function’s stack Implementation ideas Queue – תור, First In First Out (FIFO) Applications: Scheduling, typing Implementation idea Cyclic Queue

55 Binary Search Input: A sorted array of integers A An integer query q Output: The index of q in A if q is a member of A -1 otherwise Algorithm: Check the middle element of A If it is equal to q, return its index If it is >= q, search for q in A[0,…,middle-1] If it is < q, search for q in A[middle+1,...,end]

56 Time Complexity of BS Worst case analysis Size of the inspected array: n  n/2  n/4  …..  1 Each step is very fast (a small constant number of operations) There are log 2 (n) such steps So it takes ~ log 2 (n) steps per search Much faster then ~ n

57 Bubble Sort n iterations i iterations constant n * (n-1 + n-2 + n-3 + …. + 1) * const ~ ½ * n 2

58 Marge Sort If the array is of length 0 or 1, then it is already sorted. Otherwise: Divide the unsorted array into two sub-arrays of about half the size Sort each sub-array recursively by re-applying merge sortrecursively Merge the two sub-arrays back into one sorted arrayMerge n + 2 * (n/2) * n/ * n/2 3 + … + 2log(n) * n/2 log(n) = n + n + … + n = n * log(n) log(n)

59 Bucket Sort Linear-time sorting algorithm! But: restrictions on data – bounded integers…

60 Quick Sort Want to hear about it?

61 Scala Memory Model Passing arguments to functions, local names Objects in memory Stack, Heap, Garbage collection

62 Object-Oriented Programming Represent problem-domain entities using a computer language Abstraction Classes as blueprint / data-types Scala API (and Java’s)

63 Rational Numbers Example Customize classes so that they are natural to use fields, methods, primary constructor Method overriding Self reference (this) Define several constructors Encapsulation Define operators as method Method overloading Implicit conversions, companion object

64 Guest Lectures Prof. Nir Shavit Prof. Ran Canetti Prof. Ronitt Rubinfeld Dr. Lior Wolf

65 Art of Multiprocessor Programming65 Real-World Scaling Process 1.8x 2x 2.9x User code Multicore Speedup Parallelization and Synchronization require great care…

66 Art of Multiprocessor Programming 66 Mutual Exclusion or “Alice & Bob share a pond” AB

67 Complexity and Cryptography Hard problems Relation to Cryptography/Security

68 How can we understand?

69 The Gold Standard linear time algorithms: for inputs encoded by n bits/words, allow cn time steps (constant c ) Inadequate?

70 Example Definition: a list of size n is  -close to sorted if can delete at most.01 n values to make it sorted. Otherwise,.99-far. Sorted: Close: Far: Requirements for algorithm: pass sorted lists if list passes test, can change at most.99 fraction of list to make it sorted

71 Today הפתעה! (+ משובים) Finish Functional Objects Guest lecture by Dr. Lior Wolf 10:10 Course Summary ++ Lists More OOP (inheritance, hierarchy, polymorphism) Go home!

72 Programming in Scala Chapter 16: Working with Lists Chapter 22: Implementing Lists

73 Problems with Arrays Limited in space (static): the size of an array is defined as it is created Costly to perform dynamic operations (e.g., add an element)

74 Linked Lists Built out of links, each link holds: Data Pointer to the next link (tail) Pointer to the first element (head)

75 Linked Lists (cont.) Infinite loop? (link  link  link….) Nil – the empty list The elements have the same type

76 Lists Vs. Arrays ListArray Initialization / memory EconomicalWasteful Insert element FastSlow Remove element FastSlow Direct access No direct accessDirect access Traverse Linear

77 Functionality initiate isEmpty length add element remove element append reverse

78 Lists in Scala List class have a type parameter T (similar to Arrays…) List operations are based on three basic methods: isEmpty : Boolean – true iff the list is empty head : T – first element in list tail : List[T] – a list consisting of the elements except the first

79 Initiating Lists

80 Constructing Lists All lists are build from two fundamental building blocks: Nil :: (cons)

81 Example: Insertion Sort

82 Implementation of ::

83 Implementation of: length, map

84 Concatenating Lists

85 Reverse a List def rev[T](xs : List[T]) = { if (xs.isEmpty) xs else rev(xs.tail):::List(xs.head) } Complexity?

86 Higher Order Methods map filter partition foreach And more

87 Example - map map(_+1)  map((x:Int)=>x+1)

88 Example – filter, partition

89 Example – filter, partition

90 Example – foreach

91 Example – sort

92 Other Data Structures Trees Maps

93 Example var capital = Map( "US"  "Washington", "France"  "paris", "Japan"  "tokyo" ) capital += ( "Russia"  "Moskow" ) for ( (country, city)  capital ) capital += ( country  city.capitalize ) assert ( capital("Japan") == "Tokyo" )

94 Pattern Matching in Scala Here's a a set of definitions describing binary trees: And here's an inorder traversal of binary trees: This design keeps purity: all cases are classes or objects extensibility: you can define more cases elsewhere encapsulation: only parameters of case classes are revealed abstract class Tree[T] case object Empty extends Tree case class Binary(elem: T, left: Tree[T], right: Tree[T]) extends Tree def inOrder [T] ( t: Tree[T] ): List[T] = t match { case Empty => List() case Binary(e, l, r) => inOrder(l) ::: List(e) ::: inOrder(r) } The case modifier of an object or class means you can pattern match on it

95 Today הפתעה! (+ משובים) Finish Functional Objects Guest lecture by Dr. Lior Wolf 10:10 Course Summary ++ Lists More OOP (inheritance, hierarchy, polymorphism) Go home!

96 More OOP (only talking…) Inheritance Class Hierarchy Polymorphism

97 Scala Hierarchy

98 Today הפתעה! (+ משובים) Finish Functional Objects Guest lecture by Dr. Lior Wolf 10:10 Course Summary ++ Lists More OOP (inheritance, hierarchy, polymorphism) Go home!

99 Thanks / References Guest lecturers: Nir Shavit, Ran Canetti, Ronitt Rubinfeld, Lior Wolf Administration: Avia, Pnina References: “Programming in Scala” Jackie Assa Sheme Course

100 שנה טובה! תהנו משארית החופשה!