Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python
- # -*- coding: utf-8 -*-
- # Filename: magic_square_sums.py
- # Version: 1.0.0
- # Author: Jeoi Reqi
- """
- This script efficiently generates magic squares and computes the sum of each row, column, and diagonal for specified dimension ranges. Key points include:
- Magic Square Generation:
- - The script uses the Siamese method to generate magic squares of various dimensions.
- Sum Calculation:
- - It calculates the sum of each row, column, and diagonal within the generated magic squares.
- User Interface:
- - The script provides a user-friendly menu interface for selecting predefined dimension ranges.
- Terminal Output:
- - It displays the sums of rows, columns, and diagonals to the terminal for the selected dimension range.
- File Saving Option:
- - Additionally, users have the option to save the output data to a file. The filename is dynamically generated based on the selected dimension range.
- Requirements:
- - Python3.x
- Functions:
- 1. magic_square(n): This function generates a magic square of dimension 'n x n' using the Siamese method.
- 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.
- Usage:
- - Run the script in a Python environment.
- - Follow the on-screen prompts to select an option from the menu and input the desired dimension range.
- - 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.
- - Optionally, the user can choose to save the output data to a file in the current working directory.
- Additional Notes:
- - The script supports predefined dimension ranges ranging from 3x3 to 999x999.
- - Magic squares for dimensions less than 3 or even dimensions are not supported.
- - The sum of each row/column/diagonal is calculated and displayed for each generated magic square.
- - Output data can be saved to a file with a dynamically generated filename based on the selected dimension range.
- """
- import os
- # Function to create Magic Square
- def magic_square(n):
- if n < 3:
- return "- Magic squares for dimensions less than 3 are not supported by this algorithm!\n"
- elif n % 2 == 0:
- return "- Even dimension values are not supported by this algorithm!\n"
- # Initialize the magic square with zeros
- magicSquare = []
- for i in range(n):
- listt = []
- for j in range(n):
- listt.append(0)
- magicSquare.append(listt)
- # Initialize starting position
- i = n // 2
- j = n - 1
- # Set the number of elements to insert
- num = n * n
- count = 1
- # Populate the magic square
- while count <= num:
- if i == -1 and j == n: # condition 4
- j = n - 2
- i = 0
- else:
- if j == n: # column value is exceeding
- j = 0
- if i < 0: # row is becoming -1
- i = n - 1
- # Check if cell is occupied
- if magicSquare[i][j] != 0:
- j = j - 2
- i = i + 1
- continue
- else:
- magicSquare[i][j] = count
- count += 1
- # Move to the next cell
- i = i - 1
- j = j + 1 # condition 1
- # Calculate the sum of each row, column, and diagonal
- row_sums = [sum(row) for row in magicSquare]
- col_sums = [sum(col) for col in zip(*magicSquare)]
- diagonal_sum_1 = sum(magicSquare[i][i] for i in range(n))
- diagonal_sum_2 = sum(magicSquare[i][n - i - 1] for i in range(n))
- return f"The magic square {n}x{n} sum of each row/column/diagonal is: {sum(row_sums)}\n"
- if __name__ == "__main__":
- """
- Main function to execute the script.
- """
- print(" :: MAGIC SQUARES GENERATOR ::\n")
- print("\t:: Options Menu :")
- print(" ___________________________\n")
- print(" Option 1: 3x3 - 9x9")
- print(" Option 2: 11x11 - 31x31")
- print(" Option 3: 33x33 - 99x99")
- print(" Option 4: 101x101 - 315x315")
- print(" Option 5: 317x317 - 999x999") # This Option Will Take Some Time
- print(" Option 6: !SHOW ALL RANGES!") # This Option Will Take Alot Of Time
- print(" ___________________________")
- option = int(input("\n Enter the option number: "))
- output_data = ""
- start_range = 0
- end_range = 0
- if option == 1:
- start_range = 3
- end_range = 9
- elif option == 2:
- start_range = 11
- end_range = 31
- elif option == 3:
- start_range = 33
- end_range = 99
- elif option == 4:
- start_range = 101
- end_range = 315
- elif option == 5:
- print(
- "\n\tThis Option Will Take Some Time...\n\tThank You For Your Patience!\n"
- )
- start_range = 317
- end_range = 999
- elif option == 6:
- print(
- "\n\tThis Option Will Take Alot Of Time...\n\tThank You For Your Patience!\n"
- )
- start_range = 3
- end_range = 999
- else:
- print("\nInvalid option selected!\n")
- for n in range(start_range, end_range + 1, 2):
- output_data += magic_square(n)
- print(output_data)
- # Save the output sums of the given ranges to a dynamically named file in the curent working directory
- save_file = input(
- "\nDo you want to save the output to a file?\n\n1: Yes\n2: No\n\nMake your selection (1 or 2): "
- )
- if save_file == "1":
- file_name = (
- f"magic_square_{start_range}x{start_range}_to_{end_range}x{end_range}.txt"
- )
- with open(file_name, "w") as file:
- file.write(output_data)
- print(f"Output saved to {file_name} in the current directory!\n")
- elif save_file == "2":
- print("\nOutput not saved!\n")
- else:
- print("\nInvalid input. Output not saved!\n")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement