[ create a new paste ] login | about

Link: http://codepad.org/hKboFPd2    [ raw code | fork | 1 comment ]

Python, pasted on Apr 7:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
def divide(m, n):
    quotient, c = str(m // n) + ".", 10 * (m % n)
    while c and c < n:
        c *= 10
        quotient += "0"
    digits = ""
    passed = {}
    i = 0
    while True:
        if c in passed:
            prefix = digits[:passed[c]]
            cycle = digits[passed[c]:]
            result = quotient + prefix + "(" + cycle + ")"
            return result.replace("(0)", "").rstrip(".")
        q, r = c // n, c % n
        passed[c] = i
        digits += str(q)
        i += 1
        c = 10 * r


Output:
No errors or program output.


Create a new paste based on this one


Comments:
posted by Glenwing on Jun 27
Note: output is incorrect when M is negative, and loops infinitely when N is negative.

>>> divide(1, 2)
'0.5'
>>> divide(-1, 2)
'-1.5'
>>> divide(1, -2)
Traceback (most recent call last):
File "<pyshell#11>", line 1, in <module>
divide(1, -2)
File "<pyshell#1>", line 5, in divide
quotient += "0"
KeyboardInterrupt
>>> divide(-1, -2)
Traceback (most recent call last):
File "<pyshell#12>", line 1, in <module>
divide(-1, -2)
File "<pyshell#1>", line 5, in divide
quotient += "0"
KeyboardInterrupt
reply