Contents
warmup-2
string_match
Q.
『Given 2 strings, a and b, return the number of the positions where they contain the same length 2 substring. So “xxcaazz” and “xxbaaz” yields 3, since the “xx”, “aa”, and “az” substrings appear in the same place in both strings.』
ex)
string_match(‘xxcaazz’, ‘xxbaaz’) → 3
string_match(‘abc’, ‘abc’) → 2
string_match(‘abc’, ‘axc’) → 0
要するに、連続した2文字を比較した時に、かぶる個数を数えろということである。
自分が書いたコードが以下である。for文処理を何回繰り返すかは、文字列aと文字列bの長さによるので、a>bの時とa<bの時をif文で表現した。
1 2 3 4 5 6 7 8 9 10 11 |
def string_match(a, b): count = 0 if len(a)>=len(b): for i in range(len(b)-1): if a[i:i+2]==b[i:i+2]: count = count +1 if len(a)<len(b): for i in range(len(a)-1): if a[i:i+2]==b[i:i+2]: count = count +1 return count |
しかしpythonには便利な関数min()関数があることをしる(思い出す)。
min(len(a),len(b))でaとbの文字数の少ない方を選択できるわけだ。これを用いると簡単になる。
1 2 3 4 5 6 7 8 9 10 11 |
def string_match(a, b): shorter = min(len(a), len(b)) count = 0 for i in range(shorter-1): a_sub = a[i:i+2] b_sub = b[i:i+2] if a_sub == b_sub: count = count + 1 return count |
上のようにもかける。