Strategies for debugging:
-Print out intermediate information (eg print statements)
-Commenting your code
-Naming variables descriptively
-Testing early - try to break things
-Modularity - breaking up code into pieces that can be tested separately (eg make lots of different functions) -First solve an easier case
-Explain your code to someone else
-"Rubber ducky" debugging
# CHALLENGE: find gcd(24,36) using Euclidean algorithm, by hand on paper
# CHALLENGE: write my_gcd (Hint: use recursion)
def my_gcd(a,b):
"""Return gcd(a,b), computed using Euclidean algorithm.
a,b non-negative integers"""
if a<b:
a,b = b,a # swaps a,b if a<b
# Now we can assume that a>=b
if b==0:
return a
return my_gcd(a%b,b) # recursive call
my_gcd(39,24)
my_gcd(24,36)
my_gcd(24,0)
my_gcd(24,1)
my_gcd(21391201292181, 12323123123928)
my_gcd(2^123, 2^135)
my_gcd(2^123, 2^135 - 1)
%%time
my_gcd(10^12349999, 10^12329999- 3^45)
# upshot: my_gcd is very fast
# we will now compare to factoring (which gives another way of finding gcd)
# bultin factor function. Can find gcd(24,36) using prime factorization, as below
factor(24), factor(36)
%%time
factor(2^123), factor(2^135 - 1)
factor(2^235)
%%time
factor(2^335-1)
# amount of time factor(n) takes is very roughly around n
# amount of time gcd(n,m) is around the number of digits of n or m