简体   繁体   中英

Time limit exceeded Error - When I try to run Python 3 code

  • Starting to learn Python 3 on HackerRank when I run this code I get this error:

Time limit exceeded Your code did not execute within the time limits. Please optimize your code. For more information on execution time limits, refer to the environment page

Here is a link to the question on Hackerrank.

https://www.hackerrank.com/challenges/repeated-string/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=warmup

#!/bin/python3

import math
import os
import random
import re
import sys

#
# Complete the 'repeatedString' function below.
#
# The function is expected to return a LONG_INTEGER.
# The function accepts following parameters:
#  1. STRING s
#  2. LONG_INTEGER n
#

def repeatedString(s, n):
    Write your code here
    i = 0
    aCount = 0
    
    while i <= n:
        if 'a' == s[i]:
            aCount += 1
            ++i
        else:
            ++i
            
            print(aCount)
            return aCount 

if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    s = input()

    n = int(input().strip())

    result = repeatedString(s, n)

    fptr.write(str(result) + '\n')

    fptr.close()

Even though ++i is syntactically valid, it doesn't do what one would expect it to do, coming from a C-like language. In Python, ++i is just unary + applied to i twice ( +(+i) ), without changing it. The Python way of incrementing a variable is i+=1 .

You're running the while loop from 0 to n, maximum value for n is 10^12. That while loop is running 10^12 times in worst case. That's why time exceeded. Try to optimize code.

Try this code

def repeatedString(s, n):
    #Write your code here
    aCount = 0
    
    for i in range(len(s)):
        if 'a' == s[i]:
            aCount += 1
    aCount*=(n//len(s))
    x=n%len(s)
    for i in range(x):
        if 'a' == s[i]:
            aCount += 1
            
    return aCount 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM