python - 超出时间限制错误 - 当我尝试运行 Python 3 代码时
问题描述
- 当我运行此代码时开始在 HackerRank 上学习 Python 3 时出现此错误:
超出时间限制 您的代码未在时间限制内执行。请优化您的代码。有关执行时间限制的更多信息,请参阅环境页面
这是 Hackerrank 上问题的链接。
#!/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()
解决方案
您正在从 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
推荐阅读
- java - 我不明白私有访问修饰符的使用
- memory - 如何检查 x86 PTE 在 Linux 中是否有效?
- django - django (DRF) 的 update_or_create 中的使用条件
- vespa - 没有会话 id,如何找到应用程序的内容 url。我只知道应用程序名称
- java - 在 RestTemplate 代码中得到 400 Request Bad Error 但在 SOAPUI 中得到正确的响应
- python - 如何将时间序列转换为从 00:00.00 开始的 %M:%S.%f
- java - MuteSetup 命令未设置有效的静音命令
- flutter - Dart @macro 在评论中
- node.js - Typegoose 类定义的静态方法返回空数组
- mysql - 是否有替代 ALTER TABLE AUTO_INCREMENT = 1 的方法?