from string import index
n,d=1,7
def f(n, d):
x = n * 9
z = x
k = 1
while z % d:
z = z * 10 + x
k += 1
return k, z / d
#print f(n,d)
# (.051,2) = .0515151... = 51/990
# n = len(s[index(s,'~'):])
def r(r, n):
s = str(r)
a,b = s[index(s,'.')+1:-n], s[-n:]
al,l = len(a), len(a+b)
u,v = 10**al, 10**l
n,d = int(r*u-int(a if a<>''else 1)), v-u
g = gcd(n,d)
while g <> 1:
n,d = n/g,d/g
g = gcd(n,d)
return (n,d)
gcd=lambda a,b:a if b==0 else gcd(b,a%b)
# These aren't all correct, but why?
print r(1.1,1) # = 10/9
print r(2.5,1) # = 23/9 X
print r(0.4,1) # = 4/9 X
print r(0.142857,6) # = 1/7 X
ZnJvbSBzdHJpbmcgaW1wb3J0IGluZGV4CgpuLGQ9MSw3CmRlZiBmKG4sIGQpOgogICAgeCA9IG4gKiA5CiAgICB6ID0geAogICAgayA9IDEKICAgIHdoaWxlIHogJSBkOgogICAgICAgIHogPSB6ICogMTAgKyB4CiAgICAgICAgayArPSAxCiAgICByZXR1cm4gaywgeiAvIGQKCiNwcmludCBmKG4sZCkKCiMgKC4wNTEsMikgPSAuMDUxNTE1MS4uLiA9IDUxLzk5MAojIG4gPSBsZW4oc1tpbmRleChzLCd+Jyk6XSkKZGVmIHIociwgbik6CiAgICBzID0gc3RyKHIpCiAgICBhLGIgPSBzW2luZGV4KHMsJy4nKSsxOi1uXSwgc1stbjpdCiAgICBhbCxsID0gbGVuKGEpLCBsZW4oYStiKQogICAgdSx2ID0gMTAqKmFsLCAxMCoqbAogICAgbixkID0gaW50KHIqdS1pbnQoYSBpZiBhPD4nJ2Vsc2UgMSkpLCB2LXUKICAgIGcgPSBnY2QobixkKQogICAgd2hpbGUgZyA8PiAxOgogICAgICAgIG4sZCA9IG4vZyxkL2cKICAgICAgICBnID0gZ2NkKG4sZCkKICAgIHJldHVybiAobixkKQoKZ2NkPWxhbWJkYSBhLGI6YSBpZiBiPT0wIGVsc2UgZ2NkKGIsYSViKQogICAgCiMgVGhlc2UgYXJlbid0IGFsbCBjb3JyZWN0LCBidXQgd2h5PwpwcmludCByKDEuMSwxKSAjID0gMTAvOQpwcmludCByKDIuNSwxKSAjID0gMjMvOSAJCVgKcHJpbnQgcigwLjQsMSkgIyA9IDQvOQkJCVgKcHJpbnQgcigwLjE0Mjg1Nyw2KSAjID0gMS83CQlYCg==