3
我一直在使用python研究黑客等級中的Bonetrousle問題。幾個小時後,下面的代碼通過了所有測試用例,除了超時之外的所有測試用例。任何關於如何使代碼更快的建議,將不勝感激。我相信問題是處理剩餘的代碼,我在下面和上面放置註釋,以便很容易找到。不幸的是,我對如何重構它感到茫然,所以它工作得更快。Python HackerRank Bonetrousle代碼超時
我寫的代碼得到了所有測試用例的正確答案,我已經在pycharm中驗證了這一點。唯一的問題是,它會減慢一個黑客等級測試案例。
這裏是鏈接的問題https://www.hackerrank.com/challenges/bonetrousle
firstLine = int(input())
for a in range(0, firstLine):
nums = input()
numsArr = list(map(int, nums.split(" ")))
n = numsArr[0]
k = numsArr[1]
b = numsArr[2]
num1 = 0
rem = 0
answer = True
remAdded = False
count = 0
boxArr = []
for i in range(1, b+1):
count += i
boxArr.append(i)
num1 = (n - count)//b
rem = (n - count)%b
for j in range(0, len(boxArr)):
boxArr[j] = boxArr[j] + num1
if boxArr[j] > k:
answer = False
# In below code -> if there is a remainder I am adding it to an element in the array that has box numbers
# I check to see if I can add the remainder to an element in the array
#without that element exceeding k, the number of sticks. If I can't then the bool remAdded doesn't get set to True
# The below code works but it seems inefficient and looks like the problem
if rem == 0:
remAdded = True
elif answer != False:
for r in range(len(boxArr) - 1, 0, -1):
if boxArr[r] + rem <= k and r == len(boxArr) - 1:
boxArr[r] = boxArr[r] + rem
remAdded = True
break
else:
if boxArr[r] + rem <= k and (boxArr[r] + rem) not in boxArr:
boxArr[r] = boxArr[r] + rem
remAdded = True
break
# above is code for dealing with remainder. Might be the problem
if answer == False or remAdded == False:
print(-1)
elif 0 in boxArr:
print(-1)
else:
for z in range(0, len(boxArr)):
if z != len(boxArr) - 1:
print(boxArr[z], end =" ")
else:
print(boxArr[z])