math - 找到 2 个彼此尽可能接近的数字,当相乘时给出整数 X
问题描述
输入是要布局的单元格数,例如 X = 6。我需要将它们布局为正方形(或尽可能接近正方形的矩形)。对于 X = 6,矩形将是 3 列宽和 2 行高。
对于具有整数根的 X-es,例如 4 和 9,这很容易。列数和行数只是 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
推荐阅读
- sql - 为什么我不能将数据从 CSV 文件导入到表中?
- postgresql - Flask 从 flask_sqlalchemy 查询返回 '(Decimal('0.82483097725875845114'),),'。如何清理?
- python - Python pandas cumsum 在另一列中按值重置
- python - Python:在深度嵌套的字典或数组中转换类型
- java - 在单独的 JVM 上执行新的 JavaFX 应用程序
- python - 散景仅绘制网络抓取数据中的特定列
- python - 如何获取字符串的每个组合?
- r - 如何根据R中的类别将长格式转换为宽格式
- c++ - 使用 Qt 树模型存储数据?
- multithreading - 信号量小书中的无饥饿互斥锁