简体   繁体   中英

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. We will be given a number n that is the slicing size of the infinite string.

sample input:
aba 10

output:
7

Here aba is multiplied with 10, resulting in 'abaabaabaa' and the no. of 'a's are 7. This is my code:

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). Where did I go wrong? I just multiplied the given string with n because it will never be greater than the slicing size.

Here's the link to the problem: https://www.hackerrank.com/challenges/repeated-string/problem

Much simpler solution using 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. 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. 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). Now the places left to be filled are equal to the remainder(y) of divmond() function. Now slice the string s up to y and find the number of a's in it and add it to count.

divmond(10,3) returns (10//3) and it's remainder.

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:

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

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)
if character 'a' is present in a given string pattern, then its quite faster to get the repeated count for it and later based on the total length of final string mentioned, will be trying to repeat the given pattern for same number of times & hence will multiple the repeated count with number of times a string pattern is going to repeat. Importantly if final string input is in odd numbers then we need to identify the those odd pattern and separately count the occurance of character 'a' in odd string pattern. Finally summing up the total count ( even & odd ) will gives us the expected result
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. First, if conditions: constrain

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). Now find the number of times "a" is used in our string.

We can multiply the quotient with this number to get the total "a" used. 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM