为什么我的代码给内存错误?

时间:2018-07-19 23:16:03

标签: python string python-3.x memory

我正在编写一个程序,可以计算字符串中a的数量。这是我的代码:

def repeatedString(s, n):
    converged = s*n
    got_it = converged[0:n]
    count = 0
    for x in got_it:
        if "a" in x:
           count += 1
    return count
s = input()
n = int(input())
result = repeatedString(s, n)
print(result)

变量s是输入字符串的位置,变量n的使用期限为字符串重复的时间。我的代码可以正常运行,但是由于某些原因,当我给出一个更大的整数时,它会崩溃并给我Memory Error。例如,我的输入是:

a
1000000000000

它给了我这个错误:

Traceback (most recent call last):
  File "programs.py", line 11, in <module>
    result = repeatedString(s, n)
  File "programs.py", line 2, in repeatedString
    converged = s*n
MemoryError

如何解决此内存错误?如果有更好的方法,这也将有所帮助。

4 个答案:

答案 0 :(得分:2)

您的代码存在问题,您可以在此处converged = s*n进行操作。在那一行中,您要求程序采用字符串s并分配足够的内存以适合s * n中的字节数,如您所见,它具有一个限制,因为您的计算机具有有限的可用内存量(大多数现代计算机仅承载4-16 GB的RAM)。

解决内存错误的一种方法是利用函数的一个方面-您只需检查一个字符串"a"中有多少s个合适的字符串,重复长度为{{ 1}}。因此,您无需执行n和随后的修改而需要大量内存来存储如此大的字符串,而是可以使用简单的数学运算来获取所需的答案。

此外,您可以做的另一种优化是,您不必将字符串转换为数组就可以对其进行循环。除了执行converged = s*n,您还可以执行for x in got_it

这是一个如何完成所需内容的有效示例:

for c in s

答案 1 :(得分:0)

感谢所有帮助人员,我设法通过使用tryexcept MemoryError处理异常来解决了问题

答案 2 :(得分:0)

this program
  takes a input string named s
  repeats this string concatenated n times
  takes only the first n charactes in the concatenated
  counts how many times the letter "a" appears 


you
  you give the string "a"
  you give the number 1000000000000
  then the program should count and return 1000000000000


memmory problem
  I guess this string with 1000000000000 letters "a" is too big 
    for the type in the python language
    or for the computer memmory


the way it is
  given that the program searches for the fixed occurrences of letter "a"
  you passed exactly the letter "a" and the number 1000000000000
  the better way is that it's not necessary a program
  if you want to know how many times there is the letter "a" 
    in a string with 1000000000000 letters "a"
    the answer is obviously 1000000000000


extra:
  it would be complicated:
    to rewrite the program 
      to search for a pattern 
        given as input parameter, 
        with variable length
    AND
      avoid the memmory problem


  I guess I would write a program that 
    concatenates the "s" input just to have a length bigger than the searched pattern (if already not is)
    check if the pattern occurs

    after that multiply by "n"
    ajust the how many times it will 'fit' in the final

答案 3 :(得分:0)

单行解决方案:在字符串s中找到“ a”的编号,然后将重复编号no的底数乘以s的长度+在s的其余长度中找到“ a”

s.count(“ a”)*(n // len(s))+ s [:n%len(s)]。count(“ a”)