How to fix Time limit exceeded error

Asked

Viewed 337 times

1

I was trying to solve this issue in URI and I managed to reach the output required by URI. However I got the error Time limit exceeded, because the running time limit is 2s, and my code resulted in 3s. I would like you to help me optimize my code to not exceed this limit.

Question link in URI and enunciation image:

https://www.urionlinejudge.com.br/judge/pt/problems/view/1146

inserir a descrição da imagem aqui

My code:

N = 1
sequencia = ''
while N != 0:

    N = int(input())
    i = 1

    while i <= N:
        sequencia = sequencia + f'{i} '

        i = i + 1
    else:
         sequencia = sequencia[:-1] + '\n'


print(sequencia[:-1])

1 answer

2


Probably what makes your code slow is the creation and concatenation of several strings (not counting the Slices as [:-1], which also generate another string).

A more efficient way is to use join (understand the reasons reading here), along with a range, which already generates the sequence of numbers:

while True:
    n = int(input())
    if n == 0: break
    print(' '.join(map(str, range(1, n + 1))))

Remembering that in a range the final value is not included, so you have to put n + 1. And you need to convert the numbers to string (using map and str), otherwise the join makes a mistake.

Another advantage is that you don’t have to worry about the extra space at the end, because the join already takes care of it too.

I just submitted and the solution was accepted.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.