[Python] Programming to find the number of a in a character string that repeats a specified number of times.

[Python] Programming to find the number of a in a character string that repeats a specified number of times

▼ 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.

URL

▼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


The above while statement can be replaced with "for i in range (r)".

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)

#### Make the if statement into one sentence and rewrite it to the inclusion notation.

▼ 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)

Supplement: MemoryError

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

[Python] Programming to find the number of a in a character string that repeats a specified number of times.
Divides the character string by the specified number of characters. In Ruby and Python.
Find out the apparent width of a string in python
How to quickly count the frequency of appearance of characters from a character string in Python?
[Python] A program to find the number of apples and oranges that can be harvested
Find the number of days in a month
[Python] A program that calculates the number of socks to be paired
[Introduction to Python] Thorough explanation of the character string type used in Python!
Check if the string is a number in python
How to get the number of digits in Python
"A book to train programming skills to fight in the world" Python code answer example --1.1 Duplicate character string
[Python] How to expand variables in a character string
# Function that returns the character code of a string
Python version (PHP to Python) that deletes the subsequent character string from the specified character string (extension)
How to find the coefficient of the trendline that passes through the vertices in Python
A python script that gets the number of jobs for a specified condition from indeed.com
How to identify the element with the smallest number of characters in a Python list?
[Ansible] Example of playbook that adds a character string to the first line of the file
[Python] A program that finds the shortest number of steps in a game that crosses clouds
[Python] Leave only the elements that start with a specific character string in the array
Find a guideline for the number of processes / threads to set in the application server
How to find the first element that matches your criteria in a Python list
How to find the optimal number of clusters in k-means
Get the number of specific elements in a python list
Python --Find out number of groups in the regex expression
Find the eigenvalues of a real symmetric matrix in Python
"A book to train programming skills to fight in the world" Python code answer example --1.2 Count the number of the same characters
Get the value of a specific key up to the specified index in the dictionary list in Python
When a character string of a certain series is in the Key of the dictionary, the character string is converted to the Value of the dictionary.
How to determine the existence of a selenium element in Python
[Introduction to Python] How to output a character string in a Print statement
A story that struggled to handle the Python package of PocketSphinx
How to check the memory size of a variable in Python
How to check the memory size of a dictionary in Python
A function that measures the processing time of a method in python
A script that returns 0, 1 attached to the first Python prime number
[python] A note that started to understand the behavior of matplotlib.pyplot
[Python] A simple function to find the center coordinates of a circle
[Python] A program that rotates the contents of the list to the left
Get the number of readers of a treatise on Mendeley in Python
[Python] How to invert a character string
Summary of character string format in Python3 Whether to live with the old model or the new model
[Python] A program that calculates the number of chocolate segments that meet the conditions
Mayungo's Python Learning Episode 6: I tried to convert a character string to a number
[Python] How to put any number of standard inputs in a list
Test & Debug Tips: Create a file of the specified size in Python
I want to batch convert the result of "string" .split () in Python
I want to color a part of an Excel string in Python
The eval () function that calculates a string as an expression in python
[Introduction to Python] How to write a character string with the format function
I made a program to check the size of a file in Python
"A book to train programming skills to fight in the world" Python code answer example --1.9 Rotation of strings
Count the number of times two values appear in a Python 3 iterator type element at the same time
4 methods to count the number of occurrences of integers in a certain interval (including imos method) [Python implementation]
[Completed version] Try to find out the number of residents in the town from the address list with Python
How to input a character string in Python and output it as it is or in the opposite direction.
Create a bot that posts the number of people positive for the new coronavirus in Tokyo to Slack
A story about creating a program that will increase the number of Instagram followers from 0 to 700 in a week
Output the number of CPU cores in Python
How to embed a variable in a python string
Get the caller of a function in Python