A description of the "Conway's Rational Tangles" activity can be found by following the link at the bottom of this page.¶
This is a solver program for CRT which uses the python "Fraction" class.
In [1]:
from fractions import Fraction # bring in the Fraction class
Tangle='SSRSSR' # instructions for creating a tangle stored as a string. S=Swap, R=Rotate
Score = Fraction(0,1) # initial score is zero, or zero-over-one as a Fraction
print 'Tangle'
for i in Tangle:
if i=='S': # Swap
Score = Score + 1 # add one to Score
print i, str(Score) # NOTE: Stringifying the Fraction makes it prettier!
else: # if instruction was not Swap, assume Rotate
Score = -1*Fraction(1,Score) # negative reciprocal of Score
print i, str(Score) # NOTE: Stringifying the Fraction makes it prettier!
print '\nUntangle' # NOTE: \n is a carriage return
Untangle = '' # This string will hold our untangle instructions.
for x in range(10): # This loop will limit the number of untangle operations to 10
if Score == 0: continue # Untangle Complete! Bail out of x loop
if Score < 0: # Score < 0, do a Swap and add 1 to Score
Untangle = Untangle+'S'
Score = Score + 1
print 'S', str(Score)
else: # Score > 0, do a Rotate and take the negative reciprocal of Score
Untangle = Untangle+'R'
Score = -1*Fraction(1,Score)
print 'R',str(Score)
print '\nSummary' # NOTE: \n is a carriage return
print 'Tangle Instructions: ', Tangle
print 'Untangle Instructions: ', Untangle