繁体   English   中英

超出时间限制错误 - 当我尝试运行 Python 3 代码时

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

  • 当我运行此代码时,开始在 HackerRank 上学习 Python 3 我收到此错误:

超出时间限制 您的代码未在时间限制内执行。 请优化您的代码。 有关执行时间限制的更多信息,请参阅环境页面

这是 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()

尽管++i在语法上是有效的,但它并没有做人们期望它做的事情,它来自一种类似 C 的语言。 在 Python 中, ++i只是一元+应用于i两次( +(+i) ),无需更改。 Python 增加变量的方法是i+=1

您正在从 0 到 n 运行 while 循环,n 的最大值为 10^12。 在最坏的情况下,while 循环运行 10^12 次。 这就是为什么时间超过了。 尝试优化代码。

试试这个代码

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 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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