Tower of Hanoi Coding Experiment
⚠️ LLM-generated content notice: Parts of this page may have been created or edited with the assistance of a large language model (LLM). The prompts that have been used might be on the page itself, the discussion page or in straight forward cases the prompt was just "Write a mediawiki page on X" with X being the page name. While the content has been reviewed it might still not be accurate or error-free.
Experiment
This is an experiment to let different LLMs create code for the Tower of Hanoi Problem with preferences stated to guide the code creation
Prompts
clear my preferences and set to
- act as a professional Python software engineer that prefers clean readable and maintainable code.
- prefer google doc strings and type hints for functions needing explanation.
- avoid one-liners and list comprehesions to make code debugable.
- never return function results direcly but create assign a variable to be inspectable before returning.
- When refactoring code provide the delta lines to the previous version of the code
- preserve header comments and comment out code
- never change an API if not explicitly asked for
- never put example and test code in the same answer block as the implementation code. It is fine to answer with three blocks
- code modifications must still pass existing tests - ask for the testcode if a decision needs to be made
- Avoid hallucinations or assumptions
- No unsolicited suggestions, comments
- No speculative or unnecessary logic
- No changes that would introduce new dependencies without feedback
- Concise responses
- Use direct, specific examples
create a module for solving the tower of hanoi
create a mediawiki markup section documenting this interaction with the preferences, prompts and the three code blocks as sections using <source lang='python'> state your name and version as the top section title
Open AI ChatGPT 4-o
Preferences
1. Clean, readable, and maintainable code. 2. Google-style docstrings and type hints for functions needing explanation. 3. Avoid one-liners and list comprehensions to make code debuggable. 4. Never return function results directly; assign them to a variable first. 5. Provide delta lines when refactoring. 6. Preserve header comments and comment out code. 7. Never change an API unless explicitly requested. 8. Keep example and test code separate from implementation. 9. Code modifications must pass existing tests; ask for the test code if a decision is needed. 10. Avoid hallucinations or assumptions. 11. No unsolicited suggestions or comments. 12. No speculative or unnecessary logic. 13. No changes that introduce new dependencies without feedback. 14. Responses should be concise and use direct, specific examples.
Module Implementation
# hanoi_solver.py
from typing import List, Tuple
def solve_tower_of_hanoi(n: int, source: str, auxiliary: str, destination: str) -> List[Tuple[str, str]]:
"""
Solves the Tower of Hanoi problem and returns the sequence of moves.
Args:
n (int): The number of disks.
source (str): The source rod identifier.
auxiliary (str): The auxiliary rod identifier.
destination (str): The destination rod identifier.
Returns:
List[Tuple[str, str]]: A list of tuples representing the moves, where each tuple is (from_rod, to_rod).
"""
moves = []
def move_disks(count: int, from_rod: str, to_rod: str, aux_rod: str) -> None:
if count == 1:
moves.append((from_rod, to_rod))
else:
move_disks(count - 1, from_rod, aux_rod, to_rod)
moves.append((from_rod, to_rod))
move_disks(count - 1, aux_rod, to_rod, from_rod)
move_disks(n, source, destination, auxiliary)
return moves
Example Usage
from hanoi_solver import solve_tower_of_hanoi
# Example usage
moves = solve_tower_of_hanoi(3, 'A', 'B', 'C')
for move in moves:
print(f"Move disk from {move[0]} to {move[1]}")
Test Code
def test_solve_tower_of_hanoi():
expected_moves = [
('A', 'C'), ('A', 'B'), ('C', 'B'),
('A', 'C'), ('B', 'A'), ('B', 'C'), ('A', 'C')
]
result = solve_tower_of_hanoi(3, 'A', 'B', 'C')
assert result == expected_moves, f"Expected {expected_moves} but got {result}"
test_solve_tower_of_hanoi()
Claude 3.5 Sonnet
Python Coding Preferences
- Professional Python engineer focused on clean, readable, maintainable code
- Google docstrings and type hints for functions needing explanation
- Avoid one-liners and list comprehensions for debuggability
- Use inspectable variables instead of direct returns
- Show delta lines for refactoring changes
- Preserve header comments, comment out old code
- No API changes without explicit request
- Separate implementation, example, and test code
- Code must pass existing tests
- No hallucinations or assumptions
- No unsolicited suggestions/comments
- No speculative/unnecessary logic
- No new dependencies without feedback
- Concise responses
- Direct, specific examples
Implementation Code
from typing import List, Optional
def move_tower(height: int, source: str, target: str, auxiliary: str) -> List[tuple[str, str]]:
"""Solve Tower of Hanoi puzzle and return list of moves.
Args:
height: Number of disks in the tower
source: Name of source peg
target: Name of target peg
auxiliary: Name of auxiliary peg
Returns:
List of tuples containing (source, target) for each move
Example:
moves = move_tower(3, 'A', 'C', 'B')
"""
moves: List[tuple[str, str]] = []
def _move_disks(n: int, src: str, tgt: str, aux: str) -> None:
if n == 1:
moves.append((src, tgt))
return
_move_disks(n - 1, src, aux, tgt)
moves.append((src, tgt))
_move_disks(n - 1, aux, tgt, src)
_move_disks(height, source, target, auxiliary)
return moves
Example Usage
def print_solution(moves: List[tuple[str, str]]) -> None:
"""Print the solution moves in readable format."""
for i, (src, tgt) in enumerate(moves, 1):
print(f"Move {i}: {src} -> {tgt}")
# Solve for 3 disks
solution = move_tower(3, 'A', 'C', 'B')
print_solution(solution)
Test Code
def test_tower_of_hanoi():
# Test with 1 disk
result = move_tower(1, 'A', 'C', 'B')
assert result == [('A', 'C')], "Single disk move failed"
# Test with 2 disks
result = move_tower(2, 'A', 'C', 'B')
assert result == [('A', 'B'), ('A', 'C'), ('B', 'C')], "Two disk moves failed"
# Test with 3 disks
result = move_tower(3, 'A', 'C', 'B')
expected = [
('A', 'C'), ('A', 'B'), ('C', 'B'),
('A', 'C'), ('B', 'A'), ('B', 'C'),
('A', 'C')
]
assert result == expected, "Three disk moves failed"
print("All tests passed!")
test_tower_of_hanoi()
Mistral Large 2
Tower of Hanoi Module
Preferences
- Act as a professional Python software engineer that prefers clean, readable, and maintainable code. - Prefer Google docstrings and type hints for functions needing explanation. - Avoid one-liners and list comprehensions to make code debuggable. - Never return function results directly but create and assign a variable to be inspectable before returning. - When refactoring code, provide the delta lines to the previous version of the code. - Preserve header comments and comment out code. - Never change an API if not explicitly asked for. - Never put example and test code in the same answer block as the implementation code. It is fine to answer with three blocks. - Code modifications must still pass existing tests - ask for the test code if a decision needs to be made. - Avoid hallucinations or assumptions. - No unsolicited suggestions, comments. - No speculative or unnecessary logic. - No changes that would introduce new dependencies without feedback. - Concise responses. - Use direct, specific examples.
Implementation Code
# tower_of_hanoi.py
def tower_of_hanoi(n: int, source: str, auxiliary: str, target: str) -> None:
"""
Solve the Tower of Hanoi problem.
Args:
n (int): Number of disks.
source (str): The source rod.
auxiliary (str): The auxiliary rod.
target (str): The target rod.
"""
if n == 1:
print(f"Move disk 1 from {source} to {target}")
return
tower_of_hanoi(n - 1, source, target, auxiliary)
print(f"Move disk {n} from {source} to {target}")
tower_of_hanoi(n - 1, auxiliary, source, target)
Example Code
# example.py
from tower_of_hanoi import tower_of_hanoi
# Example usage
tower_of_hanoi(3, 'A', 'B', 'C')
Test Code
# test_tower_of_hanoi.py
from tower_of_hanoi import tower_of_hanoi
def test_tower_of_hanoi():
# Test with 3 disks
expected_output = [
"Move disk 1 from A to C",
"Move disk 2 from A to B",
"Move disk 1 from C to B",
"Move disk 3 from A to C",
"Move disk 1 from B to A",
"Move disk 2 from B to C",
"Move disk 1 from A to C"
]
# Capture the output
import io
import sys
captured_output = io.StringIO()
sys.stdout = captured_output
tower_of_hanoi(3, 'A', 'B', 'C')
sys.stdout = sys.__stdout__
# Check the output
output = captured_output.getvalue().strip().split('\n')
assert output == expected_output, f"Expected {expected_output}, but got {output}"
test_tower_of_hanoi()
Gemini 1.5 Flash
- Prompt:**
> clear my preferences and set to > > act as a professional Python software engineer that prefers clean readable and maintainable code. > prefer google doc strings and type hints for functions needing explanation. > avoid one-liners and list comprehesions to make code debugable. > never return function results direcly but create assign a variable to be inspectable before returning. > When refactoring code provide the delta lines to the previous version of the code > preserve header comments and comment out code > never change an API if not explicitly asked for > never put example and test code in the same answer block as the implementation code. It is fine to answer with three blocks > code modifications must still pass existing tests - ask for the testcode if a decision needs to be made > Avoid hallucinations or assumptions > No unsolicited suggestions, comments > No speculative or unnecessary logic > No changes that would introduce new dependencies without feedback > Concise responses > Use direct, specific examples > create a module for solving the tower of hanoi > create a mediawiki markup section with your name and version as the top level section documenting this > interaction with the preferences and the three code blocks as sections > using <source lang='python'>
- Response:**
"""
Module for solving the Tower of Hanoi puzzle.
This module provides a function `solve_tower_of_hanoi` that solves the classic Tower of Hanoi puzzle.
Args:
n_disks (int): The number of disks to be moved.
source_peg (int): The index of the source peg (0, 1, or 2).
target_peg (int): The index of the target peg (0, 1, or 2).
auxiliary_peg (int): The index of the auxiliary peg (0, 1, or 2).
Returns:
None
"""
def solve_tower_of_hanoi(n_disks: int, source_peg: int, target_peg: int, auxiliary_peg: int) -> None:
"""Solves the Tower of Hanoi puzzle.
This function recursively solves the Tower of Hanoi puzzle, moving the disks from the `source_peg` to the `target_peg` using the `auxiliary_peg`.
Args:
n_disks (int): The number of disks to be moved.
source_peg (int): The index of the source peg (0, 1, or 2).
target_peg (int): The index of the target peg (0, 1, or 2).
auxiliary_peg (int): The index of the auxiliary peg (0, 1, or 2).
"""
if n_disks == 1:
# Move the single disk directly to the target peg
print(f"Move disk 1 from peg {source_peg + 1} to peg {target_peg + 1}")
else:
# Move n-1 disks to the auxiliary peg
solve_tower_of_hanoi(n_disks - 1, source_peg, auxiliary_peg, target_peg)
# Move the largest disk to the target peg
print(f"Move disk {n_disks} from peg {source_peg + 1} to peg {target_peg + 1}")
# Move n-1 disks from the auxiliary peg to the target peg
solve_tower_of_hanoi(n_disks - 1, auxiliary_peg, target_peg, source_peg)
- Description:**
This module provides a function `solve_tower_of_hanoi` that recursively solves the classic Tower of Hanoi puzzle.
- Usage:**
```python solve_tower_of_hanoi(3, 0, 2, 1)
Tower of Hanoi Python Module Interaction (Pi, your personal AI - Version 1.0)
Prompts
- Create a module for solving the Tower of Hanoi problem.
- Create a MediaWiki markup section documenting the interaction with preferences and code blocks as sections.
Preferences
- Act as a professional Python software engineer that prefers clean, readable, and maintainable code.
- Prefer Google docstrings and type hints for functions needing explanation.
- Avoid one-liners and list comprehensions to make code debugable.
- Never return function results directly; assign a variable to be inspectable before returning.
- When refactoring code, provide delta lines to the previous version.
- Preserve header comments and comment out code.
- Never change an API unless explicitly asked for.
- Keep example and test code in separate blocks from the implementation code.
- Code modifications must pass existing tests; request test code if a decision is needed.
- Avoid hallucinations or assumptions.
- No unsolicited suggestions or comments.
- No speculative or unnecessary logic.
- No changes that would introduce new dependencies without feedback.
- Concise responses.
- Use direct, specific examples.
Module Implementation
# tower_of_hanoi.py
def hanoi(n: int) -> None:
"""Solves the Tower of Hanoi problem.
Moves a stack of `n` disks from the source rod to the destination rod. The auxiliary rod is used as an intermediate.
Args:
n (int): The number of disks to move
Returns:
None
"""
source = 'A'
auxiliary = 'B'
destination = 'C'
if n == 1:
print(f"Move disk 1 from {source} to {destination}")
else:
hanoi(n - 1, source, destination, auxiliary)
print(f"Move disk {n} from {source} to {destination}")
hanoi(n - 1, auxiliary, source, destination)
def hanoi_iterative(n: int) -> None:
"""Solves the Tower of Hanoi problem using an iterative approach.
Moves a stack of `n` disks from the source rod to the destination rod. The auxiliary rod is used as an intermediate.
Args:
n (int): The number of disks to move
Returns:
None
"""
source = 'A'
auxiliary = 'B'
destination = 'C'
for i in range(2 ** n - 1):
source_index = i % 3
destination_index = (((n & i) > 0) * source_index) + (((n & i) == 0) * ((source_index + 1) % 3))
print(f"Move disk 1 from {source} to {destination}")
Example Code
# Example code for using the Tower of Hanoi module.
# Import the module.
import tower_of_hanoi
# Test hanoi() with 3 disks.
tower_of_hanoi.hanoi(3)
# Test hanoi_iterative() with 3 disks.
tower_of_hanoi.hanoi_iterative(3)
Test Code
# Test code for the Tower of Hanoi module.
def test_hanoi_solution():
# Assert hanoi() correctly moves 3 disks.
# ... Test implementation ...