Skip to content

Instantly share code, notes, and snippets.

@kracekumar
Created December 16, 2025 00:02
Show Gist options
  • Select an option

  • Save kracekumar/c326b3a04102453aaa9b0ae4219ed6b0 to your computer and use it in GitHub Desktop.

Select an option

Save kracekumar/c326b3a04102453aaa9b0ae4219ed6b0 to your computer and use it in GitHub Desktop.
Write a function to generate a Latin Square given a positive integer `n`. The values can be any n distinct values, and don't have to be consistent for different n.
def latin_square(n):
if n <= 0:
return []
numbers = list(range(1, n + 1))
result = []
for i in range(n):
result.append(numbers.copy())
# Rotate left: move first element to the end
numbers = numbers[1:] + [numbers[0]]
return result
if __name__ == "__main__":
print(latin_square(1))
print(latin_square(2))
print(latin_square(3))
print(latin_square(4))
$uv run python latin_square.py
[[1]]
[[1, 2], [2, 1]]
[[1, 2, 3], [2, 3, 1], [3, 1, 2]]
[[1, 2, 3, 4], [2, 3, 4, 1], [3, 4, 1, 2], [4, 1, 2, 3]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment