> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Fraction to Recurring Decimal Python Solution

> Tested Python solution for LeetCode 166 with 20 pytest cases. Generate a practice environment with lcpy.

LeetCode 166, [Medium](/catalog/medium). Topics: [Hash Table](/catalog/topics/hash-table), [Math](/catalog/topics/math), [String](/catalog/topics/string). [View on LeetCode](https://leetcode.com/problems/fraction-to-recurring-decimal/description/).

Generate this problem as a practice environment: tested reference solution, 20 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 166   # by problem number
lcpy gen -s fraction_to_recurring_decimal   # by problem name
```

## Problem

Given two integers representing the numerator and denominator of a fraction, return the fraction in string format.

If the fractional part is repeating, enclose the repeating part in parentheses.

If multiple answers are possible, return any of them.

It is guaranteed that the length of the answer string is less than 10^4 for all the given inputs.

Note that if the fraction can be represented as a finite length string, you must return it.

### Examples

```
Input: numerator = 1, denominator = 2
Output: "0.5"
```

```
Input: numerator = 2, denominator = 1
Output: "2"
```

```
Input: numerator = 4, denominator = 333
Output: "0.(012)"
```

### Constraints

* -2^31 \<= numerator, denominator \<= 2^31 - 1
* denominator != 0

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/fraction_to_recurring_decimal/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/fraction_to_recurring_decimal/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
class Solution:
    # Time: O(denominator) digits emitted, bounded by the answer length
    # Space: O(k) for the remainder-position map, k = cycle length
    def fraction_to_decimal(self, numerator: int, denominator: int) -> str:
        if numerator == 0:
            return "0"

        sign = "-" if (numerator < 0) != (denominator < 0) else ""
        num, den = abs(numerator), abs(denominator)

        whole, remainder = divmod(num, den)
        parts = [str(whole)]

        if remainder:
            seen: dict[int, int] = {}
            digits: list[str] = []
            while remainder and remainder not in seen:
                seen[remainder] = len(digits)
                remainder *= 10
                digits.append(str(remainder // den))
                remainder %= den
            fraction = "".join(digits)
            if remainder:
                cycle_start = seen[remainder]
                fraction = f"{fraction[:cycle_start]}({fraction[cycle_start:]})"
            parts.append(f".{fraction}")

        return sign + "".join(parts)
```

## Complexity

| Time | Space |
| - | - |
| O(denominator) digits emitted, bounded by the answer length | O(k) for the remainder-position map, k = cycle length |

## Tags


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.