0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[Python3]任意の文字列に含まれる文字を数える

Last updated at Posted at 2018-11-24

はじめに

昨日に引き続きcheckioの課題にトライ。
(普通に1時間以上かかっているので、平日はちょっと厳しそう)

今回書いたコード

入力した文字列から、アルファベットの数を数えて一番多い文字を返すプログラム。
(アルファベット以外は数えない。大文字小文字は区別しない)

def checkio(text: str) -> str:
    import re

    ### 変数定義
    phrase = text.lower() # 大文字,小文字は区別しない
    count_lst = []
    count = []
    result = []

    ### 処理開始
    for word in phrase:
        ### アルファベット以外は除外
        if not bool(re.match("[a-z]+",word)):
            continue
        flg = 0
    
        ### 文字の数を数えながらリストに格納
        for x in range(len(count_lst)):
            try:
                count_lst[x].index(word)
                count_lst[x][1] += 1
                flg = 1
                break
            except ValueError:
                pass
    
        ### フラグが0(リストに値が存在しない)の場合、リストに文字を追加
        if flg != 1:
            count_lst.append([word,1])

    ### リストから文字数だけをリストに格納
    for y in range(len(count_lst)):
        count.append(count_lst[y][1])
    max_num = max(count)

    ### 一番多い数だった文字をリストに格納
    for z in range(len(count_lst)):
        if count_lst[z][1] == max_num:
            result.append(count_lst[z][0])

    ### アルファベット順にソート
    result.sort()
    return(result[0])

今回学んだこと

  • アルファベットの数え方に少し苦労(アルファベット分変数を作れば簡単だったかもですが、さすがにクソダサだと思って自重)
  • リストの検索にはindex(毎回忘れるマン)
  • リストの要素数を数える時はlen
  • 二次元のリストでmax(またはmin)を使った場合、いずれも前にある要素について判定
  • sortでアルファベット順に並べ替えができる(便利)
  • 二次元のリストで検索をかけるならenumerate()を使っている例もあった(むしろこっちの方が本筋くさい。いつか調べる)
  • 「最初の一文字を除外」はword[1:]でできる(今回は使わなかった)

構文まとめ

メソッド 説明 構文
index リストに検索文字が含まれている場合、アドレスを返す(無い場合はValueError) word.index("検索文字")
len 文字数を数える。リストの場合は要素数を数える len("文字列")
0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?