We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
With Python, a brute force way to generate all magic squares is to generate all possible permutations of 1 to 9 with itertools.permutations then check each created list to see if the sums of all rows, columns and diagonals are equal. I added the sums to a set then checked if the length of the set was 1 to determine if it was a magic square.
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Forming a Magic Square
You are viewing a single comment's thread. Return to all comments →
With Python, a brute force way to generate all magic squares is to generate all possible permutations of 1 to 9 with itertools.permutations then check each created list to see if the sums of all rows, columns and diagonals are equal. I added the sums to a set then checked if the length of the set was 1 to determine if it was a magic square.