I am trying to answer the makeBricks codingbat
problem link.
I couldn't figure out any alternative, but came up with the following brute-force algorithm to solve the problem. I attempt every possible calculation to equal the goal.
I am able to get the code to run in Jupyter notebook
(anaconda python3
, but not in the codingbat
website, which gives a timed out
error. Can anyone explain to me why?
def make_bricks(small, big, goal):
# make a list of all the big and small bricks
small_list=[]
for i in range(small):
small_list.append(1)
#print(small_list)
big_list=[]
for i in range(big):
big_list.append(5)
#print(big_list)
#print(goal)
target = goal
# first see if the difference between the goal and a big brick is ==0,
# if not, start removing one small brick at a time to get to goal. if not reached
# then take off another big brick and check again, then go and take off one
# by one the small bricks and so on, if by the end you dont reach ==0 it means it is False.
for i in range(len(big_list)):
target =target - big_list[i]
#print(f'i is {i}, target is {target}')
if target ==0:
return True
for k in range(len(small_list)):
target=target-small_list[k]
#print(f'k is {k}, target is {target}')
if target ==0:
return True
else:
target= goal-big_list[i]
#print(f'target is {target}')
#print(target)
#print("done")
if target !=0:
return False
答案 0 :(得分:0)
所以我在Codingbat make_bricks timed out with while loop in python
上找到了另一个人的问题的答案基本上,暴力破解方法会使以下一项或两项测试使网站崩溃:
make_bricks(1000000,1000,1000100)→ make_bricks(2,1000000,100003)→
它们太大了,codingbat会为所有问题给出“超时”错误。
Jupyter笔记本一直在工作,但我没有耐心看它是否成功:-)