Recitation 8 Programming for Engineers in Python.

Slides:



Advertisements
Similar presentations
Recursion Michael Ernst UW CSE 140 To seal: moisten flap, fold over, and seal.
Advertisements

Dr. Sharon Persinger October 30,  Recursion is a type of repetition used in mathematics and computing to create objects and to define functions.
CS1010 Programming Methodology
Recursion Michael Ernst CSE 190p University of Washington To seal: moisten flap, fold over, and seal.
D IVIDE AND CONQUER STRATEGY, D ATA TYPE, A LGORITHM DESIGN AND PRACTICE. Week 13 Mr.Mohammed Rahmath.
Lesson 19 Recursion CS1 -- John Cole1. Recursion 1. (n) The act of cursing again. 2. see recursion 3. The concept of functions which can call themselves.
Recursion. Idea: Some problems can be broken down into smaller versions of the same problem Example: n! 1*2*3*…*(n-1)*n n*factorial of (n-1)
מבוא מורחב למדעי המחשב בשפת Scheme תרגול 2. 2 Outline Scoping and block structure Recursive and iterative processes Orders of growth.
CSC2110 Discrete Mathematics Tutorial 5 GCD and Modular Arithmetic
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Sixth Edition Chapter 14: Recursion by.
6/20/2015 5:05 AMNumerical Algorithms1 x x1x
Algorithms. Problems, Algorithms, Programs Problem - a well defined task. –Sort a list of numbers. –Find a particular item in a list. –Find a winning.
CSC 2300 Data Structures & Algorithms January 30, 2007 Chapter 2. Algorithm Analysis.
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 14 Recursion.
Section Section Summary Recursive Algorithms Proving Recursive Algorithms Correct Recursion and Iteration (not yet included in overheads) Merge.
Mathematics of Cryptography Part I: Modular Arithmetic, Congruence,
Great Theoretical Ideas in Computer Science for Some.
Quiz 2 key.
Data Structures Using C++ 2E Chapter 6 Recursion.
Programming Training Main Points: - Working with Functions in Python
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 19: Recursion.
Algorithms Friday 7th Week. Algorithms What is an Algorithm? –A series of precise steps, known to stop eventually, to solve a problem –NOT necessarily.
Module :MA3036NI Cryptography and Number Theory Lecture Week 7
Data Structures Using C++ 2E Chapter 6 Recursion.
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Eighth Edition by Tony Gaddis,
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 19 Recursion.
Chapter 14: Recursion Starting Out with C++ Early Objects
Chapter 3 (Part 3): Mathematical Reasoning, Induction & Recursion  Recursive Algorithms (3.5)  Program Correctness (3.6)
© by Kenneth H. Rosen, Discrete Mathematics & its Applications, Sixth Edition, Mc Graw-Hill, 2007 Chapter 4 (Part 3): Mathematical Reasoning, Induction.
Programming Principles II Lecture Notes 5 Recursion Andreas Savva.
Recursive. 2 Recursive Definitions In a recursive definition, an object is defined in terms of itself. We can recursively define sequences, functions.
Programming for Engineers in Python Sawa 2015 Lecture 2: Lists and Loops 1.
Review Introduction to Searching External and Internal Searching Types of Searching Linear or sequential search Binary Search Algorithms for Linear Search.
Examples of Recursion Data Structures in Java with JUnit ©Rick Mercer.
Edited by Malak Abdullah Jordan University of Science and Technology Data Structures Using C++ 2E Chapter 6 Recursion.
1 Section 2.1 Functions: Definitions and Examples A function ƒ from A to B associates each element of A with exactly one element of B. Write ƒ : A  B.
CSE 311: Foundations of Computing Fall 2014 Lecture 12: Primes, GCD.
MA/CSSE 473 Day 06 Euclid's Algorithm. MA/CSSE 473 Day 06 Student Questions Odd Pie Fight Euclid's algorithm (if there is time) extended Euclid's algorithm.
Math 409/409G History of Mathematics Books VII – IX of the Elements Part 1: Divisibility.
COMPSCI 102 Introduction to Discrete Mathematics.
MA/CSSE 473 Day 08 Extended Euclid's Algorithm Modular Division Fermat's little theorem.
1 Introduction  Algorithms  Data structures  Abstract data types  Programming with lists and sets © 2008 David A Watt, University of Glasgow Algorithms.
Application: Algorithms Lecture 20 Section 3.8 Wed, Feb 21, 2007.
Programming With Java ICS201 University Of Ha’il1 Chapter 11 Recursion.
Chapter 2: Algorithm Analysis Application of Big-Oh to program analysis Logarithms in Running Time Lydia Sinapova, Simpson College Mark Allen Weiss: Data.
Application: Algorithms Lecture 19 Section 3.8 Tue, Feb 20, 2007.
Maitrayee Mukerji. Factorial For any positive integer n, its factorial is n! is: n! = 1 * 2 * 3 * 4* ….* (n-1) * n 0! = 1 1 ! = 1 2! = 1 * 2 = 2 5! =
Program Development and Design Using C++, Third Edition
Section Recursion  Recursion – defining an object (or function, algorithm, etc.) in terms of itself.  Recursion can be used to define sequences.
ITI 1120 Lab #8 Contributors: Diana Inkpen, Daniel Amyot, Sylvia Boyd, Amy Felty, Romelia Plesa, Alan Williams.
Recursive Algorithms Section 5.4.
Chapter 19: Recursion.
Chapter 4 (Part 3): Mathematical Reasoning, Induction & Recursion
Topic 6 Recursion.
Recall: d is a divisor of n  n % d == 0
Great Theoretical Ideas in Computer Science
Chapter 14: Recursion Starting Out with C++ Early Objects
Numerical Algorithms x x-1
Chapter 14: Recursion Starting Out with C++ Early Objects
Chapter 14: Recursion Starting Out with C++ Early Objects
Recursion UW CSE 160 Winter 2017
Recursion Spring 2015 UW CSE 160
Recursion UW CSE 160 Spring 2018
Recursion Winter 2014 UW CSE 140
Recursion UW CSE 160 Winter 2016
Application: Algorithms
Application: Algorithms
Recursion.
Lecture 6 - Recursion.
Presentation transcript:

Recitation 8 Programming for Engineers in Python

Plan Recursion Sum of Digits Choose k elements from n Permutations GCD Fast Power Reverse Digits 2

Sum of Digits 3 Write a program that receives an integer and returns its sum of digits. We do not know the number of digits in advance. Example: >>> sum_of_digits(369) 18 Before we begin, let us recall the recursion “rules”

The Three Rules of Recursion 4 1.Base (termination) condition 2.Decomposition to smaller instances 3.Use solutions to smaller instances to solve the original problem

def sum_of_digits(num): print num # for tracking if num == 0: return 0 return sum_of_digits(num/10)+num%10 >>> sum_of_digits(12046) Sum of Digits 5

6 >>> sum_of_digits(12045) >>> sum_of_digits(9001) 10 >>> sum_of_digits(999)

What Does this Program Do? 7 def secret(): var = input('Enter a value:') if var == 0: return else: secret() print var

Secret Output 8 >>> secret() Enter a value:1 Enter a value:'mellon' Enter a value:2 Enter a value:'bananas' Enter a value:0 bananas 2 mellon 1

def secret(): var = input('Enter a value:') if var == 0: return else: secret() print var What Does this Program Do? 9 secret var = 1

What Does this Program Do? 10 def secret(): var = input('Enter a value:') if var == 0: return else: secret() print var secret var = 1 secret var =‘mellon’ secret var = 2 secret var = ‘bananas

What Does this Program Do? 11 def secret(): var = input('Enter a value:') if var == 0: return else: secret() print var secret var = 1 secret var =‘mellon’ secret var = 2 secret var = ‘bananas

12 What Does this Program Do? def secret(): var = input('Enter a value:') if var == 0: return else: secret() print var secret var = 1 secret var =‘mellon’ secret var = 2 secret var = ‘bananas

Reverse Print 13 def secret(): var = input('Enter a value:') if var == 0: return else: secret() print var

Choose k elements from n 14 Think recursion: If the n th element is selected – there are k-1 elements to choose from {1, …, n-1}. If the n th element is not selected – there are k elements to choose from {1, …, n-1}.

Choose k from n 15 Recursive formula: Termination Criteria: k > n  0 k = 0  1 k == n  1

Choose k from n–Formula to Code 16 def choose(n, k): if k==0 or n==k: return 1 if n < k: return 0 return choose(n-1, k-1) + choose(n-1, k)

Choose – Recursion Tree 17 >>> choose(4, 2) n = 4 k = 2 n = 3 k = 1 n = 3 k = 2 n = 2 k = 0 n = 2 k = 1 n = 2 k = 1 n = 2 k = 2 n = 1 k = 0 n = 1 k = 1 n = 1 k = 0 n = 1 k = 1

Permutations 18 Permutation – arranging objects in a particular order. For example, the set {1, 2, 3} has six permutations: (1,2,3), (1,3,2), (2,1,3), (2,3,1), (3,1,2), (3,2,1).  How many permutations exists for a set with n elements?

Permutations 19  How can we create all permutations of n elements?  Wishful thinking! - Set the last element, - Create all sub-permutations - Append last element - Repeat for all elements in the list Returns all permutations of n-1 elements

Permutations - Code 20 def permute(lst): if len(lst) == 0: # ternimation condition return [[]] # in each iteration, one element is chosen as the last element sets = [] for elem in lst: sub_lst = lst[:] # duplicate, then create sublist sub_lst.remove(elem) sub_perms = permute(sub_lst) # create all sub-perms # add last element for sub in sub_perms: sub.append(elem) sets.extend(sub_perms) # unite all permutations return sets

GCD – Greatest Common Divisor 21 Definition: For two or more non-zero integers, The GCD is the largest positive integer that divides both numbers without a remainder. Examples: GCD(12, 4) = 4 GCD(32, 14) = 2 GCD(12, 5) = 1

GCD – Euclid’s Algorithm 22 What is GCD(616, 143) ? 616 % 143 = 44  GCD(143, 44) 143 % 44 = 11  GCD(44, 11) 44 % 11 = 0  11

GCD – Euclid’s Algorithm 23  Stopping Criteria? The second number is 0  Smaller instances? Solve GCD(b, a%b)  Solve original solution with these instances In this case – unnecessary

GCD – Code for Euclid’s Algorithm 24 def gcd(a, b): if (b == 0): return a return gcd(b, a%b) >>> gcd(12, 8) 4 >>> gcd(161, 143) 1 >>> gcd(616, 143) 11 >>> gcd(616, 0) 616 >>> gcd(0, 616) 616

Fast Power Calculation 25 x y = x*x*…*x Recursive definitions (assume non-negative y): 1,y = 0 x y = x*x y-1,y odd (x y/2 ) 2,y even y times

Fast Power - Code 26 def rec_power(x, y): print "rec_power("+str(x)+","+str(y)+")"+' ** ', if y == 0: return 1 if y%2 != 0: # odd power return x * rec_power(x, y - 1) else:# even power tmp = rec_power(x, y/2) return tmp*tmp  Note: In every call for rec_power there is only one multiplication!

Fast Power - Run 27 rec_power(2, 5) x = 2, y = 5 return 2 *rec_power x = 2, y = 4 return rec_power ^2 x = 2, y = 2 return rec_power ^2 x = 2, y = 1 return 2* rec_power x = 2, y = 0 return 1 >>>rec_power(2, 5)

>>> rec_power(2, 17) rec_power(2,17) --> rec_power(2,16) --> rec_power(2,8) --> rec_power(2,4) --> rec_power(2,2) --> rec_power(2,1) --> rec_power(2,0) -->  7 multiplications instead of 17 >>> rec_power(0.5, 30) rec_power(0.5,30) --> rec_power(0.5,15) --> rec_power(0.5,14) --> rec_power(0.5,7) --> rec_power(0.5,6) --> rec_power(0.5,3) --> rec_power(0.5,2) --> rec_power(0.5,1) --> rec_power(0.5,0) --> e-10  9 multiplications instead of 30  How fast is fast calculation? What is the relation between the power and the number of multiplications? Fast Power - Usage 28

Reverse digits 29 Receive an Integer number, reverse the order of its digits. >>> reverse_digits(573824) How can we solve it recursively? Wishful Thinking: If I only knew reverse_digits(73824) or reverse_digits(57382)…

Reverse digits 30 Problem – for d digits, the last digit is multiplied by 10 d. But I don’t know d in advance! Solution – Call a helper function that diffuses the temporal result throughout the recursion. Termination criterion?

Reverse Digits - Code 31 def reverse_help(n, res): if (n == 0): return res; return reverse_help(n/10, 10*res + n%10); def reverse_digits(n): return reverse_help(n, 0)