mercredi 28 octobre 2020

how to reduce run tiime for a simple if-else-while program

i had just started learning python,so i was practising some code at codechef one of the problem i was trying was https://www.codechef.com/problems/CHEFEZQ

"Chef published a blog post, and is now receiving many queries about it. On day i, he receives Qi queries. But Chef can answer at most k queries in a single day.

Chef always answers the maximum number of questions that he can on any given day (note however that this cannot be more than k). The remaining questions (if any) will be carried over to the next day.

Fortunately, after n days, the queries have stopped. Chef would like to know the first day during which he has some free time, i.e. the first day when he answered less than k questions.

Input: First line will contain T, the number of testcases. Then the testcases follow. The first line of each testcase contains two space separated integers n and k. The second line of each testcase contains n space separated integers, namely Q1,Q2,...Qn. Output: For each testcase, output in a single line the first day during which chef answers less than k questions.

Constraints 1≤T≤105 1≤ sum of n over all testcases ≤105 1≤k≤108 0≤Qi≤108"

so i wrote my code like this:

i=0

while (i<T):
    nk=input()
    q=[int(a) for a in input().split(" ")]
    n_k=nk.split(" ")
    n=int(n_k[0])
    k=int(n_k[1])
    j=0
    l=0
    while j<n:
        l=l+q[j]-k
        if l<0:
            print(j+1)
            break
        j+=1
    while j>=n:
        l=l-k
        if l<0:
            print(j+1)
            break
        j+=1
    i+=1

the total time limit is 1sec but my code takes 5 sec i dont find any method to reduce time,can someone pls help me out thank you in advance

Aucun commentaire:

Enregistrer un commentaire