2016-09-16 65 views
3

我一直在使用python研究黑客等級中的Bonetrousle問題。幾個小時後,下面的代碼通過了所有測試用例,除了超時之外的所有測試用例。任何關於如何使代碼更快的建議,將不勝感激。我相信問題是處理剩餘的代碼,我在下面和上面放置註釋,以便很容易找到。不幸的是,我對如何重構它感到茫然,所以它工作得更快。Python HackerRank Bonetrousle代碼超時

我寫的代碼得到了所有測試用例的正確答案,我已經在pycharm中驗證了這一點。唯一的問題是,它會減慢一個黑客等級測試案例。

這裏是鏈接的問題https://www.hackerrank.com/challenges/bonetrousle

這裏是測試用例的鏈接失敗 https://hr-testcases-us-east-1.s3.amazonaws.com/21649/input12.txt?AWSAccessKeyId=AKIAJAMR4KJHHUS76CYQ&Expires=1473987910&Signature=xaHGvYRVmUVJHh4r3on%2BWgoIsjs%3D&response-content-type=text%2Fplain

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]) 

回答

2

通過更換您的意見之間的代碼:

if rem == 0: 
    remAdded = True 
elif boxArr[-1] + 1 > k: 
    remAdded = False 
elif answer != False: 
    l = len(boxArr)-1 
    for r in range(l, l-rem, -1): 
     boxArr[r] += 1 
    remAdded = True 

這基本上擺脫了昂貴的(boxArr[r] + rem) not in boxArr。它通過了我所有的測試案例。