[英]Finding how many times a certain character appears in a multiplied string
We want to find the number of 'a's in a given string s
multiplied infinite times.我们想找到给定字符串s
中的 'a' 的数量无限次相乘。 We will be given a number n
that is the slicing size of the infinite string.我们将得到一个数字n
,它是无限字符串的切片大小。
sample input:样本输入:
aba 10
output: output:
7
Here aba
is multiplied with 10, resulting in 'abaabaabaa' and the no.这里aba
乘以 10,得到 'abaabaabaa' 和 no。 of 'a's are 7. This is my code: 'a's 是 7。这是我的代码:
def repeatedString(s, n):
count = 0
inters = s * n
reals = s[0:n+1]
for i in reals:
if (i == 'a'):
count += 1
return count
I'm getting 2 instead of 7 as the output (test case 'aba' 10).我得到 2 而不是 7 作为 output (测试用例 'aba' 10)。 Where did I go wrong?我在哪里 go 错了? I just multiplied the given string with n
because it will never be greater than the slicing size.我只是将给定的字符串与n
相乘,因为它永远不会大于切片大小。
Here's the link to the problem: https://www.hackerrank.com/challenges/repeated-string/problem这是问题的链接: https://www.hackerrank.com/challenges/repeated-string/problem
Much simpler solution using python3.使用 python3 更简单的解决方案。
s = input().strip()
n = int(input())
print(s[:n%len(s)].count('a')+(s.count('a')*(n//len(s))))
There's no reason to slice the string没有理由对字符串进行切片
def repeatedString(s, n):
count = 0
for index, i in enumerate(s*n):
if index >= n:
return count
if(i == 'a'):
count += 1
# empty string
return count
If you would like a more readable answer....如果您想要一个更具可读性的答案......
def repeatedString(s, n):
target = 'a'
target_count = 0
# how many times does the string need to be repeated: (n // len(s) * s) + s[:(n % len(s))]
quotient = n // len(s)
remainder = n % len(s)
for char in s: # how many times target appears in 1 instance of the substring
if char == target:
target_count += 1
# how many times the target appears in many instances of the substring provided
target_count = target_count * quotient
for char in s[:remainder]: # count the remaining targets in the truncated substring
if char == target:
target_count += 1
return target_count
so if the string contains "a"s only simply return n.因此,如果字符串包含“a”,则只需简单地返回 n。 otherwise, count the number of a's in the string s, now using divmond() function I have found the number of string that can be added without surpassing n.否则,计算字符串 s 中 a 的数量,现在使用 divmond() function 我找到了可以添加的字符串数量不超过 n。 for example string s is "aba" and n=10, so I can add 3 "abs"s completely without the length of string going over 10. now the number of a's in the added string (3*2).例如字符串 s 是“aba”并且 n=10,所以我可以完全添加 3 个“abs”,而字符串的长度不会超过 10。现在添加的字符串中的 a 的数量(3 * 2)。 Now the places left to be filled are equal to the remainder(y) of divmond() function.现在剩下要填充的位置等于 divmond() function 的余数(y)。 Now slice the string s up to y and find the number of a's in it and add it to count.现在将字符串 s 切成 y 并找到其中 a 的数量并将其添加到计数中。
divmond(10,3) returns (10//3) and it's remainder. divmond(10,3) 返回 (10//3) 并且是余数。
def repeatedString(s, n):
if len(s)==1 and s=="a":
return n
count=s.count("a")
x,y=divmod(n,len(s))
count=count*x
str=s[:y]
return count+str.count("a")
The solution in Python 3: Python 3中的解决方案:
def repeatedString(s,n):
i = 0
c = 0
for i in s:
if i == 'a':
c += 1
q = int(n / len(s)) #Finding the quotient
r = int(n % len(s)) #Finding the remainder
if r == 0:
c *= q
else:
x = 0
for i in range(r):
if s[i] == 'a':
x += 1
c = c*q + x
return int(c)
s = input()
n = int(input())
print(repeatedString(s,n))
I used a simple unitary method.我使用了一个简单的单一方法。 Number of 'a' in one repetition is cnt_a
so the number of 'a' in first n
characters will be (cnt_a/len(s)) * n
一次重复中的“a”数为cnt_a
,因此前n
字符中的“a”数将为(cnt_a/len(s)) * n
def repeatedString(s, n):
if len(s)==1 and s=='a':
return n
cnt_a=0
for i in s:
if i == 'a':
cnt_a+=1
if cnt_a % 2 == 0:
no_a = (cnt_a/len(s)) * n
return math.ceil(no_a)
else:
no_a = (cnt_a/len(s)) * n
return math.floor(no_a)
def repeatedString(s, n): # Get the length of input string strlen = len(s) a_repeat = 0 # Get the total count of a repeated character from the input string for i in range(0,strlen): if s[i] == 'a': a_repeat = a_repeat + 1 # Get the multiplier to make sure that desired input string length achieved str_multiplier = int(n // strlen) # Get the repeated count if new string is been created result = a_repeat*str_multiplier new_str = s[:int( n % strlen )] # for odd length of string, get the remaining characters and find repated characters count and add up it to final count for i in range(0, len(new_str)): if new_str[i] == 'a': result += 1 return result
One liner answer:一个班轮回答:
return [s[i%len(s)] for i in range(n)].count('a')
There is only two problem in your code您的代码中只有两个问题
s = 'aba'
n = 10
count = 0
inters = s * n
# Here you need to slice(inters) not (s) because s only hold 'aba'
# And not n+1 it's take 11 values only n
reals = inters[0:n]
for i in reals:
if (i == 'a'):
count += 1
print(count)
For this problem, Get the length of string s.对于这个问题,获取字符串 s 的长度。 First, if conditions: constrain一、if条件:约束
Now, instead of using a loop to add to space and time complexity, we use basic math's.现在,我们不使用循环来增加空间和时间复杂度,而是使用基本数学。 Find the quotient of n//Len (s).求 n//Len (s) 的商。 Now find the number of times "a" is used in our string.现在找到我们的字符串中使用“a”的次数。
We can multiply the quotient with this number to get the total "a" used.我们可以将商乘以这个数字,得到使用的总“a”。 Now, we can find the remainder of the string and use slice to search for "a" in the string we have left in the last.现在,我们可以找到字符串的剩余部分,并使用 slice 在我们最后留下的字符串中搜索“a”。
Add both to get our answer.添加两者以获得我们的答案。
def repeatedString(s, n):
#finding quotient and remainder of division
str1=len(s)
remainder=0
if 1<=str1<=100 and 1<=n<=10**12:
quotient= n//str1
a_s = s.count("a")
if a_s==0:
return 0
else:
remainder=s[:n%str1].count('a')
return quotient*a_s + remainder
Simple answer:简单的回答:
def repeatedString(s, n):
totalNumber = 0 // setting total of a's to 0
// using count function to find the total number of a's in the substring
totalNumber = s.count('a')
// finding how many number of times the substring fits in "n" and multiplying that by the number of a's we found earlier
totalNumber = n//len(s) * totalNumber
// if there is a remainder, we loop through the remainder string and add the number of "a's" found in that substring to the total
for i in s[:n%len(s)]:
if(i == "a"):
totalNumber +=1
return totalNumber
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.