ブリブリ備忘録 おっ、python

HackerRankの問題とコメント(python3) 拙いですが...

Find a string

・問題

In this challenge, the user enters a string and a substring. You have to print the number of times that the substring occurs in the given string. String traversal will take place from left to right, not from right to left.

NOTE: String letters are case-sensitive.

Input Format

The first line of input contains the original string. The next line contains the substring.

Constraints

 
Each character in the string is an ascii character.

Output Format

Output the integer number indicating the total number of occurrences of the substring in the original string.

Sample Input

ABCDCDC
CDC

Sample Output

2

Concept

Some string processing examples, such as these, might be useful. 
There are a couple of new concepts: 
In Python, the length of a string is found by the function len(s), where  is the string. 
To traverse through the length of a string, use a for loop:

for i in range(0, len(s)):
    print (s[i])

A range function is used to loop over some length:

range (0, 5)

Here, the range loops over  to  is excluded.

ソースコード

def count_substring(string, sub_string):
    L1=len(string)
    L2=len(sub_string)
    n=0
    for i in range (L1-L2+1):
        if string[i:i+L2] == sub_string:
            n+=1        
    return n

if __name__ == '__main__':
    string = input().strip()
    sub_string = input().strip()
    
    count = count_substring(string, sub_string)
    print(count)

・コメント

一行目の入力内に二行目の入力が何個含まれているかを調べる問題。

 

問題文中で出されている例として、ABCDCDCの中にCDCは2つ含まれているというものがあった。前側のCDCの最後のCと後ろ側のCDCの最初のCは被っているという点に気をつけなければならない。

 

この問題を解く際に、共通する文字列がどれだけ含まれているかを出力する関数を探したが、この重複を許さないものしか見つけることができなかった(もっと探せばあったのかも?)ので、自分で真面目に書くことにした。

 

例えば例ではABCDCDCという7文字の中からCDCという3文字を見つけるので、7文字の中から連続した3文字の抜き取り方はABC,BCD,CDC,DCD,CDCの5通りしかないので、これらが一致する個数をカウントすればいいだけと気づいたので、これを一般的な形に拡張した。

 

一行目の文字列の長さをL1,二行目の文字列の長さをL2とすると長さL1の文字列から長さL2の文字列を抜き取る方法はL1-L2+1通りあるので、その全てで一致するかを試す。

 

文字列stringのk番目からn番目までを抜き出す方法はstring[k-1:k+n]でよい。

・URL

https://www.hackerrank.com/challenges/find-a-string/problem