INTRO2CS Tirgul 6. Understanding the Traceback # in file t.py: def a(L): return b(L) def b(L): return L.len() #should have been len(L) # in the python.

Slides:



Advertisements
Similar presentations
More Recursion: Permutations and Towers of Hanoi COP 3502.
Advertisements

Recursion Genome 559: Introduction to Statistical and Computational Genomics Elhanan Borenstein.
Analyzing Algorithms and Problems Prof. Sin-Min Lee Department of Computer Science.
Introduction to Computing Science and Programming I
P Chapter 6 introduces the stack data type. p Several example applications of stacks are given in that chapter. p This presentation shows another use called.
Factorial Recursion stack Binary Search Towers of Hanoi
Backtracking COP Backtracking  Backtracking is a technique used to solve problems with a large search space, by systematically trying and eliminating.
More on Recursive Recursion vs. Iteration Why Recursion?
Chapter 10 Recursion. Copyright © 2005 Pearson Addison-Wesley. All rights reserved Chapter Objectives Explain the underlying concepts of recursion.
CS 106 Introduction to Computer Science I 03 / 28 / 2008 Instructor: Michael Eckmann.
Recursion Chapter 7. Chapter 7: Recursion2 Chapter Objectives To understand how to think recursively To learn how to trace a recursive method To learn.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 16: Recursion.
Recursion Chapter 7. Chapter 7: Recursion2 Chapter Objectives To understand how to think recursively To learn how to trace a recursive method To learn.
CHAPTER 10 Recursion. 2 Recursive Thinking Recursion is a programming technique in which a method can call itself to solve a problem A recursive definition.
analysis, plug ‘n’ chug, & induction
Introduction to Programming (in C++) Recursion Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept. of Computer Science, UPC.
Copyright © Cengage Learning. All rights reserved.
Data Structures Using C++ 2E Chapter 6 Recursion.
Analysis of Algorithm Lecture 3 Recurrence, control structure and few examples (Part 1) Huma Ayub (Assistant Professor) Department of Software Engineering.
Data Structures Using C++ 2E Chapter 6 Recursion.
Recursion Chapter 5.
Recursion Chapter 7. Chapter Objectives  To understand how to think recursively  To learn how to trace a recursive method  To learn how to write recursive.
1 CS 132 Spring 2008 Chapter 6 Recursion Read p Skip example 6-3 (Fibonacci), 6-4 (Hanoi) Read example 6-5 (p. 387)
Chapter 15: Advanced Topics: Introducing Data Structures and Recursion Visual Basic.NET Programming: From Problem Analysis to Program Design.
CIS 068 Welcome to CIS 068 ! Stacks and Recursion.
Recursion Textbook chapter Recursive Function Call a recursive call is a function call in which the called function is the same as the one making.
Recursion Jordi Cortadella Department of Computer Science.
1 7.Algorithm Efficiency What to measure? Space utilization: amount of memory required  Time efficiency: amount of time required to process the data Depends.
# 1# 1 VBA Recursion What is the “base case”? What is the programming stack? CS 105 Spring 2010.
Chapter 4 Recursion. Copyright © 2004 Pearson Addison-Wesley. All rights reserved.1-2 Chapter Objectives Explain the underlying concepts of recursion.
Back Tracking Project Due August 11, 1999 N-queens: –A classic puzzle for chess buffs is the N- Queens problem. Simply stated: is it possible to place.
Fall Week 4 CSCI-141 Scott C. Johnson.  Computers can process text as well as numbers ◦ Example: a news agency might want to find all the articles.
1 7.Algorithm Efficiency What to measure? Space utilization: amount of memory required  Time efficiency: amount of time required to process the data.
Recursion Recursion Chapter 12. Outline n What is recursion n Recursive algorithms with simple variables n Recursion and the run-time stack n Recursion.
Data Structures Using C++ 2E1 Recursion and Backtracking: DFS Depth first search (a way to traverse a tree or graph) Backtracking can be regarded as a.
Data Structures R e c u r s i o n. Recursive Thinking Recursion is a problem-solving approach that can be used to generate simple solutions to certain.
Upon completion, the world will end…
Recursion A function that calls itself. Recursion A function which calls itself is said to be recursive. Recursion is a technique which will allow us.
1 Recursion Recursion is a powerful programming technique that provides elegant solutions to certain problems. Chapter 11 focuses on explaining the underlying.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 12 Recursion.
CSE 143 Lecture 13 Recursive Backtracking slides created by Ethan Apter
1 Programming for Engineers in Python Autumn Lecture 8: Recursion.
CS 116 Object Oriented Programming II Lecture 13 Acknowledgement: Contains materials provided by George Koutsogiannakis and Matt Bauer.
Recursion by Ender Ozcan. Recursion in computing Recursion in computer programming defines a function in terms of itself. Recursion in computer programming.
Section Recursion  Recursion – defining an object (or function, algorithm, etc.) in terms of itself.  Recursion can be used to define sequences.
1 7.Algorithm Efficiency These factors vary from one machine/compiler (platform) to another  Count the number of times instructions are executed So, measure.
1 CSC 143 Recursion [Reading: Chapter 17]. 2 Recursion  A recursive definition is one which is defined in terms of itself.  Example:  Sum of the first.
Lecture 11 Recursion. A recursive function is a function that calls itself either directly, or indirectly through another function; it is an alternative.
1 Tirgul 11: Recursion & Backtracking. 2 Elements of a recursive solution (Reminder) A base case that is so simple we need no computation to solve it.
Recursion You may have seen mathematical functions defined using recursion Factorial(x) = 1 if x
Recursion.
Recursion Data Structure Submitted By:- Dheeraj Kataria.
Chapter Topics Chapter 16 discusses the following main topics:
Chapter 15 Recursion.
Tirgul 7 Recursion.
Chapter 15 Recursion.
CSCI 104 Backtracking Search
Recursion in Java December 12, 2005
Recursive Thinking Chapter 9 introduces the technique of recursive programming. As you have seen, recursive programming involves spotting smaller occurrences.
Java Software Structures: John Lewis & Joseph Chase
Mathematical Induction Recursion
Recursive Thinking Chapter 9 introduces the technique of recursive programming. As you have seen, recursive programming involves spotting smaller occurrences.
Jordi Cortadella Department of Computer Science
Recursion Copyright (c) Pearson All rights reserved.
Chapter 12 Recursion (methods calling themselves)
ECE 103 Engineering Programming
CSC 143 Recursion.
Dr. Sampath Jayarathna Cal Poly Pomona
Chapter 3 :Recursion © 2011 Pearson Addison-Wesley. All rights reserved.
Presentation transcript:

INTRO2CS Tirgul 6

Understanding the Traceback # in file t.py: def a(L): return b(L) def b(L): return L.len() #should have been len(L) # in the python shell we try a(L) Traceback (most recent call last): File " ", line 1, in a(L) NameError: name 'L' is not defined

Understanding the Traceback # in file t.py: def a(L): return b(L) def b(L): return L.len() #should have been len(L) # in the python shell we try a([1,2,3]) Traceback (most recent call last): File " ", line 1, in a(L) File ”…/t.py", line 2, in a return b(L) File ”…/t.py", line 6, in b return L.len() AttributeError: 'list' object has no attribute 'len'

Understanding the Traceback # in file t.py: def c(L): print((L[0]) print(“bye”) # in the python shell we try a([]) Traceback (most recent call last): File " ", line 1, in c([]) File “…\t.py", line 10, in c print(L[0]) IndexError: list index out of range

Understanding the Traceback # in file t.py: def c(L): print((L(0)) print(“bye”) # in the python shell we try c([1,2,3]) Traceback (most recent call last): File " ", line 1, in c([1,2,3]) File “…\t.py", line 9, in c print(L(0)) TypeError: 'list' object is not callable

Understanding the Traceback # in file t.py: def c(L): print((L[0]) print(“bye”) invalid syntax (but the next line is marked) or unexpected EOF while parsing if this is the last line in the

Tips  Pay attention to indentation (and other idle formatting issues) – it might imply on bugs  Make sure you are in the right range when working with containers  Adding printouts might be helpful  You can use Google with the error name (e.g. TypeError: 'list' object is not callable)

8 What is recursion?  Similar to mathematical induction  A recursive definition is self-referential  A larger, more complex instance of a problem is defined in terms of a smaller, simpler instance of the same problem  A base case must be defined explicitly

9 When do we use recursion?  We are given a large problem (say of size n)  We notice that:  There is some simple base case we know how to solve directly (say n=0)  The solution to the large problem is composed of solutions to smaller problems of the same type  If we could solve a smaller instance of the problem (say n-1), we could use that solution to solve the large problem

10 How do we use recursion?  A function may call itself  Such a function is called recursive  There must be some base case that is handled explicitly, without a recursive call  The other case has to make sure there is progress towards the base case.  The recursive function call will use simpler/smaller arguments

11 Recursive factorial  n! = 1·2·3·…·n  By definition, 0! = 1 (base case)  Recursive definition: n! = (n-1)! · n  For example: 4! = 3! · 4 = (2! · 3) · 4 = ((1! · 2) · 3) · 4 = (((0! · 1) · 2) · 3) · 4 = (((1 · 1) · 2) · 3) · 4 = 24

12 Recursive factorial def factorial(n): if n == 0: return 1 else: return n*factorial(n-1) Base case recursive call

13 What’s happening here? i = factorial(4); factorial(3) factorial(1) factorial(0) 1 2·1=2 1·1=1 3·2=6 factorial(2) 4·6=24 def factorial(n): if n == 0: return 1 else: return n*factorial(n-1)

14 Iterative factorial def iterative_factorial(n): res == 1: for i in range(1,n+1): res *= i return res

15 Recursion vs. loops  We could have calculated factorial using a loop  In general, loops are more efficient than recursion  However, sometimes recursive solutions are much simpler than iterative ones  Recursion can be a powerful tool for solving certain types of problems  Lets see a classic example

16 Recursive power  Given an integer x and a non-negative integer n, we want to compute x n  What’s the recursive formula?  What’s the base case?  What do you think?

17 Recursive power #1 Def power(x, n): if n == 0: return 1 else: return x*power(x,n-1) Base case recursive call 2 3 = 2 · 2 2 = 2 · 2 · 2 1 = 2 · 2 · 2 · 2 0 = 2 · 2 · 2 · 1 = 8

18 Recursive power rethought  Recall that x a+b = x a · x b  We can decompose the power n: n = 2(n / 2) + (n % 2)  So we can “divide and conquer”: x n = x 2(n/2)+(n%2) = x n/2 · x n/2 · x n%2

19 Recursive power #2 def power(x, n): if n == 0: return 1 if n == 1: return x tmp = power(x, n//2) return tmp * tmp * power(x, n%2) 2 5 = 2 2 ·2 2 ·2 1 = (2 1 ·2 1 ·2 0 ) 2 ·2 1 = (2·2·1) 2 ·2 = 32 Why do we need two base cases? Why do we use a temporary variable to store x n/2 ?

20 Recursive power #2 complexity

Tower of Hanoi  Given:  Mission: move all the disks from pole A to pole B using rod C, following these rules:  In each step you can move only one disk  Disks could be only on larger ones

Tower of Hanoi  The puzzle was first publicized in the West by the French mathematician Édouard Lucas in 1883.Édouard Lucas  There is a story about an Indian temple in Kashi Vishwanath which contains a large room with three time-worn posts in it surrounded by 64 golden disks. IndianKashi Vishwanath  Brahmin priests, acting out the command of an ancient prophecy, have been moving these disks, in accordance with the immutable rules of the Brahma, since the creation of the world. Brahmin  According to the legend, when the last move of the puzzle will be completed, the world will end.

Tower of Hanoi  According to the legend, when the last move of the puzzle will be completed, the world will end.

Tower of Hanoi – only two disks  Move yellow from A to C  Move green from A to B  Move yellow from C to B

Tower of Hanoi – now three disks  We know how to move two disks so:

Tower of Hanoi – now three disks  We know how to move two disks so:  Move red and yellow to C using B

Tower of Hanoi – now three disks  We know how to move two disks so:  Move red and yellow to C using B  Move green to B

Tower of Hanoi – now three disks  We know how to move two disks so:  Move red and yellow to C using B  Move green to B  Move red and yellow to B using A

Tower of Hanoi – recursive solution for general n  Lets assume we know how to move n-1 disks from source pole to target pole using some third pole  Move disks 1, 2, …, n-1 from pole A to pole C using pole B  Move disk n from pole A to pole B  Move disks 1, 2, …, n-1 from pole C to pole B using pole A

Hanoi – python code def hanoi(n, source, target, using): hanoi(n-1, source, using, target) print(“move disk %d from %s to %s” % (n, source, target)) hanoi(n-1, using, target, source)

Hanoi – python code def hanoi(n, source, target, using): hanoi(n-1, source, using, target) print(“move disk %d from %s to %s” % (n, source, target)) hanoi(n-1, using, target, source) Didn’t we forget something?

Tower of Hanoi – recursive solution for general n  Lets assume we know how to move n-1 disks from source pole to target pole using some third pole  Move disks 1, 2, …, n-1 from pole A to pole C using pole B  Move disk n from pole A to pole B  Move disks 1, 2, …, n-1 from pole C to pole B using pole A  Base case: if we need to move only one disk just move it from source to target

Hanoi – python code def hanoi(n, source, target, using): if n == 1: print(“move disk 1 from %s to %s” % (source, target)) return hanoi(n-1, source, using, target) print(“move disk %d from %s to %s” % (n, source, target)) hanoi(n-1, using, target, source)

Hanoi – python code w/o code repetition (but with extra calls) def hanoi(n, source, target, using): if n == 0: return hanoi(n-1, source, using, target) print(“move disk %d from %s to %s” % (n, source, target)) hanoi(n-1, using, target, source)

hanoi(3,”A”,”B”,”C”)

When will the world come to an end?  According to the legend, when the last move of the puzzle will be completed, the world will end.  The number of disc moves required is about 2 n (where n is the number of disks)  If we assume each move takes a second we will get 2 64 seconds = 550 billion year….

37 Exploring all states using recursion Backtracking  We can use recursion to go over many options, and do something for each case.  Example:  printing all subsets of the set S = {0, …,n-1} (printing the power set of S).  Difficult to do with loops (but possible).  Much simpler with recursion.

Power Set - The basic idea  Lets decompose the problem to two smaller problems of the same type.  The recursive decomposition:  Print all subsets that contain an item,  Then print all the subsets that do not contain it.  Keep track of our current “state”.  items that are in the current subset,  items not in the current subset,  items we did not decide about yet. 38

39 Power Set – python code def power_set(n): cur_set = [False]*n power_set_helper(cur_set, 0) Holds the subset we are currently building. This is not the recursive function. It calls the recursive function that does the real work. The recursive function

40 Power Set – python code def power_set_helper(cur_set, index): # base:we picked out all the items in the set if index==len(cur_set): print_power_set(cur_set) return #runs on all sets that include this index cur_set[index] = True power_set_helper(cur_set, index+1) #runs on all sets that does not include index cur_set[index] = False power_set_helper(cur_set, index+1)

41 Power Set – python code def print_power_set(cur_set): print('{', end=' ') for (idx, in_cur_set) in enumerate(cur_set): if in_cur_set: print(idx, end=' ') print('}')

42 power_set and the stack ??? ??t ?tt?ft tttftttftfft index=0 index=1 index=2 {0,1,2} {0,1} {0,2}{0}

43 power_set and the stack ??? ??f??t ?tt?ft tttftttftfft ?tf?ff ttfftftfffff {0,1,2} {0,1} {0,2}{0} {1,2}{1} {2} {}

Exploring all states using backtracking  A backtracking alg. can be used to find a solution (or all solutions) to a combinatorial problem.  Solutions are constructed incrementally  If there are several options to advance incrementally, the algorithm will try one option, then backtrack and try more options.  If you reach a state where you know the path will not lead you to the solution, backtrack! 44

45 N-Queens  The problem:  On an NxN chess board, place N queens so that no queen threatens the other (no other queen allowed in same row,col or diagonal).  Print only one such board.  Simplifying step:  Place 1 queen somewhere in an available column then solve the problem of placing all other queens.  Base case:  All queens have been placed.

The N-Queen Problem #This function uses a recursive helper method that really does the work def place_queens(board_size): board = [] for i in range (board_size): board.append([]) for j in range (board_size): board[i].append(False) if place_queen_at_col(board, 0): print_board(board) else: print("No Placement Found!") # what would happen if we were trying to do it using: # board = [[False]*board_size] *board_size # what would happen if we were trying to do it using: # board = [[False]*board_size] *board_size

The N-Queen Problem def place_queen_at_col(board, col): #Base case: we have passed the last column if col == len(board[0]): return True #Iterate over rows until it is okay to place a queen for row in range(len(board)): if illegal_placement(board, row, col): continue #place the queen board[row][col] = True #Check if we can fill up the remaining columns if place_queen_at_col(board, col+1): return True #If not, remove the queen and keep iterating board[row][col] = False #If no placement works, give up return False

The N-Queen Problem def illegal_placement(board, row, col): #Note: it is enough to look for threatening queens in lower columns for delta in range(1,col+1): #Check for queen in the same row or in upper diagonal or in lower diagonal if (board[row][col-delta] or (row-delta>=0 and board[row-delta][col-delta]) or (row+delta<len(board) and board[row+delta][col- delta])): return True return False def print_board(board): for row in board: for q in row: print('Q',end=' ') if q else print('-',end=' ') print()

49 Output of N-Queens Q Q Q Q - Q Q Q Q