1

I wrote a code to output the number of times the letter 'a' is repeated within a given length of a list, it works perfectly with an input of the length less than 1000000 but there is no output with a length larger than 1000000. I would really appreciate the help.

Code:

n = int(input("Length: "))
s = list(input("String: "))
a = s
for i in s:
    if len(a) < n:
        a.append(i)
print(a.count("a"))
print(a)

For an example if the inputs such as below are given the code won't be executed

Length: 100000000000000
String: abcasc

I also noticed that my computer freezes when another app is opened/running while this program is running.

Reblochon Masque
  • 35,405
  • 10
  • 55
  • 80
Tharu
  • 188
  • 2
  • 14
  • 1
    Are you using 32-bit or 64-bit computer/python? – Tamir Nov 16 '20 at 14:27
  • 2
    `100_000_000_000_000 / (1024 ** 4)` gives a value around `90`. Even if we assume that one character needs only one byte you need 90TB of memory just for the string alone. Whatever you're trying to do, I suggest an other approach. – Matthias Nov 16 '20 at 14:41
  • 2
    A couple of things about your code. First, you declare a = s and then you execute ```for i in s ``` within this loop you are appending i to a. But since a=s you are extending the length of s. This means your for loop is executing 100000000000000 times. After leaving the for loop you execute ```a.count('a)```, which essentially performs another 100000000000000 operations. So even running a computer capable of 10 megaflops your problem would take a couple of centuries to execute. I don't think ii isn't running, I think you won't live long enough to see it complete – itprorh66 Nov 16 '20 at 14:57

1 Answers1

6

100,000,000,000,000 is a large input... Larger (much larger) than most computers have in available RAM.

Quoting @Matthias in the comments:

100_000_000_000_000 / (1024 ** 4) gives a value around 90. Even if we assume that one character needs only one byte you need 90TB of memory just for the string alone.

Quoting @itprorh66 comment:

...I think you won't live long enough to see it complete

Quoting @RaymondHettinger:

There has to be a better way!

...and there is:

You can solve this problem by calculating how many times the string repeats in the given length times the number of a in it, and add the number of times a appears in the remaining length at the end.

length = 100000000000000
string = 'abcasc'
a_s = sum(1 for c in string if c == 'a') 
repeats = length // len(string)
mod = length % len(string)
res = repeats * a_s + sum(1 for c in string[:mod] if c == 'a')
res

output:

33333333333334

You can also make it a one liner, to complete the exercise in futility:

res = sum(1 for c in string if c == 'a') * (length // len(string)) + sum(1 for c in string[:length % len(string)] if c == 'a')
Reblochon Masque
  • 35,405
  • 10
  • 55
  • 80