LoginSignup
2
5

More than 5 years have passed since last update.

【python】100本ノックにチャレンジ!(006〜009)

Last updated at Posted at 2017-08-16

これまでの経緯などについて

最初の投稿を参照ください

ノック状況

9/24追加

006. 集合

"paraparaparadise"と"paragraph"に含まれる文字bi-gramの集合を,それぞれ, XとYとして求め,XとYの和集合,積集合,差集合を求めよ.さらに,'se'というbi-gramがXおよびYに含まれるかどうかを調べよ.

set_006.py
from training.bigram_005 import ngram

msg1 = "paraparaparadise"
msg2 = "paragraph"
msg3 = "se"

type = 'char'
X_list = ngram(msg1,2,type)
Y_list = ngram(msg2,2,type)
msg3_list = ngram(msg3,2,type)

set_X=set(X_list)
set_Y=set(Y_list)
set_msg3=set(msg3_list)

plus_list = set_X | set_Y
multi_list = set_X & set_Y
sub_list = set_X - set_Y

print("X_list=",X_list)
print("Y_list=",Y_list)
print("set_X=",set_X)
print("set_Y=",set_Y)
print("plus_list=",plus_list)
print("multi_list=",multi_list)
print("sub_list=",sub_list)
print("seをset_Xに含んでいる場合はtrue",set_X.issuperset(set_msg3))
print("seをset_Yに含んでいる場合はtrue",set_Y.issuperset(set_msg3))

result
X_list= ['pa', 'ar', 'ra', 'ap', 'pa', 'ar', 'ra', 'ap', 'pa', 'ar', 'ra', 'ad', 'di', 'is', 'se']
Y_list= ['pa', 'ar', 'ra', 'ag', 'gr', 'ra', 'ap', 'ph']
set_X= {'ar', 'ap', 'ra', 'is', 'se', 'ad', 'pa', 'di'}
set_Y= {'ar', 'ap', 'ra', 'ag', 'pa', 'ph', 'gr'}
plus_list= {'ar', 'ap', 'ra', 'is', 'ag', 'se', 'ad', 'pa', 'ph', 'di', 'gr'}
multi_list= {'pa', 'ar', 'ap', 'ra'}
sub_list= {'ad', 'di', 'se', 'is'}
seをset_Xに含んでいる場合はtrue True
seをset_Yに含んでいる場合はtrue False

Process finished with exit code 0

感想:SETってすごい・・・便利すぎる。

007. テンプレートによる文生成

引数x, y, zを受け取り「x時のyはz」という文字列を返す関数を実装せよ.さらに,x=12, y="気温", z=22.4として,実行結果を確認せよ.

template_007.py
from string import Template

def template_print(x,y,z):
    value ={'time':x,'name':y,'tempture':z}
    t = Template("$time時の$nameは$tempture")
    return print(t.substitute(value))

if __name__ == "__main__":
    x=12
    y='気温'
    z=22.4
    template_print(x,y,z)

result
12時の気温は22.4
Process finished with exit code 0

感想:template関数を初めて知りましたがイマイチ使い所が分からない。。。

008. 暗号文

与えられた文字列の各文字を,以下の仕様で変換する関数cipherを実装せよ。英小文字ならば(219 - 文字コード)の文字に置換。その他の文字はそのまま出力。この関数を用い,英語のメッセージを暗号化・復号化せよ

cipher_008.py
import re

def cipher(msg):
    pattern = re.compile("[a-z]")
    cipher_msg = ''
    for temp in msg:
        if pattern.match(temp):
            cipher_msg += chr(219-ord(temp))
            continue
        else:
            cipher_msg += temp
            continue
    return  cipher_msg

if __name__=="__main__":
    msg = "Cipher_msg_012345"
    print("元msg=",msg)
    c = cipher(msg)
    print("暗号化=",c)
    d = cipher(c)
    print("復号化=",d)

result
元msg= Cipher_msg_012345
暗号化= Crksvi_nht_012345
復号化= Cipher_msg_012345
Process finished with exit code 0

感想:ordやchrを使わないとasciiコードの値として計算できないのを知った。そして最初は復号処理として別関数を用意し、219を足したら復号になるだろとか思ってやったらそんなことなかった。

009. Typoglycemia

スペースで区切られた単語列に対して,各単語の先頭と末尾の文字は残し,それ以外の文字の順序をランダムに並び替えるプログラムを作成せよ.ただし,長さが4以下の単語は並び替えないこととする.適当な英語の文("I couldn't believe that I could actually understand what I was reading :the phenomenal power of the human mind .")を与え,その実行結果を確認せよ.

typoglycemia_010.py
from training.word2list_003 import word2list
import random

#文字列をランダム化する関数
#random_msgを返す
def random_word(word):
    random_msg=''
    for temp in word:
#4文字以下は処理しない
        if(len(temp)<=4):
            random_msg += temp
            random_msg += " "
            continue
        else:
#文字列の最初はfirst_strに格納
#文字列の最初はlast_strに格納
            temp_length = len(temp)
            first_str= temp[0]
            last_str=temp[temp_length-1]
            random_word_list=[]
            random_word=''
            temp_random_list = []
#取得した文字列の最初と最後は処理しない
#中間の文字列をリスト化してrandom_word_listに入れる
            for index,temp_word in enumerate(temp):
                if(index==0 or index==temp_length-1):
                    continue
                else:
                    random_word_list.append(temp_word)
                continue
#リスト化した文字列からランダムに抽出し、temp_random_listに入れる
#抽出した文字列は抽出元のリストから削除する
            for i in range(len(random_word_list)):
                temp_random_list.append(random.choice(random_word_list))
                random_word_list.remove(temp_random_list[i])
                continue
#ランダムリストをtemp_wordに追加していく
            for temp_word in temp_random_list:
                random_word+=temp_word
                continue
#firstとrandomとlastを組み合わせてrandom_msgへ入れる
            random_msg += (first_str + random_word + last_str)
            random_msg += " "

    return  random_msg

if __name__ == "__main__":
    msg = "I couldn't believe that I could actually understand what I was reading : the phenomenal power of the human mind ."
    word = word2list(msg)
    random = random_word(word)
    print(random)

result
I cdlonu't beivele that I could alalutcy uanserntdd what I was rindeag : the paeemnonhl pweor of the hmuan mind . 
Process finished with exit code 0

感想:値をランダムにとってきて、取得した値をリストから削除する処理が工夫ポイント

2
5
2

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
2
5