Can anyone tell me the problem with this code?
Yes, I say the code is all wrong. For the following reasons:
- The approach is too complicated for a simple problem.
- It doesn’t even solve your initial problem of building a string based on another to count the characters
a
repeated.
- Is difficult to interpret.
- Even if the code was fixed the algorithm would have performance.
If you have a string s
and wants to repeat it until n
the best approach is to divide the length of s
for n
to know how many times s
shall be repeated and with the rest of the division take a fraction of s
which will complete the missing characters. Python offers the built-in function divmode()
that in an operation returns the quotient and the rest of a division:
>>>s = 'abc'
>>>n = 10
>>>dm = divmod(n, len(s))
>>>print(s * dm[0] + s[:dm[1]])
abcabcabca
Test the code on Ideone
Where:
s * dm[0]
is the string s
repeated by the quotient dm[0]
.
s[:dm[1]]
is the fraction of the string s
determined by the rest dm[1]
.
So, or you can count how many times the character a
is repeated in the resulting string with the help of the method str.count()
:
>>>s = 'abc'
>>>n = 10
>>>dm = divmod(n, len(s))
>>>res = s * dm[0] + s[:dm[1]]
>>>print(res.count("a"))
4
Test the code on Ideone
This solution has the disadvantage of memory consumption in the case of n
be very big, example n = 1000000000
, with multilinear time complexity O(Len(s)*n).
If you want performance, instead of counting how many times the character a
repeats in the resulting string you can count once how many times the letter a
appears in the string s
multiply by the quotient and count again how many times the letter a
fraction of the string appears s
:
>>>s = 'abc'
>>>n = 10
>>>dm = divmod(n, len(s))
>>>c1 = s.count("a") * dm[0]
>>>c2 = s[:dm[1]].count("a")
>>>print(c1 + c2)
4
Test the code on Ideone
This solution already has constant time complexity O(1) and works well with absurd values to n
and s
.
Packaging the solution as a function:
def repeatedString(s, n):
dm = divmod(n, len(s))
c1 = s.count("a") * dm[0]
c2 = s[:dm[1]].count("a")
return c1 + c2
print(repeatedString('abc',11234567890987654321)) #3744855963662551441
Test the code on Ideone
while i in (len(s), n-len(s))
, can explain to us what you hoped that expression would do?– Woss
yes, I expected her to mark an interval that started after the last letter of s until reaching n to add the right amount of letters
– Yasmin Teixeira