Skip to content

Instantly share code, notes, and snippets.

Created Jan 8, 2022
What would you like to do?
import sys
import numpy as np
from multiprocessing import Pool
import time
def get_value(square):
tot = 0
s = 0
col = 1
row = 1
for i in square:
if i == '\n':
col += 1
s += (int(i) + 1)**(col + row)
if col == (order + 1):
col = 1
row += 1
tot += np.log(s)
s = 0
return square, tot
def build_dict(results):
totals = {}
for result in results:
sq, tot = result
if tot not in totals.values():
totals[sq] = tot
other = None
for t in totals:
if totals[t] == tot:
other = t
return totals
if __name__=='__main__':
if len(sys.argv) < 3:
print("Filename and order are required: python3 <order> <file>")
start = time.time()
order = int(sys.argv[1])
filename = sys.argv[2]
with open(filename) as f:
length = order**2
lines = f.readlines()
totals = {}
processes = 20 # using 20 processes since I'm running this on my server
with Pool(processes) as p: # create the pool
print(f"Determining square values.")
# spawn the processes for each Latin square (lines is a list of strings representing the squares)
results =, lines)
print(f"Aggregating results.")
# determine how to split up the resulting (square, value) pairs [i.e. how many per process]
values_per_list = int(len(results)/processes)
extra = len(results) - (values_per_list*processes)
result_lists = []
# break the list up into smaller lists for each process
for i in range(processes-1):
# give the last process all of the remaining squares
# get all of the dictionaries returned by the build_dict function, this will be a list of dictionaries
union_dicts =, result_lists)
# combine each dictionary into one dictionary, namely 'totals'
for d in union_dicts:
totals = {**totals, **d}
end = time.time()
print(f"# Distinct Totals: {len(totals)}\n# Squares: {len(lines)}\nAll Distinct? {len(totals) == len(lines)}\nMax: {max(totals.values())}\
\nTime Taken: {(end - start):.6f} sec/{((end-start)/60):.6f} min")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment