5
\$\begingroup\$

Here is a fairly straightforward solution in Python to the Tower of Hanoi problem

def helper(number_rings: int, origin: int, target: int, spare: int, list_result=[])->list:
    """Helper function works out which ring to move"""
    if number_rings == 1:
        list_result.append([origin, target])
    else:
        #Move all but 1 ring from ORIGIN tower to SPARE tower
        helper(number_rings - 1, origin=origin, target=spare, spare=target)
        #MOVE the last ring from ORIGIN tower to TARGET tower
        helper(1, origin=origin, target=target, spare=spare)
        #MOVE the remaining rings from the SPARE tower to TARGET tower
        helper(number_rings - 1, origin=spare, target=target, spare=origin)
        return list_result


def move_rings(number_rings: int)->int:
    """Function prints the ring move required"""
    dict_rings = {0: "A", 1: "B", 2: "C"}
    if number_rings == 1:
        print("Move from A to C")
        return 1
    list_result = helper(number_rings, 0, 2, 1)
    for item in list_result:
        print("Move from", dict_rings[item[0]], "to", dict_rings[item[1]])
    return len(list_result)


if __name__ == "__main__":
    counter = move_rings(1)
    print(f"Solution possible in {counter} moves")

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.