python 3 代码在一些测试用例中的运行时错误
runtime error for python 3 code in a few test cases
我是 Python 的新手,我正在尝试完成这个挑战:
https://www.hackerrank.com/challenges/repeated-string/problem?h_r=internal-search
我不知道为什么在提交代码时会出现运行时错误。
这是我的代码:
s = input("Type a string: ")
n = int(input("Enter the number of repetition: "))
sf = ' '
repeat = n // len(s)
remain = n % len(s)
i = 0
j = 0
if s == 'a':
count = n
else:
while i < repeat:
sf += s
i += 1
while j < remain:
sf += s[j]
j += 1
count = sf.count('a')
print(count)
任何提示或解决方案将不胜感激!
注意: 当您打开 link 时,它会要求您注册或登录。您可以简单地忽略它,然后它会查看挑战。
当测试规模变得非常大时,问题就会出现。字符串 sf 会变得很大,你会得到一个内存错误。问题的挑战性部分是弄清楚如何在不创建长字符串的情况下解决它。
您对剩余部分的处理方法很好。也许找到一个序列中有多少 'a' ,然后将其乘以重复次数?然后你只需要处理剩余部分。您需要计算出字符串的前 'remainder' 个字符中有多少个 'a'。
我是 Python 的新手,我正在尝试完成这个挑战: https://www.hackerrank.com/challenges/repeated-string/problem?h_r=internal-search 我不知道为什么在提交代码时会出现运行时错误。 这是我的代码:
s = input("Type a string: ")
n = int(input("Enter the number of repetition: "))
sf = ' '
repeat = n // len(s)
remain = n % len(s)
i = 0
j = 0
if s == 'a':
count = n
else:
while i < repeat:
sf += s
i += 1
while j < remain:
sf += s[j]
j += 1
count = sf.count('a')
print(count)
任何提示或解决方案将不胜感激!
注意: 当您打开 link 时,它会要求您注册或登录。您可以简单地忽略它,然后它会查看挑战。
当测试规模变得非常大时,问题就会出现。字符串 sf 会变得很大,你会得到一个内存错误。问题的挑战性部分是弄清楚如何在不创建长字符串的情况下解决它。
您对剩余部分的处理方法很好。也许找到一个序列中有多少 'a' ,然后将其乘以重复次数?然后你只需要处理剩余部分。您需要计算出字符串的前 'remainder' 个字符中有多少个 'a'。