+/foobar
google programming puzzles
git clone https://git.julia.blue/+/foobar
2e1d345
master
1from fractions import Fraction 2 3 4def peg2rad (first ,pegs ): 5rad = [Fraction (first ,1 )] 6for j in range (1 ,len (pegs )): 7rad .append (pegs [j ]- pegs [j - 1 ]- rad [- 1 ]) 8return rad 9 10 11def rad2ratio (rad ): 12ratios = [rad [i ]/ rad [i + 1 ]for i in range (0 ,len (rad )- 1 )] 13return reduce (lambda x ,y :x * y ,ratios ) 14 15 16def answer (pegs ): 17rad = peg2rad (1 ,pegs ) 18smallest = min (rad [::2 ]) 19if smallest <= 0 : 20smallest = 2 - smallest 21else : 22smallest = 1 23small_rad = peg2rad (smallest ,pegs ) 24largest = smallest + min (small_rad [1 ::2 ])- 1 25if largest < smallest : 26return [- 1 ,- 1 ] 27small_ratio = rad2ratio (small_rad ) 28slope = small_ratio < 2 29large_rad = peg2rad (largest ,pegs ) 30large_ratio = rad2ratio (large_rad ) 31# print "Original:", [str(x) for x in rad] 32# print "Start:", [str(x) for x in small_rad], small_ratio 33# print "End:", [str(x) for x in large_rad], large_ratio 34# print "small:", smallest, "\tlarge:", largest 35if small_ratio < 2 and large_ratio < 2 or small_ratio > 2 and large_ratio > 2 : 36return [- 1 ,- 1 ] 37for i in range (int (smallest ),int (largest )+ 1 ): 38rad = peg2rad (i ,pegs ) 39ratio = rad2ratio (rad ) 40# print "Loop:", [str(x) for x in rad], ratio 41if ratio == 2 : 42return [rad [0 ].numerator ,rad [0 ].denominator ] 43if ratio < 2 and not slope or ratio > 2 and slope : 44if ratio > 2 : 45i -= 1 46n = 1 47d = 1 48f = Fraction (n ,d ) 49ratio = rad2ratio (peg2rad (i + f ,pegs )) 50while ratio != 2 : 51d += 1 52if ratio < 2 : 53n += 1 54else : 55n -= 1 56f = Fraction (n ,d ) 57ratio = rad2ratio (peg2rad (i + f ,pegs )) 58f += i 59return [f .numerator ,f .denominator ] 60return [- 1 ,- 1 ] 61 62 63from random import randint 64import sys 65 66answer ([4 ,30 ,50 ]) 67answer ([4 ,17 ,50 ]) 68answer ([4 ,12 ])# FRACTION 69sys .exit () 70 71while True : 72# arr = [40, 80, 100, 150] 73arr = sorted ([randint (1 ,100 )for i in range (4 )]) 74ans = answer (arr ) 75ans 76if ans [1 ]not in (- 1 ,1 ): 77break 78sys .exit () 79 80a = Fraction (17 ,37 ) 81n = 1 82d = 1 83f = Fraction (n ,d ) 84"target" ,a ,"(" + str (float (a ))+ ")" 85while int (a )+ f != a : 86d += 1 87int (a )+ f ,"(" + str (float (int (a )+ f ))+ ")" 88if int (a )+ f < a : 89n += 1 90else : 91n -= 1 92f = Fraction (n ,d ) 93int (a )+ f ,"(" + str (float (int (a )+ f ))+ ")"