Strategies for debugging
-Print out intermediate information
-Commenting code liberally
-Name variables descriptively
-Test early - try to break
-Modularity - separate program into functions that do specific things, and can be tested separately
-First solve an easier case
-Explaining code to someone else
-"Rubber ducky" debugging
# CHALLENGE: compute gcd(49,28) on paper using Euclidean algorithm
# CHALLENGE: write my_gcd function
def my_gcd(a,b):
"Returns gcd(a,b), where a,b are non-negative integers."
if a<b:
a,b = b,a # swap a,b if a<b
# Now we can assume that a>=b (since made swap above otherwise)
if b==0:
return a
return my_gcd(a%b, b)
my_gcd(24,39)
my_gcd(49,28)
my_gcd(18,1)
%%time
my_gcd(2^800+3^812,2^865 -3^500)
%%time
# built-in gcd function is a bit better (doesn't run in to "maximum recursion depth" issue)
gcd(2^1273128-1, 3^1281273-1)
# upshot: Euclidean algorithm is very fast, even for big numbers
# compare to factorization method, using builtin factor() function
# can compute gcd by computing both factorizations
factor(24),factor(39)
%%time
factor(2^137-1)
# below takes too long
factor(2^547-1)
# factorization algorithm is much slower than Euclidean algorithm