CS 116 Fall 2016 Review Notes Created By: Rina Dong

Size: px
Start display at page:

Download "CS 116 Fall 2016 Review Notes Created By: Rina Dong"

Transcription

1 Design Recipe: ü Purpose Explicitly indicate what the function does, including how the parameters are used. (Function name, parameters name, how the parameters are used) Example: fn_name(p1, p2,, pn) consumes., and produces. ü Effect If function mutates the contents of a parameter, this must be included in the Purpose and Effect statement Possible effects of a function: 1. Printing to screen (have print statement in the function) 2. Reading from keyboard (ask for user input) 3. Mutation of parameter (e.g., mutate the list) ü Contract Types of consumed and produced values. Example: fn_name: type_of_p1 type_of_p2 type_of_pn > produced_type Data types Nat: 0 + all the positive integer (immutable) {ONLY USED in design recipe} Int: all the negative integer all the positive integer (immutable) Float: rational and irrational numbers (3 is Int or Nat, 3.0 is a Float) (immutable) Str: have single quotes ( ) or double quotes ( ) (immutable) Bool: Boolean return one of True or False (immutable) (listof ): a list of somethings (somethings can be Nat Int Float Str or (listof..)) None: the function returns nothing (BUT the function may mutate the parameters or do somethings else) (anyof ): data type can be one of ü Requires Function has any restrictions or requirements about parameters (consumed values only) Example: Requires: ü Examples Need to write at least 2 examples (one base case and one non-base case). Also, in python, examples are COMMENTS Example: fn_name(p1, p2,, pn) => expected_value

2 ü Function def : ü Tests import check Tests have to include ALL base cases and SOME non-base cases Mechanics of testing: check.expect( label the test, expr, value_expected) check.within( label the test, expr, value_expected, tolerance) {tolerance: close enough value} check.set_screen( description of expected screen output ) check.set_input([ a, list, of, string ]) {user input is always a string} Using different mechanics for different situations: 1. Return number Nat & Int: check.expect() Float: check.within() 2. Return string and list check.expect() 3. Having user input ONLY check.set_input() + check.expect() 4. Having print statement ONLY check.set_screen() + check.expect() 5. Mutation check.expect() + check.expect() OR check.within() {first need to check the output of function is None, and check the parameter is mutated. When one item in the list is a floating point number should use check.within}

3 The math Module: Basic Mathematical Operations ü Addition (+), Substraction (-), Multiplication (*) Int Int -> Int OR Nat Nat -> Nat Float (anyof Int Nat Float) -> Float ü Division (/) Always produce Float ü Integer division (//) Int Int -> Int Float (anyof Float Int Nat) -> Float (but with the decimal part being.0) ü Remainder (%) Int Int -> Nat ü Exponents (**) (anyof Int Nat Float) (anyof Int Nat Float) -> (anyof Int Nat Float) More math function import math ü math.sqrt(n) => n ü math.log(n, b) => log b (n) ü math.log(n) => ln(n) ü math.floor(n) => largest integral value <= n ü math.ceil(n) => smallest integral value >= n ü math.factorial(n) => n! = n x (n-1) x (n-2) x x 1

4 Boolean Expressions & Conditional Statements ü Bool expressions will return True or False e.g., ==, >, <, >=, <=,!=, and, or ü Conditional statement 1. Basic conditional statement If test: true_action 2. Another conditional statement If test: true_action else: false_action 3. Chained Conditional statement if test1: true_action_test1 elif test2: true_action2_test2 else: false_action 4. Nested conditional statement If test1: true_action_test1 if test2: true_action_test2 elif/else elif/else 5. Separated conditional statement if test1: true_action1 else: false_action1 if test2: true_action2 else: false_action2

5 The string Module & Print & User Input: ü string operations 1. s in t (s is a substring of t? => Bool) 2. len(s) => length of s 3. s[i:j] => substring from string s 4. +: combine two or more strings ü string methods s = this is a string 1. s.find("s ) => 3 {only for the first s } 2. s.find( s, 11, 15) => -1 { s is not in tring } 3. s.split() => ['this', 'is', 'a', 'string'] {return a list of string} 4. s.isupper() 5. s.islower() 6. s.isnumeric() ü Print statement 1. Has an effect 2. Produces None 3. print(x) => None {x can be any type of data} ü The format method print( CS116 ISAs are {0}, {1}, and {2}..format( Ian, Liyan, Rina )) 1. Uses the embedded {#} to show where a value should be inserted in the new string 2. The # indicates which of the format arguments (0 - n) should appear at the location of the string. ü User input user_input = input(prompt) OR user_input = input() 1. Prints the value of prompt (if have) before reading any characters 2. Value produced by input is always a Str 3. Must be described in the Purpose statement (describe what happens with the value entered by the user, use relevant parameter names in description) 4. Mentioned in the Effect statement ü Special Characters 1. \n print in a new line (newlines character), len( \n ) = 1

6 Lists: ü lists functions 1. len(l) => the length of L 2. L[i] => itme at position I, 0 <= i < len(l) 3. L[i:j] => [L[i], L[i+1],, L[j-1]] 4. L[i:j:k] => [L[i], L[i+k], L[i+2k],, L[i+m*k]], includes all the positions up to (but not including) j {empty case} 5. x in L => True if x in L, False otherwise 6. sum => produces the sum of all values in a list of numbers ü Mutation 1. L[i] = new_value => sign new_value to L[i] 2. L.append(add_value) => add_value appears at the end of L 3. L.extend((listof )) => add a list of value at the end of L 4. L.insert(p, value) => insert value in L[p], len(l) increases by 1 5. L.remove(value) =>remove the value (first time appears in L) 6. L.pop(p) => return the value in L[p], and remove the value in L[p] ü Abstract list functions 1. list(map(fn, lst/string)) => apply fn to each item in lst/string, and return a new list 2. list(filter(fn, lst/string)) => apply fn to each item in lst/string, and only keep the item that fn return True (a new list) 3. lambda x1, x2,, xn: body => body should be an expression

7 Recursions: ü Countup & Countdown template def countdown_fn(n): if n == 0: return base_answer else: answer = n countdown_fn(n-1) return answer { countup need to change the base case and n increase} ü Basic List template def basic_list_fn(lst): if lst == []: return base_answer else:..lst[0].. return basic_list_fn(lst[1:]) ü Accumulative Recursion def acc_helper(acc, remaining,...): # if at stopping case of remaining # return (answer using acc) # else: # return acc_helper(updated acc, # updated remaining....) def fn(...): # process result of calling # acc_helper(initial acc, # initial remaining,...) # Note: consider special cases, as needed ü Generative Recursion ü Functions: return none

8 Iteration ü while loop 1. while loop template ## initialize loop variables while (test): ## body, including statements to: ## - update variables used in test ## - update value being calculated ## additional processing 2. while loop basics - If the continuation test is True => Execute the loop body - If the continuation test is False => Do not execute the loop body - After completing the loop body => Evaluate the continuation test again - The body usually includes a mutation of variables used in the continuation test 3. Steps for writing a while loop You must determine: how to initialize variables outside the loop when the loop body should be executed, or, when it should stop what variables must be updated in the loop body so the loop will eventually stop what other actions are needed within the loop bod 4. Tests for while loop - the body executes zero times - the body executes exactly one time - the body executes a "typical" number of times - the body executes the maximum number of times ü for loop 1. for loop template for item in collection: loop_body 2. for loop basics Iterate over all members in a collection Called bounded iteration 3. range is an iterator. It can generate a collection, and the next value in the range is computed automatically with each pass through the for loop.

9 ü while and for loop > while loop - Loop counter should be initialized outside loop. - Includes continuation test before body. - Should update loop variables in body of loop. - Body contains steps to repeat > for loop - Loop counter initialized automatically - Continues while more elements in collection, or more values in iterator - Loop variable updated automatically do not update in loop - Body contains steps to repeat

10 Efficiency ü Time efficiency: how long it takes an algorithm to solve a problem. Depends on its implementation ü Running time is always stated as a function of n. We denote it by T(n) Let n refer to the size: Length of list Number of characters in a string Number of digits in a Nat Meaning should be specified if not clear ü Best case & Worst case - the minimum value of T(n) possible for a fixed value of n => best case - the largest value of T(n) possible for a fixed value of n => worst case ü Big O notation 1. The order of a running time: the order is the dominant term without its coefficient. This is called the asymptotic run time. 2. The orders arranged from smallest to largest: O(1) < O(log n) < O(n) < O(n log n) < O(n 2 ) < O(2 n ) 3. Big O arithmetic: - Add => the result is the largest of the two orders - Multiply => the result is the product of the two orders ü Basic Operations in Python Numerical operations: +,-,*,/,= are O(1) max(a,b), min(a,b) are O(1) String operations, where n = len(s) len(s), s[k] are O(1) s + t is O(n + len(t)) Most string methods (e.g. count, find, lower) are O(n) print and input are dependent on the length of what is being printed and read in when n = len(l) - len(l), L[k] are O(1) - L + M is O (n + len M) L + [x] is O(n) - sum(l), max(l), min(l) are O(n) - L[a:b] is O(b a), so at most O(n) L[1:]is O n - L.append(x) is O(1) - list(range(n)) is O(n)

11 - Most other list methods on L (e.g. count, index, insert, pop, remove) are O(n) - L.sort() is O(n log n) ü Common Summations O 1 = O(log n) O(1) = O(n) O(n) = O(n : ) O(i) = O(n : ) ü Recurrence Relations T(n) = O(1) + T(n-1) = O(n) T(n) = O(n) + T(n-1) =O(n 2 ) T(n) = O(1) + T(n/2) = O(log n) T(n) = O(1) +2 * T(n/2) = O(n) T(n) = O(n) + 2 * T(n/2) = O(n log n) OR T(n) = O(n) + T(n/2) = O(n log n) T(n) = O(1) + T(n-1) + T(n-2) = O(2 n ) OR T(n) = O(1) + 2 * T(n-1) = O(2 n ) ü Abstract list functions => map(f, L), filter(f, L) are at least O(n)

12 Searching and Sorting Algorithms ü Algorithm (called Linear Search) Implementing Linear Search ## linear_search(l, target) ## produces True if target is in L, ## False otherwise ## linear_search: (listof X) X -> Bool ## Note: equivalent to: target in L def linear_search (L, target): for val in L: if val == target: return True return False Best case => O(1) Worst case => O(n) ü Binary Search Implementing Binary Search def binary_search(l, target): beginning = end = while : middle = if L[middle] == target: return True elif L[middle] > target : else: return False Test cases: 1. empty list 2. list of length 1: target in list and not in list 3. small list, both even and odd lengths 4. larger list target outside list, i.e. target < L[0] or target > L[len(L)-1] target in the list, various positions (first, last, middle) target not in the list, value between two list consecutive values

13 Worst case => O(log n) ü Selection Sort Implementing Selection Sort def selection_sort(l): n = len(l) positions = list(range(n-1)) for i in positions: min_pos = i for j in range(i,n): if L[j] < L[min_pos]: min_pos = j temp = L[i] L[i] = L[min_pos] L[min_pos] = temp Runtime: O(n 2 ) ü Insertion Sort Implementing Insertion Sort # insert(l,pos) sorts L[0:pos] when L[0:pos-1] is already sorted. def insert(l, pos): while pos > 0 and L[pos] < L[pos-1]: temp = L[pos] L[pos] = L[pos-1] L[pos-1] = temp pos = pos-1 def insert_sort(l): for i in range(1,len(l)): insert(l,i) Runtime: O(n 2 ) ü Merge sort Implementing Merge sort: def merge(l1, L2, L): pos1 = 0 pos2 = 0 posl = 0 while (pos1 < len(l1)) and (pos2 < len(l2)): if L1[pos1] < L2[pos2]:

14 L[posL] = L1[pos1] pos1 += 1 else: L[posL] = L2[pos2] pos2 += 1 posl += 1 while (pos1 < len(l1)): L[posL] = L1[pos1] pos1 = pos1+1 posl = posl+1 while (pos2 < len(l2)): L[posL] = L2[pos2] pos2 = pos2+1 posl = posl+1 def mergesort(l): if len(l) < 2: return mid = len(l)//2 L1 = L[:mid] L2 = L[mid:] mergesort(l1) mergesort(l2) merge(l1, L2, L) Runtime: O(n log n) ü Quick Sort Implementing Quick Sort # quicksort(lst) sorts a list of integers, lst, using the # quicksort algorithm. # quicksort: (listof Int) -> (listof Int) def quicksort(lst): if lst == []: return [] n = lst[0] lst1 = list(filter(lambda x: x < n, lst)) lst2 = list(filter(lambda x: x > n, lst)) return quicksort(lst1) + [n] + quicksort(lst2) Runtime: O(n 2 )

15 ü Sorting Summary Algorithm best case worst case Insertion sort O(n) O(n : ) Selection sort O(n : ) O(n : ) Merge sort O(n log n) O(n log n) Quick sort O(n log n) O(n : )

16 Dictionaries (key-value collections) ü Use {} for dictionaries ü Data Type: (dictof Key_type Value_type) ü The type used for the key must be immutable (e.g. Str, Int) ü Any type can be used for the value ü Keys are not sorted or ordered ü Dictionary Operations: Retrieve a value by using its key as an index d[key] => value Update a value by using its key as an index && Add a value by using its key as an index d[key] = value len(d) => number of pairs in d d.keys() => a view of keys in d. list(d.keys) => list of keys d.values() => a view of values in d. list(d.values) => list of values k in d => True if k is a key in d d.pop(k) => value for k, and removes k:value from d

17 Classes ü including several very important methods in our classes to help with Creating objects Printing objects Comparing objects ü These methods will use the local name self to refer to the object being used ü init class name: def init (self, f1, f2, ): self.field1 = f1 self.field2 = f2 Creates the class Call the fields by: x = name(field1,field2, ) x.field1 ü repr def repr (self): return "name: {0},{1}, ".format(self.field1, self.field2, ) ü eq def eq (self, other): return isinstance(other, name) and \ self.field1 == other.field1 and \ self.field2 == other.field2 and \ If two classes have the same fields (and are not aliases), it is used to ensure that they produce True.

18 File Input and Output ü Step 1: Finding a file ü Step 2: Opening a file open(filename, "r") or open(filename) opens the file named filename for reading open(filename, "w") creates the file named filename for writing. If there is already a file named filename, its contents are erased before the new data is written. ü Step 3: Accessing files - reading f.readline() Returns the next line from file f Includes newline character Returns the empty string when at end of file f.readlines() Returns a list of strings containing each line from file f Each string terminates with newline character (if present in file) If file is very large, this may consume a lot of memory Template for reading from a file input_file = open(filename, "r") ## read file using ## input_file.readline() in a loop, or ## input_file.readlines() ## Note: resulting strings ## contain newline input_file.close() ü Step 3: Accessing files - reading f.write(s) Appends the string s to the end of file f Writes the newline character only if s includes it f.writelines(los) Appends all the strings in los to the end of file f Writes newline characters only for those strings in los which include it Template for writing to a file output_file = open(filename, "w") ## write to file using ## output_file.write(s) in a loop, or

19 ## output_file.writelines(los) ## Note: newlines are written only ## if strings include them output_file.close() ü Step 4: Closing a file f.close() Closes the file f If you forget to close a file after writing, you may lose some data You can no longer access a file after it has been closed ü The Design Recipe and Files: Purpose: Should include details about what is read from a file or written to a file Effects: Should mention reading from a file or writing to a file (don't need details here) Testing file input # process_file: Str -> (listof Int) def process_file(filename): f = open(filename, "r") Set up a test file of data, and include a comment describing contents of file. e.g., check.expect('q1t1', process_file("q1t1file.txt"), [2,4,6]) Testing file output 1. check.set_file_exact(actual, expected) actual name of file created by program expected name of file you created with the expected output 2. check.set_file(actual, expected) actual name of file created by program expected name of file you created with the expected output Differences: this version ignores whitespace in the two files 3. check.set_file() or check.set_file_exact() + check.expect() ü Sorting Characters ord(c) len(c) = 1 Produces the ASCII code for character c e.g. ord('a') => 97, ord('\n') => 10 chr(code) 0 <= code <= 255 Produces the string containing the character with the given code e.g. chr(100) => 'd', chr(32) => ' '

20 Graph Theory ü Undirected Graph An undirected graph G is a set V, of vertices, and a collection E, of unordered pairs from V, called edges. We write G=(V,E). The edges may (or may not) have weights associated with them. If (v k, v p ) is an edge, we say that vk and vp are neighbours, and are adjacent The number of neighbours of a vertex is also called its degree A sequence of nodes v 1, v 2,, v k is a path of length k-1 if (v 1, v 2 ),(v 2, v 3 ),,(v k-1, v k ) are all edges If v 1 = v k, this is called a cycle A graph G is connected if there exists a path through all vertices in G Results in graph: Let n = number of vertices, and m = number of edges: 1. m n(n 1)/2 2. The number of graphs on n vertices is 2 n(n-1)/2 3. The sum of the degrees over all vertices is 2m. Edge list: [e 1, e 2, e 3,, e m ], where edge e j = [a, b] when vertices a and b are connected by an edge Adjacency list: 1. For each vertex: Store the labels on its neighbours in a list 2. We will use a dictionary Keys: labels of vertices Associated values: List of neighbours (adjacent vertices) Adjacency Matrix: 1. For simplicity, assume vertices are labelled 0,, n 1 2. Create an n*n matrix for G If there is an edge connecting i and j: Set G[i][j] = 1 Set G[j][i] = 1 3. Otherwise, set these values to 0 ü Graph Traversals Breadth-first search(bfs) Definition: choose a starting point v => visit all the neighbours of v => visit all the neighbours of the neighbours of v, etc. => repeat until all reachable vertrices are visited => need some way to avoid visiting edges more than one

21 Implementation: def bfs(graph, v): all = [] Q = [] Q.append(v) while Q!= []: v = Q.pop(0) all.append(v) for n in graph[v]: if n not in Q and n not in all: Q.append(n) return all Depth-first search (dfs) Definition: choose a starting point v => proceed along a path from v as far as possible => backup to previous (most recently visited) vertex, and visit its unvisited neighbor (this is called backtracking) => repeat while unvisited, reachable vertices remain Implementation: def dfs(graph, v): visited = [] S = [v] while S!= []: v = S.pop() if v not in visited: visited.append(v) for w in graph[v]: if w not in visited: S.append(w) return visited

Module 08: Searching and Sorting Algorithms

Module 08: Searching and Sorting Algorithms Module 08: Searching and Sorting Algorithms Topics: Searching algorithms Sorting algorithms 1 Application: Searching a list Suppose you have a list L. How could you determine if a particular value is in

More information

List Mutation (Module 4) Accumulative Recursion (Module 5) Efficiency (Module 7) Searching & Sorting (Module 8) Dictionaries (Module 9)

List Mutation (Module 4) Accumulative Recursion (Module 5) Efficiency (Module 7) Searching & Sorting (Module 8) Dictionaries (Module 9) Sherry & Pauline List Mutation (Module 4) Review for CS 116!!! Accumulative Recursion (Module 5) Efficiency (Module 7) Searching & Sorting (Module 8) Dictionaries (Module 9) Class Objects (Module 9) Files

More information

Module 07: Efficiency

Module 07: Efficiency Module 07: Efficiency Topics: Basic introduction to run-time efficiency Analyzing recursive code Analyzing iterative code 1 Consider the following two ways to calculate the maximum of a nonempty list.

More information

Module 11: Additional Topics Graph Theory and Applications

Module 11: Additional Topics Graph Theory and Applications Module 11: Additional Topics Graph Theory and Applications Topics: Introduction to Graph Theory Representing (undirected) graphs Basic graph algorithms 1 Consider the following: Traveling Salesman Problem

More information

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines.

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines. 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

CSC148 Fall 2017 Ramp Up Session Reference

CSC148 Fall 2017 Ramp Up Session Reference Short Python function/method descriptions: builtins : input([prompt]) -> str Read a string from standard input. The trailing newline is stripped. The prompt string, if given, is printed without a trailing

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

Module 01: Introduction to Programming in Python

Module 01: Introduction to Programming in Python Module 01: Introduction to Programming in Python Topics: Course Introduction Introduction to Python basics Readings: ThinkP 1,2,3 1 Finding course information https://www.student.cs.uwaterloo.ca/~cs116/

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

TUTORIAL 9 DICTIONARIES AND CLASSES

TUTORIAL 9 DICTIONARIES AND CLASSES TUTORIAL 9 DICTIONARIES AND CLASSES REMINDER Assignment 08 is due March 23 rd at 8 AM REVIEW Dictionary Classes init repr eq class methods DICTIONARY {key1:value1, key2:value2, } Each element has a key

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

Module 06. Topics: Iterative structure in Python Readings: ThinkP 7. CS116 Spring : Iteration

Module 06. Topics: Iterative structure in Python Readings: ThinkP 7. CS116 Spring : Iteration Module 06 Topics: Iterative structure in Python Readings: ThinkP 7 1 In Python, repetition can be recursive def count_down_rec(x): ''' Produces the list [x, x-1, x-2,..., 1,0] count_down:nat->(listof Nat)'''

More information

Module 09: Additional Options for Organizing Data

Module 09: Additional Options for Organizing Data Module 09: Additional Options for Organizing Data Topics: Dictionaries Classes Readings: ThinkP 11, 15, 16, 17 1 Collections of key-value pairs In CS115, you studied collections of key-value pairs, where

More information

Working with recursion. From definition to template. Readings: HtDP, sections 11, 12, 13 (Intermezzo 2).

Working with recursion. From definition to template. Readings: HtDP, sections 11, 12, 13 (Intermezzo 2). Working with recursion Readings: HtDP, sections 11, 12, 13 (Intermezzo 2). We can extend the idea of a self-referential definition to defining the natural numbers, which leads to the use of recursion in

More information

Module 3: Strings and Input/Output

Module 3: Strings and Input/Output Module 3: Strings and Input/Output Topics: Strings and their methods Printing to standard output Reading from standard input Readings: ThinkP 8, 10 1 Strings in Python: combining strings in interesting

More information

Working with recursion

Working with recursion Working with recursion Readings: HtDP, sections 11, 12, 13 (Intermezzo 2). We can extend the idea of a self-referential definition to defining the natural numbers, which leads to the use of recursion in

More information

CS116 - Module 5 - Accumulative Recursion

CS116 - Module 5 - Accumulative Recursion CS116 - Module 5 - Accumulative Recursion Cameron Morland Winter 2018 1 Cameron Morland CS116 - Module 5 - Accumulative Recursion Types of Recursion Structural Recursion Generative Recursion Accumulative

More information

Question 1. Part (a) Part (b) December 2013 Final Examination Marking Scheme CSC 108 H1F. [13 marks] [4 marks] Consider this program:

Question 1. Part (a) Part (b) December 2013 Final Examination Marking Scheme CSC 108 H1F. [13 marks] [4 marks] Consider this program: Question 1. Part (a) [4 marks] Consider this program: [13 marks] def square(x): (number) -> number Write what this program prints, one line per box. There are more boxes than you need; leave unused ones

More information

Generative and accumulative recursion. What is generative recursion? Example revisited: GCD. Readings: Sections 25, 26, 27, 30, 31

Generative and accumulative recursion. What is generative recursion? Example revisited: GCD. Readings: Sections 25, 26, 27, 30, 31 Generative and accumulative recursion Readings: Sections 25, 26, 27, 30, 31 Some subsections not explicitly covered in lecture Section 27.2 technique applied to strings CS 135 Fall 2017 11: Generative

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 DECEMBER 2013 EXAMINATIONS CSC 108 H1F Instructors: Craig and Gries Duration 3 hours PLEASE HAND IN Examination Aids: None Student Number:

More information

Python: Short Overview and Recap

Python: Short Overview and Recap Python: Short Overview and Recap Benjamin Roth CIS LMU Benjamin Roth (CIS LMU) Python: Short Overview and Recap 1 / 39 Data Types Object type Example creation Numbers (int, float) 123, 3.14 Strings this

More information

Python review. 1 Python basics. References. CS 234 Naomi Nishimura

Python review. 1 Python basics. References. CS 234 Naomi Nishimura Python review CS 234 Naomi Nishimura The sections below indicate Python material, the degree to which it will be used in the course, and various resources you can use to review the material. You are not

More information

Module 8: Local and functional abstraction

Module 8: Local and functional abstraction Module 8: Local and functional abstraction Readings: HtDP, Intermezzo 3 (Section 18); Sections 19-23. We will cover material on functional abstraction in a somewhat different order than the text. We will

More information

CS-141 Final Exam Review December 8, 2017 Presented by the RIT Computer Science Community

CS-141 Final Exam Review December 8, 2017 Presented by the RIT Computer Science Community CS-141 Final Exam Review December 8, 2017 Presented by the RIT Computer Science Community http://csc.cs.rit.edu Python Basics 1. Although most in the industry will be reasonably forgiving when it comes

More information

CS116 - Module 10 - File Input/Output

CS116 - Module 10 - File Input/Output CS116 - Module 10 - File Input/Output Cameron Morland Winter 2018 Reminder: if you have not already, ensure you: Read Think Python, chapters 8, 12, 14. 1 Cameron Morland CS116 - Module 10 - File Input/Output

More information

Review Sheet for Midterm #1 COMPSCI 119 Professor William T. Verts

Review Sheet for Midterm #1 COMPSCI 119 Professor William T. Verts Review Sheet for Midterm #1 COMPSCI 119 Professor William T. Verts Simple Data Types There are a number of data types that are considered primitive in that they contain only a single value. These data

More information

CS-141 Final Exam Review December 16, 2015 Presented by the RIT Computer Science Community

CS-141 Final Exam Review December 16, 2015 Presented by the RIT Computer Science Community CS-141 Final Exam Review December 16, 2015 Presented by the RIT Computer Science Community http://csc.cs.rit.edu Python Basics 1. Although most in the industry will be reasonably forgiving when it comes

More information

15110 Principles of Computing, Carnegie Mellon University - CORTINA. Binary Search. Required: List L of n unique elements.

15110 Principles of Computing, Carnegie Mellon University - CORTINA. Binary Search. Required: List L of n unique elements. UNIT 5B Binary Search 1 Binary Search Required: List L of n unique elements. The elements must be sorted in increasing order. Result: The index of a specific element (called the key) or None if the key

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

CS-141 Final Exam Review May 16, 2015 Presented by the RIT Computer Science Community

CS-141 Final Exam Review May 16, 2015 Presented by the RIT Computer Science Community CS-141 Final Exam Review May 16, 2015 Presented by the RIT Computer Science Community http://csc.cs.rit.edu Python Basics 1. Although most in the industry will be reasonably forgiving when it comes to

More information

Lab 6 Sorting. Sup Biotech 3 Python. Pierre Parutto

Lab 6 Sorting. Sup Biotech 3 Python. Pierre Parutto Lab 6 Sorting Sup Biotech 3 Python Pierre Parutto October 31, 2016 Preamble Document Property Authors Pierre Parutto Version 1.0 Number of pages 7 Contact Contact the assistant team at: supbiotech-bioinfo-bt3@googlegroups.com

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

CS 115 Exam 3, Fall 2016, Sections 5-8

CS 115 Exam 3, Fall 2016, Sections 5-8 , Sections 5-8 Your name: Rules You may use one handwritten 8.5 x 11 cheat sheet (front and back). This is the only resource you may consult during this exam. Explain/show work if you want to receive partial

More information

Multiple-choice (35 pt.)

Multiple-choice (35 pt.) CS 161 Practice Midterm I Summer 2018 Released: 7/21/18 Multiple-choice (35 pt.) 1. (2 pt.) Which of the following asymptotic bounds describe the function f(n) = n 3? The bounds do not necessarily need

More information

CS115 - Module 9 - filter, map, and friends

CS115 - Module 9 - filter, map, and friends Fall 2017 Reminder: if you have not already, ensure you: Read How to Design Programs, Intermezzo 3 (Section 18); Sections 19-23. Abstraction abstraction, n. 3a.... The process of isolating properties or

More information

Lab 6 Sorting. Sup Biotech 3 Python. Pierre Parutto

Lab 6 Sorting. Sup Biotech 3 Python. Pierre Parutto Lab 6 Sorting Sup Biotech 3 Python Pierre Parutto November 23, 2016 Preamble Document Property Authors Pierre Parutto Version 1.0 Number of pages 11 Contact Contact the assistant team at: supbiotech-bioinfo-bt3@googlegroups.com

More information

Sorting Pearson Education, Inc. All rights reserved.

Sorting Pearson Education, Inc. All rights reserved. 1 19 Sorting 2 19.1 Introduction (Cont.) Sorting data Place data in order Typically ascending or descending Based on one or more sort keys Algorithms Insertion sort Selection sort Merge sort More efficient,

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 APRIL 2010 EXAMINATIONS CSC 108 H1S Instructors: Horton Duration 3 hours PLEASE HAND IN Examination Aids: None Student Number: Family Name(s):

More information

Module 05: Types of recursion

Module 05: Types of recursion Module 05: Types of recursion Topics: Review of purely structural recursion Accumulative recursion Generative recursion Readings:ThinkP 5.8-5.10, 6.5-6.7 1 Review: Structural Recursion Template for code

More information

Summer 2017 Discussion 10: July 25, Introduction. 2 Primitives and Define

Summer 2017 Discussion 10: July 25, Introduction. 2 Primitives and Define CS 6A Scheme Summer 207 Discussion 0: July 25, 207 Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write Scheme programs,

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 SUMMER 2012 EXAMINATIONS CSC 108 H1Y Instructors: Janicki Duration NA PLEASE HAND IN Examination Aids: None Student Number: Family Name(s):

More information

COMP 250 Fall recurrences 2 Oct. 13, 2017

COMP 250 Fall recurrences 2 Oct. 13, 2017 COMP 250 Fall 2017 15 - recurrences 2 Oct. 13, 2017 Here we examine the recurrences for mergesort and quicksort. Mergesort Recall the mergesort algorithm: we divide the list of things to be sorted into

More information

LISTS WITH PYTHON. José M. Garrido Department of Computer Science. May College of Computing and Software Engineering Kennesaw State University

LISTS WITH PYTHON. José M. Garrido Department of Computer Science. May College of Computing and Software Engineering Kennesaw State University LISTS WITH PYTHON José M. Garrido Department of Computer Science May 2015 College of Computing and Software Engineering Kennesaw State University c 2015, J. M. Garrido Lists with Python 2 Lists with Python

More information

INSTITUTE OF AERONAUTICAL ENGINEERING

INSTITUTE OF AERONAUTICAL ENGINEERING INSTITUTE OF AERONAUTICAL ENGINEERING (Autonomous) Dundigal, Hyderabad - 500 043 COMPUTER SCIENCE AND ENGINEERING TUTORIAL QUESTION BANK Course Name Course Code Class Branch DATA STRUCTURES ACS002 B. Tech

More information

Algorithms and Programming

Algorithms and Programming Algorithms and Programming Lecture 9 Computational complexity, Search and sorting algorithms Camelia Chira Course content Programming in the large Programming in the small Introduction in the software

More information

Introduction to Concepts in Functional Programming. CS16: Introduction to Data Structures & Algorithms Spring 2017

Introduction to Concepts in Functional Programming. CS16: Introduction to Data Structures & Algorithms Spring 2017 Introduction to Concepts in Functional Programming CS16: Introduction to Data Structures & Algorithms Spring 2017 Outline Functions State Functions as building blocks Higher order functions Map Reduce

More information

CS 115 Exam 3, Fall 2015, Sections 1-4

CS 115 Exam 3, Fall 2015, Sections 1-4 , Sections 1-4 Your name: Rules You may use one handwritten 8.5 x 11 cheat sheet (front and back). This is the only resource you may consult during this exam. Explain/show work if you want to receive partial

More information

UNIVERSITY OF TORONTO SCARBOROUGH. December 2017 EXAMINATIONS. CSCA20H3 Duration 3 hours. Examination Aids: Instructor: Bretscher

UNIVERSITY OF TORONTO SCARBOROUGH. December 2017 EXAMINATIONS. CSCA20H3 Duration 3 hours. Examination Aids: Instructor: Bretscher PLEASE HAND IN UNIVERSITY OF TORONTO SCARBOROUGH December 2017 EXAMINATIONS CSCA20H3 Duration 3 hours PLEASE HAND IN Examination Aids: None Student Number: Last (Family) Name(s): First (Given) Name(s):

More information

CSE 100: GRAPH ALGORITHMS

CSE 100: GRAPH ALGORITHMS CSE 100: GRAPH ALGORITHMS 2 Graphs: Example A directed graph V5 V = { V = E = { E Path: 3 Graphs: Definitions A directed graph V5 V6 A graph G = (V,E) consists of a set of vertices V and a set of edges

More information

Introduction to the Analysis of Algorithms. Algorithm

Introduction to the Analysis of Algorithms. Algorithm Introduction to the Analysis of Algorithms Based on the notes from David Fernandez-Baca Bryn Mawr College CS206 Intro to Data Structures Algorithm An algorithm is a strategy (well-defined computational

More information

Reading for this lecture (Goodrich and Tamassia):

Reading for this lecture (Goodrich and Tamassia): COMP26120: Algorithms and Imperative Programming Basic sorting algorithms Ian Pratt-Hartmann Room KB2.38: email: ipratt@cs.man.ac.uk 2017 18 Reading for this lecture (Goodrich and Tamassia): Secs. 8.1,

More information

Language Reference Manual

Language Reference Manual ALACS Language Reference Manual Manager: Gabriel Lopez (gal2129) Language Guru: Gabriel Kramer-Garcia (glk2110) System Architect: Candace Johnson (crj2121) Tester: Terence Jacobs (tj2316) Table of Contents

More information

Recitation 9. Prelim Review

Recitation 9. Prelim Review Recitation 9 Prelim Review 1 Heaps 2 Review: Binary heap min heap 1 2 99 4 3 PriorityQueue Maintains max or min of collection (no duplicates) Follows heap order invariant at every level Always balanced!

More information

UNIVERSITY OF TORONTO SCARBOROUGH. Wnter 2016 EXAMINATIONS. CSC A20H Duration 2 hours 45 mins. No Aids Allowed

UNIVERSITY OF TORONTO SCARBOROUGH. Wnter 2016 EXAMINATIONS. CSC A20H Duration 2 hours 45 mins. No Aids Allowed Student Number: Last Name: First Name: UNIVERSITY OF TORONTO SCARBOROUGH Wnter 2016 EXAMINATIONS CSC A20H Duration 2 hours 45 mins No Aids Allowed Do not turn this page until you have received the signal

More information

CS115 - Module 10 - General Trees

CS115 - Module 10 - General Trees Fall 2017 Reminder: if you have not already, ensure you: Read How to Design Programs, Sections 15 and 16. Arithmetic Expressions Recall with binary trees we could represent an expression containing binary

More information

CS 135 Winter 2018 Tutorial 7: Accumulative Recursion and Binary Trees. CS 135 Winter 2018 Tutorial 7: Accumulative Recursion and Binary Trees 1

CS 135 Winter 2018 Tutorial 7: Accumulative Recursion and Binary Trees. CS 135 Winter 2018 Tutorial 7: Accumulative Recursion and Binary Trees 1 CS 135 Winter 2018 Tutorial 7: Accumulative Recursion and Binary Trees CS 135 Winter 2018 Tutorial 7: Accumulative Recursion and Binary Trees 1 Goals of this tutorial You should be able to... understand

More information

10/5/2016. Comparing Algorithms. Analyzing Code ( worst case ) Example. Analyzing Code. Binary Search. Linear Search

10/5/2016. Comparing Algorithms. Analyzing Code ( worst case ) Example. Analyzing Code. Binary Search. Linear Search 10/5/2016 CSE373: Data Structures and Algorithms Asymptotic Analysis (Big O,, and ) Steve Tanimoto Autumn 2016 This lecture material represents the work of multiple instructors at the University of Washington.

More information

CS171 Midterm Exam. October 29, Name:

CS171 Midterm Exam. October 29, Name: CS171 Midterm Exam October 29, 2012 Name: You are to honor the Emory Honor Code. This is a closed-book and closed-notes exam. You have 50 minutes to complete this exam. Read each problem carefully, and

More information

Recursion defining an object (or function, algorithm, etc.) in terms of itself. Recursion can be used to define sequences

Recursion defining an object (or function, algorithm, etc.) in terms of itself. Recursion can be used to define sequences Section 5.3 1 Recursion Recursion defining an object (or function, algorithm, etc.) in terms of itself. Recursion can be used to define sequences Previously sequences were defined using a specific formula,

More information

COMP 161 Lecture Notes 16 Analyzing Search and Sort

COMP 161 Lecture Notes 16 Analyzing Search and Sort COMP 161 Lecture Notes 16 Analyzing Search and Sort In these notes we analyze search and sort. Counting Operations When we analyze the complexity of procedures we re determine the order of the number of

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

Midterm 1 Review. Important control structures. Important things to review. Functions Loops Conditionals

Midterm 1 Review. Important control structures. Important things to review. Functions Loops Conditionals Midterm 1 Review Important control structures Functions Loops Conditionals Important things to review Binary numbers Boolean operators (and, or, not) String operations: len, ord, +, *, slice, index List

More information

Python and Bioinformatics. Pierre Parutto

Python and Bioinformatics. Pierre Parutto Python and Bioinformatics Pierre Parutto October 9, 2016 Contents 1 Common Data Structures 2 1.1 Sequences............................... 2 1.1.1 Manipulating Sequences................... 2 1.1.2 String.............................

More information

SCHEME 8. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. March 23, 2017

SCHEME 8. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. March 23, 2017 SCHEME 8 COMPUTER SCIENCE 61A March 2, 2017 1 Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write Scheme programs,

More information

Choice of C++ as Language

Choice of C++ as Language EECS 281: Data Structures and Algorithms Principles of Algorithm Analysis Choice of C++ as Language All algorithms implemented in this book are in C++, but principles are language independent That is,

More information

SCHEME 7. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. October 29, 2015

SCHEME 7. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. October 29, 2015 SCHEME 7 COMPUTER SCIENCE 61A October 29, 2015 1 Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write Scheme programs,

More information

CITS3001. Algorithms, Agents and Artificial Intelligence. Semester 2, 2016

CITS3001. Algorithms, Agents and Artificial Intelligence. Semester 2, 2016 CITS3001 Algorithms, Agents and Artificial Intelligence Semester 2, 2016 Tim French School of Computer Science & Software Eng. The University of Western Australia 2. Review of algorithmic concepts CLRS,

More information

Use recursion to write a function that duplicates the following function: (def (f L) (map (lambda (x) (+ (sqr x) x)) L))

Use recursion to write a function that duplicates the following function: (def (f L) (map (lambda (x) (+ (sqr x) x)) L)) Write a function (multiply-each L n). It consumes a (listof Num) and a Num, and returns the list containing all the values in L, each multiplied by n. (multiply-each (list 2 3 5) 4) => (list 8 12 20) Write

More information

CS 115 Exam 3, Fall 2016, Sections 1-4

CS 115 Exam 3, Fall 2016, Sections 1-4 , Sections 1-4 Your name: Rules You may use one handwritten 8.5 x 11 cheat sheet (front and back). This is the only resource you may consult during this exam. Explain/show work if you want to receive partial

More information

TUPLES AND RECURSIVE LISTS 5

TUPLES AND RECURSIVE LISTS 5 TUPLES AND RECURSIVE LISTS 5 COMPUTER SCIENCE 61A July 3, 2012 1 Sequences From the Pig project, we discovered the utility of having structures that contain multiple values. Today, we are going to cover

More information

[CHAPTER] 1 INTRODUCTION 1

[CHAPTER] 1 INTRODUCTION 1 FM_TOC C7817 47493 1/28/11 9:29 AM Page iii Table of Contents [CHAPTER] 1 INTRODUCTION 1 1.1 Two Fundamental Ideas of Computer Science: Algorithms and Information Processing...2 1.1.1 Algorithms...2 1.1.2

More information

Short Python function/method descriptions:

Short Python function/method descriptions: Last Name First Name Student#. Short Python function/method descriptions: builtins : len(x) -> integer Return the length of the list, tuple, dict, or string x. max(l) -> value Return the largest value

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 DECEMBER 2009 EXAMINATIONS CSC 108 H1F Instructors: Gries, Horton, Zingaro Duration 3 hours PLEASE HAND IN Examination Aids: None Student

More information

Types of recursion. Structural vs. general recursion. Pure structural recursion. Readings: none. In this module: learn to use accumulative recursion

Types of recursion. Structural vs. general recursion. Pure structural recursion. Readings: none. In this module: learn to use accumulative recursion Types of recursion Readings: none. In this module: learn to use accumulative recursion learn to recognize generative recursion CS 135 Fall 2018 07: Types of recursion 1 Structural vs. general recursion

More information

CS 216 Exam 1 Fall SOLUTION

CS 216 Exam 1 Fall SOLUTION CS 216 Exam 1 Fall 2004 - SOLUTION Name: Lab Section: Email Address: Student ID # This exam is closed note, closed book. You will have an hour and fifty minutes total to complete the exam. You may NOT

More information

CSE 146. Asymptotic Analysis Interview Question of the Day Homework 1 & Project 1 Work Session

CSE 146. Asymptotic Analysis Interview Question of the Day Homework 1 & Project 1 Work Session CSE 146 Asymptotic Analysis Interview Question of the Day Homework 1 & Project 1 Work Session Comparing Algorithms Rough Estimate Ignores Details Or really: independent of details What are some details

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 APRIL 2012 EXAMINATIONS CSC 108 H1S Instructors: Campbell Duration 3 hours PLEASE HAND IN Examination Aids: None Student Number: Family

More information

The SPL Programming Language Reference Manual

The SPL Programming Language Reference Manual The SPL Programming Language Reference Manual Leonidas Fegaras University of Texas at Arlington Arlington, TX 76019 fegaras@cse.uta.edu February 27, 2018 1 Introduction The SPL language is a Small Programming

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

Lecture #15: Generic Functions and Expressivity. Last modified: Wed Mar 1 15:51: CS61A: Lecture #16 1

Lecture #15: Generic Functions and Expressivity. Last modified: Wed Mar 1 15:51: CS61A: Lecture #16 1 Lecture #15: Generic Functions and Expressivity Last modified: Wed Mar 1 15:51:48 2017 CS61A: Lecture #16 1 Consider the function find: Generic Programming def find(l, x, k): """Return the index in L of

More information

CS 115 Lecture 4. More Python; testing software. Neil Moore

CS 115 Lecture 4. More Python; testing software. Neil Moore CS 115 Lecture 4 More Python; testing software Neil Moore Department of Computer Science University of Kentucky Lexington, Kentucky 40506 neil@cs.uky.edu 8 September 2015 Syntax: Statements A statement

More information

Master Theorem, Introduction to Graphs

Master Theorem, Introduction to Graphs Master Theorem, Introduction to Graphs CSE21 Winter 2017, Day 10 (B00), Day 6-7 (A00) February 1, 2017 http://vlsicad.ucsd.edu/courses/cse21-w17 Divide & Conquer: General Strategy Divide the problem of

More information

GE PROBLEM SOVING AND PYTHON PROGRAMMING. Question Bank UNIT 1 - ALGORITHMIC PROBLEM SOLVING

GE PROBLEM SOVING AND PYTHON PROGRAMMING. Question Bank UNIT 1 - ALGORITHMIC PROBLEM SOLVING GE8151 - PROBLEM SOVING AND PYTHON PROGRAMMING Question Bank UNIT 1 - ALGORITHMIC PROBLEM SOLVING 1) Define Computer 2) Define algorithm 3) What are the two phases in algorithmic problem solving? 4) Why

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

CS61BL. Lecture 5: Graphs Sorting

CS61BL. Lecture 5: Graphs Sorting CS61BL Lecture 5: Graphs Sorting Graphs Graphs Edge Vertex Graphs (Undirected) Graphs (Directed) Graphs (Multigraph) Graphs (Acyclic) Graphs (Cyclic) Graphs (Connected) Graphs (Disconnected) Graphs (Unweighted)

More information

CSE373: Data Structures and Algorithms Lecture 4: Asymptotic Analysis. Aaron Bauer Winter 2014

CSE373: Data Structures and Algorithms Lecture 4: Asymptotic Analysis. Aaron Bauer Winter 2014 CSE373: Data Structures and Algorithms Lecture 4: Asymptotic Analysis Aaron Bauer Winter 2014 Previously, on CSE 373 We want to analyze algorithms for efficiency (in time and space) And do so generally

More information

1. [1 pt] What is the solution to the recurrence T(n) = 2T(n-1) + 1, T(1) = 1

1. [1 pt] What is the solution to the recurrence T(n) = 2T(n-1) + 1, T(1) = 1 Asymptotics, Recurrence and Basic Algorithms 1. [1 pt] What is the solution to the recurrence T(n) = 2T(n-1) + 1, T(1) = 1 1. O(logn) 2. O(n) 3. O(nlogn) 4. O(n 2 ) 5. O(2 n ) 2. [1 pt] What is the solution

More information

Scheme Quick Reference

Scheme Quick Reference Scheme Quick Reference COSC 18 Fall 2003 This document is a quick reference guide to common features of the Scheme language. It is not intended to be a complete language reference, but it gives terse summaries

More information

The ADT priority queue Orders its items by a priority value The first item removed is the one having the highest priority value

The ADT priority queue Orders its items by a priority value The first item removed is the one having the highest priority value The ADT priority queue Orders its items by a priority value The first item removed is the one having the highest priority value 1 Possible implementations Sorted linear implementations o Appropriate if

More information

Extended Introduction to Computer Science CS1001.py Lecture 7: Basic Algorithms: Sorting, Merge; Time Complexity and the O( ) notation

Extended Introduction to Computer Science CS1001.py Lecture 7: Basic Algorithms: Sorting, Merge; Time Complexity and the O( ) notation Extended Introduction to Computer Science CS1001.py Lecture 7: Basic Algorithms: Sorting, Merge; Time Complexity and the O( ) notation Instructors: Daniel Deutch, Amir Rubinstein Teaching Assistants: Michal

More information

CS1 Lecture 22 Mar. 6, 2019

CS1 Lecture 22 Mar. 6, 2019 CS1 Lecture 22 Mar. 6, 2019 HW 5 due Friday Questions? In discussion exams next week Last time Ch 12. Zip, lambda, etc Default/keyword function parameters Ch 19 conditional expresssions, list comprehensions

More information

Sequence Types FEB

Sequence Types FEB Sequence Types FEB 23-25 2015 What we have not learned so far How to store, organize, and access large amounts of data? Examples: Read a sequence of million numbers and output these in sorted order. Read

More information

Quiz 1 Practice Problems

Quiz 1 Practice Problems Introduction to Algorithms: 6.006 Massachusetts Institute of Technology March 7, 2008 Professors Srini Devadas and Erik Demaine Handout 6 1 Asymptotic Notation Quiz 1 Practice Problems Decide whether these

More information

Revision Statement while return growth rate asymptotic notation complexity Compare algorithms Linear search Binary search Preconditions: sorted,

Revision Statement while return growth rate asymptotic notation complexity Compare algorithms Linear search Binary search Preconditions: sorted, [1] Big-O Analysis AVERAGE(n) 1. sum 0 2. i 0. while i < n 4. number input_number(). sum sum + number 6. i i + 1 7. mean sum / n 8. return mean Revision Statement no. of times executed 1 1 2 1 n+1 4 n

More information

cs1114 REVIEW of details test closed laptop period

cs1114 REVIEW of details test closed laptop period python details DOES NOT COVER FUNCTIONS!!! This is a sample of some of the things that you are responsible for do not believe that if you know only the things on this test that they will get an A on any

More information

Scheme Quick Reference

Scheme Quick Reference Scheme Quick Reference COSC 18 Winter 2003 February 10, 2003 1 Introduction This document is a quick reference guide to common features of the Scheme language. It is by no means intended to be a complete

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

Types of recursion. Readings: none. In this module: a glimpse of non-structural recursion. CS 135 Winter : Types of recursion 1

Types of recursion. Readings: none. In this module: a glimpse of non-structural recursion. CS 135 Winter : Types of recursion 1 Types of recursion Readings: none. In this module: a glimpse of non-structural recursion CS 135 Winter 2018 07: Types of recursion 1 Structural vs. general recursion All of the recursion we have done to

More information

22C:16 CS:1210 Exam 2

22C:16 CS:1210 Exam 2 22C:16 CS:1210 Exam 2 April 4th, 6:30 pm to 8:30 pm Instructions: This is an open notes exam and you have 2 hours to complete it. There are 4 problems in the exam and these appear on 6 pages. The exam

More information

Fall 2018 Discussion 8: October 24, 2018 Solutions. 1 Introduction. 2 Primitives

Fall 2018 Discussion 8: October 24, 2018 Solutions. 1 Introduction. 2 Primitives CS 6A Scheme Fall 208 Discussion 8: October 24, 208 Solutions Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write

More information