Python HackerRank Bonetrousle代码超时

时间:2016-09-16 00:22:55

标签: python algorithm

我一直在使用python处理黑客级别的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])

1 个答案:

答案 0 :(得分: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。它为我传递了所有测试用例。