▼ Question
--list gives a string of arbitrary length (s) --Gives the number of characters. (n) --Calculate the number of a contained in repeating s until the number of characters (n) is satisfied.
▼sample input
python
s ="aba"
n =10
▼sample output
python
7
image
abaabaabaa <-7 a
▼my answer
python
def repeatedString(s, n):
a = s.count("a")
ans=i=0
#Find the number of a contained in the surplus characters
r = n%len(s)
if r!=0:
while i<r:
if s[i]=="a":
ans += 1
i+=1
ans += a*int(n/len(s))
return ans
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
s = input()
n = int(input())
result = repeatedString(s, n)
fptr.write(str(result) + '\n')
fptr.close()
--For to extract elements from a fixed object --While to repeat until the specified condition is met
Replace while with for
def repeatedString(s, n):
a = s.count("a")
ans=0
#Find the number of iterations(math.do not use floor)
r = n%len(s)
if r!=0:
for i in range(r):
if s[i]=="a":
ans += 1
ans += a*int(n/len(s))
return ans
repeatedString(s, n)
▼ Processing
--Extract the element from the surplus character number sentence list s, and create a list that stores 1 for a and 0 for other cases. --Add 1 with sum (list).
Comprehension notation
def repeatedString(s, n):
a = s.count("a")
ans=0
#Find the number of iterations(math.do not use floor)
r = n%len(s)
if r!=0:
ans = sum([(1 if s[i]=="a" else 0) for i in range(r)])
ans += a*int(n/len(s))
return ans
repeatedString(s, n)
I created a repeated character string for the specified number of characters and counted the number of a from it, but when the number is large, a Memory Error occurs.
python
s ="babbaabbabaababaaabbbbbbbababbbabbbababaabbbbaaaaabbaababaaabaabbabababaabaabbbababaabbabbbababbaabb"
n = 860622337747
▼ The process of finding a character string is heavy.
python
def repeatedString(s, n):
#Advance (math).floor is not used)
if float(n/len(s)):
r = int(n/len(s)) +1
else:
r = n/len(s)
#Ask for a string
ans = x = 0
ss = s*r
for letter in ss:
x += 1
if x>n:
break
elif letter == "a":
ans += 1
return ans
repeatedString(s, n)
#MemoryError:
Recommended Posts