python - Code takes a lot of time to run for large numbers
问题描述
Given the number of squares in a board (e.g. scrabble or chess board), N and dimensions AxB, this code tries to determine all possible dimensional combinations that can give N number of squares in the board.
Example: N = 8
There are four possible dimensional combinations to obtain exactly 8 squares in the board. So, the code outputs board dimensions 1x8 2x3, 3x2 and 8x1. The 8x1 boards have eight 1x1 squares; the 3x2 boards have six 1x1 squares and two 2x2 squares.
Here is my solution:
def dims(num_sqrs):
dim_list=[]
for i in range(1,num_sqrs+1):
temp = []
for x in range(1,num_sqrs+1):
res = 0
a = i
b = x
while (a != 0) and (b !=0):
res = res + (a*b)
a = a -1
b = b-1
if res == num_sqrs:
dim_list.append((i,x))
print(dim_list)
dims(8)
However, this code takes too much time to run for large values of N. Any suggestion to optimize the efficiency of the code will be much appreciated.
解决方案
我认为关键细节是@Qudus 正在寻找有 N 个任意大小的正方形的板。
一种简单的优化是在res > n
. 另一个使它快两倍的优化是只在长度>=宽度的板上运行它。
def dims(num_sqrs):
dim_list=[]
for i in range(1, num_sqrs + 1):
temp = []
for x in range(1, i + 1):
res = 0
a = i
b = x
while (a != 0) and (b != 0):
res = res + (a * b)
a = a - 1
b = b - 1
if res > num_sqrs:
break
if res == num_sqrs:
dim_list.append((i, x))
if i != x:
dim_list.append((x, i))
print(dim_list)
这是一个更快的解决方案,它采用不同的方法:
def dims(num_sqrs):
dim_list = []
sum_squares = [0]
sums = [0]
for i in range(1, num_sqrs + 1):
sums.append(sums[-1] + i)
sum_squares.append(sum_squares[-1] + i * i)
for i in range(1, num_sqrs + 1):
if sum_squares[i] > num_sqrs:
break
if sum_squares[i] == num_sqrs:
dim_list.append((i, i))
break
for x in range(i + 1, num_sqrs + 1):
total_squares = sum_squares[i] + sums[i] * (x - i)
if total_squares == num_sqrs:
dim_list.append((x, i))
dim_list.append((i, x))
break
if total_squares > num_sqrs:
break
return dim_list
推荐阅读
- sql - Postgres 查询显示可为空的字段
- php - 如何使用 cURL 或 PHP 获取 cookie 特定值
- javascript - Select2 删除选项在 jquery 中不起作用
- c++ - Embarcadero C++ builder 10.4.2-附加到进程在 64 位上不起作用
- android - 如何在顶部构建具有比例的自定义搜索栏
- javascript - Gatsby GraphQL 一次下载多个图像
- android - 如何在 RXjava - Android 中为完整的观察者设置 TimeOut?
- html - 尝试查找 URL 的创建日期
- javascript - 在 vue 中打印发票(账单)只是文本
- amazon-web-services - AWS STS 在 docker 容器中承担角色“无法找到凭证”