fork download
  1. from string import index
  2.  
  3. n,d=1,7
  4. def f(n, d):
  5. x = n * 9
  6. z = x
  7. k = 1
  8. while z % d:
  9. z = z * 10 + x
  10. k += 1
  11. return k, z / d
  12.  
  13. #print f(n,d)
  14.  
  15. # (.051,2) = .0515151... = 51/990
  16. # n = len(s[index(s,'~'):])
  17. def r(r, n):
  18. s = str(r)
  19. a,b = s[index(s,'.')+1:-n], s[-n:]
  20. al,l = len(a), len(a+b)
  21. u,v = 10**al, 10**l
  22. n,d = int(r*u-int(a if a<>''else 1)), v-u
  23. g = gcd(n,d)
  24. while g <> 1:
  25. n,d = n/g,d/g
  26. g = gcd(n,d)
  27. return (n,d)
  28.  
  29. gcd=lambda a,b:a if b==0 else gcd(b,a%b)
  30.  
  31. # These aren't all correct, but why?
  32. print r(1.1,1) # = 10/9
  33. print r(2.5,1) # = 23/9 X
  34. print r(0.4,1) # = 4/9 X
  35. print r(0.142857,6) # = 1/7 X
  36.  
Success #stdin #stdout 0.01s 7736KB
stdin
Standard input is empty
stdout
(11, 9)
(26, 9)
(1, 3)
(20408, 142857)