Search code examples
python-3.xoptimizationmathematical-optimization

Optimize the code to run in less than 5 second


In some test cases on HackerEarth following code takes more than 5 second (5.001). How can this code be even more optimized to run in less than 5 seconds?

tc = int(input())
ip = []
for x in range(0, tc):
    temp = []
    temp.append(int(input()))
    temp.append([int(n) for n in input().split()])
    temp.append(int(input()))
    ip.append(temp)

for it in ip:
    while not it[2] <= 0:
        for x in range(0, it[0]):
            if it[1][x] == '0':
                continue
            it[2] -= int(it[1][x])
            if it[2] <= 0:
                it.append(x+1)
                break
    print(it[3])

Just for reference:

Problem Statement

Aniruddha is given a milestone M to reach in terms of distance. He is living in a different Galaxy where there are N days in a year.At the ith day he can walk atmost X distance.Assuming he walks optimally you need to output the minimum day number on which he will reach the milestone.

Input

The first input line contains the T number of testcases. Each testcase consist of three lines First line consist of single integer N — the number of days in a year.

Next line contains N non-negative space-separated numbers— i.e. distance which Aniruddha will walk on ith day. It is guaranteed that at least one of those numbers is greater than zero.

And the third line consist of the value of milestone which Aniruddha has to reach.

Output

For each testcase you need to output the answer to the following query.

Constraints

1<=T<= 10

1<=N<=10^5

0<=X<=10^8

0<=M<=10^16

Solution

  • Thanks to J. Hollom, I have made some changes and ported the code into Python 3.x. Kindly note my code is designed for Hacker Earth (link given by J. Hollom) and thus it expects input!

    test_cases = int(input())
    inputs = []
    for x in range(test_cases):
        temp = []
        temp.append(int(input()))
        temp.append([int(n) for n in input().split()])
        temp.append(int(input()))
        temp.append(sum(temp[1]))
        inputs.append(temp)
    
    
    for item in inputs:
        item[2] = item[2] % item[3]
        if item[2] == 0:
            item[2] += item[3]
        day = 0
        while item[2] > 0:
            item[2] -= item[1][day]
            day += 1 # Since day begins at Day 1 this will give right answer!
        print(day)
    

    Well, now all inputs run in less than 1 seconds!