Professional Documents
Culture Documents
Lecture 28
Lecture 28
Lecture 28
Lecture Outline
• Recursion
– CS1001 Lecture 28 –
Example: Euclid’s algorithm
def gcd(n1,n2):
r=1;
while r!=0:
q=n1//n2
r=n1%n2
n1=n2
n2=r
return n1
def gcd(n1,n2):
if n1 % n2 == 0:
return n2
else:
return gcd(n2,n1%n2)
– CS1001 Lecture 28 – 1
Example: Tower of Hanoi
– CS1001 Lecture 28 – 2
Example: Tower of Hanoi
– CS1001 Lecture 28 – 3
Example: Tower of Hanoi
def main():
n = eval(input("Enter number of disks: "))
print("The moves are:")
hanoi(n,’A’,’B’,’C’)
main()
– CS1001 Lecture 28 – 4
Recursive helper functions
– CS1001 Lecture 28 – 5
Example: Square root
def main() :
print("sqrt(2) is", squareRoot(2))
main()
Output:
sqrt(2) is 1.414213562373095
– CS1001 Lecture 28 – 6