In doing string_repetida = s * n_repetidos
you are creating a string with 1 trillion characters (that is, if each character occupies 1 byte, you will need 1 terabyte for this string, so it gives error in your test as it is bursting the memory).
But anyway, you don’t have to build a giant string and then count.
An alternative to the another answer is to use the module itertools
:
from itertools import islice, cycle
def repeatedString(s, n):
qtd = 0
for letra in islice(cycle(s), n):
if letra == "a":
qtd += 1
return qtd
print(repeatedString('aba', 10)) # 7
print(repeatedString('baa', 10)) # 6
First, cycle(s)
creates an iterator that iterates repeatedly through the string. As it creates an infinite iterator, I use islice
to limit it to only the first n
elements.
Then, just count how many are equal to "a" and return the result.
Only this solution is more inefficient than the other answer, especially if the n
is very large (since it needs to iterate through the loop n
times, while the other answer only does a few simple calculations and iterates through the string only to do the count
).
Another alternative is instead to use count
2 times (once in the whole string and once in the substring), make a single loop that counts everything at once:
def repeatedString(s, n):
repetiu, sobrou = divmod(n, len(s))
qtd = 0
for i, c in enumerate(s):
if c == 'a':
qtd += repetiu
if i < sobrou:
qtd += 1
return qtd
The idea is similar to the other answer: we see how many times the string will be repeated completely, and how much more to complete the size n
.
Then we iterate through her characters and indexes at the same time (using enumerate
for this), and each time we find a letter "a", we already add the amount of times the string repeats itself completely. Then we see if you still need to add one more, if we are in a position that is used for the "leftover".