HPO機密日誌

自己をならふといふは、自己をわするるなり。

CheckiOにはまる

Pythonを学ぶにはすごいサイトではないだろうか。気がつくとパズルを解くように、ChekiOを開いている。初歩の初歩だが、たとえば文字をカウントする課題。

http://www.checkio.org/mission/most-wanted-letter/

私は冗長なプログラムしかかけなかった。

def checkio(text):
    text_list = list(text)
    a_z="zyxwvutsrqponmlkjihgfedcba"
    count = {}
    for i in text_list:
        i_lower = i.lower()
        if i_lower in a_z:
            if i_lower in count:
                count[i_lower] = count[i_lower] + 1
            else:
                count[i_lower] = 1
    count_list = []
    for i in a_z:
        if i in count:
            count_list.append([count[i],i])
            print(count_list)
    count_list.sort(key=lambda x:(0-x[0],x[1]), reverse=True)
    print(count_list)
    return count_list[-1][1] 

テキストをリストにして、辞書機能を使って単語の頻度をカウントして、ソートして答えを出すと。「key」を使って二要素でソートするところがわからず苦労した。

ChekiOがいいのは、解けた後だと公開(Publich)された人のプログラムを見るところ。私が19行にもしてしまったプログラムを4行で解いている方がいた。びっくり!

import string
 
def checkio(text):
    """
    We iterate through latyn alphabet and count each letter in the text.
    Then 'max' selects the most frequent letter.
    For the case when we have several equal letter,
    'max' selects the first from they.
    """
    text = text.lower()
    return max(string.ascii_lowercase, key=text.count)

Pythonを習ってなにをするというわけではないのだが、当分はまりそうだ。