问题描述
输入是要布局的像元数,例如X = 6。 我需要将它们布置成正方形(或尽可能接近正方形的矩形)。 对于X = 6,矩形的宽度为3列,高度为2行。
对于具有整数根(例如4和9)的X-es,这很容易。列和行的数目只是X的平方。要获得其他情况下的行和列的数学是什么?
解决方法
import numpy as np
def squarish(x):
"""returns rows and cols of a rectangle of x cells that best approximates a square"""
# TODO add an isprime check and handle it as you want
sqrt = np.sqrt(x)
if int(sqrt) == sqrt:
return int(sqrt),int(sqrt)
rows = int(sqrt)
while rows > 1:
cols = x / rows
if int(cols) == cols:
return rows,int(cols)
else:
rows -= 1