"""
Created by Hadron DaVinci
https://hadrondavinci.com

For Educational Purposes
To Run:
    1) Download https://hadrondavinci.com/assets/code/2020-12-05/method2.py
    2) python method2.py

Expected Output:
I: 12
II: 123
ID: 132
IID: 1243
IIDD: 12543
IIDDD: 126543
D: 21
DD: 321
DI: 213
DDI: 3214
DDII: 32145
DDIDDIID: 321654798
"""


def process_trend_data(result: str, stack: list) -> (str, list):
    """
    Uses information about the trend contained in stack to append digits to result.
    :param result: resulting string of digits
    :param stack:
    """
    while len(stack):
        result = result + stack.pop()
    return result, stack


def foo(_str: str) -> int:
    """
    Contains the main logic
    :param _str: input string
    :return: number formed by digits
    """
    stack = []
    result = ""

    for i in range(len(_str) + 1):                              # must iterate to one more than trend
        try:
            current_trend = _str[i]
        except IndexError:
            current_trend = None

        stack.append(str(i + 1))                                # build stack for all trends, I and D

        if current_trend is None:                               # when no trends are remaining, process previous trend
            result, stack = process_trend_data(result, stack)

        elif current_trend == 'I':                              # when the trend is I, process previous trend
            result, stack = process_trend_data(result, stack)

    print(f"{_str}:", result)
    return int(result)


if __name__ == "__main__":
    assert foo("I") == 12
    assert foo("II") == 123
    assert foo("ID") == 132
    assert foo("IID") == 1243
    assert foo("IIDD") == 12543
    assert foo("IIDDD") == 126543
    assert foo("D") == 21
    assert foo("DD") == 321
    assert foo("DI") == 213
    assert foo("DDI") == 3214
    assert foo("DDII") ==32145
    assert foo("DDIDDIID") == 321654798
