iota/trits.py
def trits_from_int(n, pad=1):
    # type: (int, Optional[int]) -> List[int]
    """
    Returns a trit representation of an integer value.

    :param n:
        Integer value to convert.

    :param pad:
        Ensure the result has at least this many trits.

    References:

    - https://dev.to/buntine/the-balanced-ternary-machines-of-soviet-russia
    - https://en.wikipedia.org/wiki/Balanced_ternary
    - https://rosettacode.org/wiki/Balanced_ternary#Python
    """
    if n == 0:
        trits = []
    else:
        quotient, remainder = divmod(n, 3)

        if remainder == 2:
            # Lend 1 to the next place so we can make this trit
            # negative.
            quotient += 1
            remainder = -1

        trits = [remainder] + trits_from_int(quotient, pad=0)

    if pad:
        trits += [0] * max(0, pad - len(trits))

    return trits
def trits_from_int(n, pad=1):
    # type: (int, Optional[int]) -> List[int]
    """
    Returns a trit representation of an integer value.

    :param n:
        Integer value to convert.

    :param pad:
        Ensure the result has at least this many trits.

    References:

    - https://dev.to/buntine/the-balanced-ternary-machines-of-soviet-russia
    - https://en.wikipedia.org/wiki/Balanced_ternary
    - https://rosettacode.org/wiki/Balanced_ternary#Python
    """
    if n == 0:
        trits = []
    else:
        quotient, remainder = divmod(n, 3)

        if remainder == 2:
            # Lend 1 to the next place so we can make this trit
            # negative.
            quotient += 1
            remainder = -1

        trits = [remainder] + trits_from_int(quotient, pad=0)

    if pad:
        trits += [0] * max(0, pad - len(trits))

    return trits
Returns a trit representation of an integer value.

    :param n:
        Integer value to convert.

    :param pad:
        Ensure the result has at least this many trits.

    References:

    - https://dev.to/buntine/the-balanced-ternary-machines-of-soviet-russia
    - https://en.wikipedia.org/wiki/Balanced_ternary
    - https://rosettacode.org/wiki/Balanced_ternary#Python