بخشی از مقاله

Several example codes

~2 دقیقه مطالعه · آخرین به‌روزرسانی ۲۶ شهریور ۱۴۰۴

Magic Square Definition

A magic square is an n×n matrix where:
- Each cell contains a unique integer from 1 to
- The sum of each row, each column, and both diagonals is the same
This algorithm works for odd values of n.


Magic Square Construction Rules:

  1. Start: Place the number 1 in the middle column of the first row.
  2. Move: For each next number, move diagonally one step up and one step left.
  3. If occupied: If the target cell is already filled, move one step directly down instead.
  4. If out of bounds: If moving diagonally goes outside the matrix, wrap around to the opposite edge of the row or column.
  5. If both row and column are out of bounds: Move one step directly down from the last position.

Python Code:


def generate_magic_square(n):
    if n % 2 == 0:
        raise ValueError("Magic square generation only works for odd n.")

    square = [[0] * n for _ in range(n)]
    num = 1
    row, col = 0, n // 2  # Step A

    while num <= n * n:
        square[row][col] = num
        num += 1

        next_row = (row - 1) % n  # Step B + wrap
        next_col = (col - 1) % n

        if square[next_row][next_col] != 0:  # Step C
            row = (row + 1) % n
        else:
            row, col = next_row, next_col

    return square

# Display the magic square
n = int(input("Enter an odd number n: "))
magic = generate_magic_square(n)
print("\nMagic Square:")
for row in magic:
    print(row)

Sample Output (n = 3):


Magic Square:
[8, 1, 6]
[3, 5, 7]
[4, 9, 2]

Explanation:

Each number from 1 to is placed according to the diagonal rule.
If the diagonal cell is occupied or out of bounds, the algorithm adjusts by moving down or wrapping around.
The final matrix satisfies the magic condition: all rows, columns, and diagonals have equal sums.


نوشته و پژوهش‌شده توسط دکتر شاهین صیامی

مقالات مرتبط

Complete Guide to Python Decorators – Enhancing Function Behavior with Reusable Logic

Decorators in Python are a powerful tool for modifying or extending the behavior of functions and classes without changing their original code. They allow developers to implement reusable logic such as logging, authentication, caching, or timing in a clean and maintainable way. This article explores the structure, definition, common use cases, and practical examples of decorators in Python.

ادامه

Comprehensive Guide to Python Classes – Object-Oriented Design, Structure, Inheritance, and Practical Use

Classes in Python are the foundation of object-oriented programming, allowing developers to define complex data structures, encapsulate logic, and create scalable, maintainable systems. This article walks through the fundamentals of defining classes, constructors, methods, inheritance, encapsulation, and real-world applications in Python projects.

ادامه

Several example codes

understand the Python programming language

ادامه

Complete Guide to Getting Text Input from Users in Python

In Python, accepting input from users is one of the simplest yet most powerful features for interactive programming. This article explores the input() function in depth, explains how to cast types, validate user data, and use input within loops and conditions. Real-life examples help clarify each concept, making this guide perfect for beginners and intermediate learners.

ادامه

Comprehensive Guide to Functions in Python: Structure, Types, and Use Cases

Functions in Python are essential building blocks for writing modular, reusable, and maintainable code. This article introduces function definitions, distinguishes between built-in and user-defined functions, explores parameters and return values, and presents advanced topics such as recursion and lambda expressions. Whether you're a beginner or brushing up for interviews, this guide offers a clear and accessible foundation.

ادامه

Loops, Iterators, and Repetition Control in Python

Loops, Iterators, and Repetition Control in Python

ادامه