Advertisement
Python253

magic_square_sums

May 12th, 2024
662
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.97 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. # Filename: magic_square_sums.py
  4. # Version: 1.0.0
  5. # Author: Jeoi Reqi
  6.  
  7. """
  8. This script efficiently generates magic squares and computes the sum of each row, column, and diagonal for specified dimension ranges. Key points include:
  9.  
  10.    Magic Square Generation:
  11.        - The script uses the Siamese method to generate magic squares of various dimensions.
  12.  
  13.    Sum Calculation:
  14.        - It calculates the sum of each row, column, and diagonal within the generated magic squares.
  15.  
  16.    User Interface:
  17.        - The script provides a user-friendly menu interface for selecting predefined dimension ranges.
  18.  
  19.    Terminal Output:
  20.        - It displays the sums of rows, columns, and diagonals to the terminal for the selected dimension range.
  21.  
  22.    File Saving Option:
  23.        - Additionally, users have the option to save the output data to a file. The filename is dynamically generated based on the selected dimension range.
  24.  
  25. Requirements:
  26.    - Python3.x
  27.  
  28. Functions:
  29.    1. magic_square(n): This function generates a magic square of dimension 'n x n' using the Siamese method.
  30.    It calculates the sum of each row, column, and diagonal within the square and returns a formatted string indicating the dimensions & sums of the magic squares in range.
  31.  
  32. Usage:
  33.    - Run the script in a Python environment.
  34.    - Follow the on-screen prompts to select an option from the menu and input the desired dimension range.
  35.    - The script will then generate magic squares for all odd dimensions within the specified range and display the sums of each row/column/diagonal to the terminal.
  36.    - Optionally, the user can choose to save the output data to a file in the current working directory.
  37.  
  38. Additional Notes:
  39.    - The script supports predefined dimension ranges ranging from 3x3 to 999x999.
  40.    - Magic squares for dimensions less than 3 or even dimensions are not supported.
  41.    - The sum of each row/column/diagonal is calculated and displayed for each generated magic square.
  42.    - Output data can be saved to a file with a dynamically generated filename based on the selected dimension range.
  43. """
  44.  
  45. import os
  46.  
  47. # Function to create Magic Square
  48. def magic_square(n):
  49.     if n < 3:
  50.         return "- Magic squares for dimensions less than 3 are not supported by this algorithm!\n"
  51.     elif n % 2 == 0:
  52.         return "- Even dimension values are not supported by this algorithm!\n"
  53.  
  54.     # Initialize the magic square with zeros
  55.     magicSquare = []
  56.     for i in range(n):
  57.         listt = []
  58.         for j in range(n):
  59.             listt.append(0)
  60.         magicSquare.append(listt)
  61.  
  62.     # Initialize starting position
  63.     i = n // 2
  64.     j = n - 1
  65.  
  66.     # Set the number of elements to insert
  67.     num = n * n
  68.     count = 1
  69.  
  70.     # Populate the magic square
  71.     while count <= num:
  72.         if i == -1 and j == n:  # condition 4
  73.             j = n - 2
  74.             i = 0
  75.         else:
  76.             if j == n:  # column value is exceeding
  77.                 j = 0
  78.  
  79.             if i < 0:  # row  is becoming -1
  80.                 i = n - 1
  81.  
  82.         # Check if cell is occupied
  83.         if magicSquare[i][j] != 0:
  84.             j = j - 2
  85.             i = i + 1
  86.             continue
  87.  
  88.         else:
  89.             magicSquare[i][j] = count
  90.             count += 1
  91.  
  92.         # Move to the next cell
  93.         i = i - 1
  94.         j = j + 1  # condition 1
  95.  
  96.     # Calculate the sum of each row, column, and diagonal
  97.     row_sums = [sum(row) for row in magicSquare]
  98.     col_sums = [sum(col) for col in zip(*magicSquare)]
  99.     diagonal_sum_1 = sum(magicSquare[i][i] for i in range(n))
  100.     diagonal_sum_2 = sum(magicSquare[i][n - i - 1] for i in range(n))
  101.  
  102.     return f"The magic square {n}x{n} sum of each row/column/diagonal is: {sum(row_sums)}\n"
  103.  
  104. if __name__ == "__main__":
  105.     """
  106.    Main function to execute the script.
  107.    """
  108.     print("   :: MAGIC SQUARES GENERATOR ::\n")
  109.     print("\t:: Options Menu :")
  110.     print("    ___________________________\n")
  111.     print("    Option 1:     3x3 - 9x9")
  112.     print("    Option 2:   11x11 - 31x31")
  113.     print("    Option 3:   33x33 - 99x99")
  114.     print("    Option 4: 101x101 - 315x315")
  115.     print("    Option 5: 317x317 - 999x999")  # This Option Will Take Some Time
  116.     print("    Option 6: !SHOW ALL RANGES!")  # This Option Will Take Alot Of Time
  117.     print("    ___________________________")
  118.  
  119.     option = int(input("\n    Enter the option number: "))
  120.     output_data = ""
  121.     start_range = 0
  122.     end_range = 0
  123.  
  124.     if option == 1:
  125.         start_range = 3
  126.         end_range = 9
  127.     elif option == 2:
  128.         start_range = 11
  129.         end_range = 31
  130.     elif option == 3:
  131.         start_range = 33
  132.         end_range = 99
  133.     elif option == 4:
  134.         start_range = 101
  135.         end_range = 315
  136.     elif option == 5:
  137.         print(
  138.             "\n\tThis Option Will Take Some Time...\n\tThank You For Your Patience!\n"
  139.         )
  140.         start_range = 317
  141.         end_range = 999
  142.     elif option == 6:
  143.         print(
  144.             "\n\tThis Option Will Take Alot Of Time...\n\tThank You For Your Patience!\n"
  145.         )
  146.         start_range = 3
  147.         end_range = 999
  148.     else:
  149.         print("\nInvalid option selected!\n")
  150.  
  151.     for n in range(start_range, end_range + 1, 2):
  152.         output_data += magic_square(n)
  153.  
  154.     print(output_data)
  155.  
  156.     # Save the output sums of the given ranges to a dynamically named file in the curent working directory
  157.     save_file = input(
  158.         "\nDo you want to save the output to a file?\n\n1: Yes\n2: No\n\nMake your selection (1 or 2): "
  159.     )
  160.     if save_file == "1":
  161.         file_name = (
  162.             f"magic_square_{start_range}x{start_range}_to_{end_range}x{end_range}.txt"
  163.         )
  164.         with open(file_name, "w") as file:
  165.             file.write(output_data)
  166.         print(f"Output saved to {file_name} in the current directory!\n")
  167.     elif save_file == "2":
  168.         print("\nOutput not saved!\n")
  169.     else:
  170.         print("\nInvalid input. Output not saved!\n")
  171.  
  172.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement