- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

# Latin Square in Python

The Latin square is a matrix that has a special pattern. Let's see different examples to examine the pattern.

1 2 2 1 1 2 3 3 1 2 2 3 1 1 2 3 4 4 1 2 3 3 4 1 2 2 3 4 1

The Latin square that you get will be of different size as you notice in the above examples. But, if you carefully observe the above matrices' pattern, you will find out that the last number of the previous row comes as the first element of the next row.

That's the pattern hidden in Latin square. We have to write the program that generates the above matrix for the input n.

## Algorithm

- Initialise the n with any number you like.
- Initialise a number with the value n + 1 call it as first_half_end.
- Write a loop that iterates from 1 to n both inclusive.
- Assign the value of first_half_end to a variable called first_half_start.
- Write a loop until first_half_start reaches to the value n.
- Print the iterating variable i.e.., first_half_start.

- Write a loop that iterates from 1 to first_half_end.
- Print the iterating variable.

- Decrement the value of first_half_end by 1.
- Move the next row.

## Implementation

Following is the implementation of the above algorithm in Python

def generateLatinSquare(n): first_half_end = n + 1 for i in range(1, n + 1): first_half_start = first_half_end while (first_half_start <= n): print(first_half_start, end=" ") first_half_start += 1 for second_half_start in range(1, first_half_end): print(second_half_start, end=" ") first_half_end -= 1 print() print() if __name__ == "__main__": generateLatinSquare(2) generateLatinSquare(3) generateLatinSquare(4)

## Output

If you run the above code, then you will get the following result.

1 2 2 1 1 2 3 3 1 2 2 3 1 1 2 3 4 4 1 2 3 3 4 1 2 2 3 4 1

- Related Questions & Answers
- Latin Square in C++
- Goat Latin in Python
- Guess Nearest Square Root in Python
- Square and Square root in Arduino
- Square list of elements in sorted form in Python
- Program to print Square inside a Square in C
- Magic Square
- Check if given number is perfect square in Python
- Count square and non-square numbers before n in C++
- Maximal Square in C++
- How to find Square root of complex numbers in Python?
- How to calculate square root of a number in Python?
- How to make hollow square marks with Matplotlib in Python?
- Compute the square root of input with emath in Python
- Return the square of the complex-value input in Python

Advertisements