学習者言語の分析(基礎)1 第2回

  • 2.1 比較演算子
    • 2.1.1 Pythonの比較演算子
  • 2.2 論理演算子
  • 2.3 制御構文 (if文)
  • 2.4 制御構文(forとwhile)
    • 2.4.1 for
    • 2.4.2 while
    • 2.4.3 for文とrange()
    • 2.4.4 for文とif文の組み合わせ
  • 2.5 正規表現: 特定の文字列の検索、除去、置換など
    • 2.5.1 Pythonにおける正規表現
    • 2.5.2 メタ文字
    • 2.5.3 reの他のメソッド
  • 練習問題

2.1 比較演算子¶

In [1]:
# ひとまず、以下のように3つ変数に値を代入してみてください。

x = 3
y = 12
z = 1
In [2]:
# xはyより大きいか等しい
# xはyより大きくも等しくもないので"False"と出力される。

x >=  y
Out[2]:
False
In [3]:
# xとyは等しくない
#"Trueと出力される。

x != y
Out[3]:
True

2.1.1 Pythonの比較演算子¶

演算子 記述例 意味
== x == y xがyに等しい
!= x != y xがyと等しくない
> x > y xがyより大きい
>= x >= y xがyより大きいか等しい
< x < y xがyより小さい
<= x <= y xがyより小さいか等しい

いくつか試してみてください。

2.2 論理演算子¶

演算子 記述 意味
and x and y xとyの両方がTrueの場合True
or x or y xとyのどちらかがTrueの場合True
not not x xがTrueのときFalse、FalseのときTrue
In [4]:
# ひとまず、以下のように3つ変数に値を代入してみてください。
x = 3
y = 12
z = 1
In [5]:
# 論理積: 両者が真であればTrue
x < y and x > z #True
Out[5]:
True
In [6]:
# 論理和: どちらかが真であればTrue
x < y or x < z #True
Out[6]:
True
In [7]:
# 否定: 式が偽であればTrue
not y < x #True
Out[7]:
True

2.3 制御構文 (if文)¶

In [8]:
# ひとまず、以下のように代入してみてください。
x = 1
y = 2
In [9]:
# 以下がPythonのif文です。
# ifの後ろに条件を書き、条件が終わったら:(コロン)
# そこでEnter
# 処理はタグで下げる(自動でタグは入力されます)

if x < y:
    print("Yes!")
    
if x < y:
    print("Yes!")
Yes!
Yes!
In [10]:
# ifの後ろの条件がFalseの場合、elseの下の処理が実行される。
x = 5
y = 3

if x < y:
    print("x is smaller than y.")
else:
    print("x is not smaller than y.")
x is not smaller than y.
In [11]:
# elifで条件を追加できる。
x = 5
y = 5

if x < y:
    print ("x is smaller than y.")
elif x > y:
    print("x is larger than y.")
elif x == y:
    print("x equals to y.")
x equals to y.
In [12]:
# if文の練習
# 入力された値の大小を判定する。

a = input("Input any number you like:")
b = input("Input any number you like:")

a = int(a)
b = int(b)

if a < b:
    print (str(a) + " is smaller than "+ str(b))
elif a == b:
    print (str(a) + " is equal to " + str(b))
else:
    print (str(a) +" is larger than " + str(b))
Input any number you like:12
Input any number you like:13
12 is smaller than 13

2.4 制御構文(forとwhile)¶

2.4.1 for¶

In [13]:
# とりあえず、以下のようなリストを作ってください。
L = [1,2,3]
In [14]:
# Lの要素が先頭からiに入って
# 2行目の処理がされる
# リストの最後まで処理したら終了

for i in L:
    print(i)
1
2
3
In [15]:
# for文とif文の組み合わせ

L = ["pen","book","apple"]

for i in L:
    if i[0] == "a":
        x = "an" + " " + i
    else:
        x = "a" + " " + i
    print(x)
a pen
a book
an apple

2.4.2 while¶

  • 以下のような構造で、

while 条件式:
  処理

  • 条件式がTrueのときにのみ処理を行います。
In [16]:
n = 0

while n < 11:
    print (n)
    n +=1
0
1
2
3
4
5
6
7
8
9
10

2.4.3 for文とrange()¶

  • range()を使用することによりfor文を用いてwhile文と同様のことができます。
In [17]:
# whileの例

i = 0

while i < 5:
    print(i)
    i += 1
0
1
2
3
4
In [18]:
# 同じことをforで

for i in range(5):
    print(i)
0
1
2
3
4
  • range()の引数はrange(X,Y,Z)と3つあり、Xが始まりの値、Yが最後の値、Zが増加量になります。

  • 3つ指定することができますが、

  • ひとつだけ指定するとYが指定されます。

  • 2つ指定するとXとYが指定されます。

  • 3つ指定するとX、Y、Zすべてが指定されます。

  • 違う言い方で

    • range(n): 0からn-1の整数列
    • range(n,m): nからm-1の整数列
    • range(n,m,p): nからmー1の公差pの整数列
In [19]:
# 2つ指定した場合
for i in range(2,10):
    print(i)
2
3
4
5
6
7
8
9
In [20]:
# 3つ指定した場合
for i in range(2,10,2):
    print(i)
2
4
6
8

2.4.4 for文とif文の組み合わせ¶

  • for文とif文を組み合わせます。
In [21]:
# Lにある文から"school"について言及している文を取り出す。

L = ["He walked to school everyday.","I bought a new shirt.", "She went to church.", "The school has a big garden.","I don't know where it is."]

for i in L:
    j = i.lower()
    k = i.split()
    if "school" in k:
        print(i)
He walked to school everyday.
The school has a big garden.

2.5 正規表現: 特定の文字列の検索、除去、置換など¶

  • 例えば、以下の文字列から"S001: "のような識別番号のみを取り除きたいとき

S001: Four score and seven years ago our fathers brought forth on this continent, a new nation, conceived in Liberty, and dedicated to the proposition that all men are created equal. \nS002: Now we are engaged in a great civil war, testing whether that nation, or any nation so conceived and so dedicated, can long endure. \nS003: We are met on a great battle-field of that war.\nS004: We have come to dedicate a portion of that field, as a final resting place for those who here gave their lives that that nation might live.\nS005: It is altogether fitting and proper that we should do this.

In [22]:
# replace()は文字列型の変数で第一変数に検索するパターン、第二変数に置換する文字列を与え
# 以下のように動作する。

sample = "I am your father"

sample.replace("father","mother")
Out[22]:
'I am your mother'
In [23]:
text = "S001: Four score and seven years ago our fathers brought forth on this continent, a new nation, conceived in Liberty, and dedicated to the proposition that all men are created equal. \nS002: Now we are engaged in a great civil war, testing whether that nation, or any nation so conceived and so dedicated, can long endure. \nS003: We are met on a great battle-field of that war.\nS004: We have come to dedicate a portion of that field, as a final resting place for those who here gave their lives that that nation might live.\nS005: It is altogether fitting and proper that we should do this."

# replace()を利用して保存を繰り返し取り除くことができる。
a = text.replace("S001: ","")
b = a.replace("S002: ","")
c = b.replace("S003: ","")
d= c.replace("S004: ","")
d.replace("S005: ","")

# 5個ぐらいだったらいいけど、2000個とかあったらきつい。
Out[23]:
'Four score and seven years ago our fathers brought forth on this continent, a new nation, conceived in Liberty, and dedicated to the proposition that all men are created equal. \nNow we are engaged in a great civil war, testing whether that nation, or any nation so conceived and so dedicated, can long endure. \nWe are met on a great battle-field of that war.\nWe have come to dedicate a portion of that field, as a final resting place for those who here gave their lives that that nation might live.\nIt is altogether fitting and proper that we should do this.'

2.5.1 Pythonにおける正規表現¶

  • 正規表現は文字列を検索、置換する方法のひとつ。
  • パターンを検索できる。
In [24]:
# reというパッケージを用いて以下のコードで目的は達成できる
# re.sub()は第一引数に検索するパターン、第二引数に置換する文字列、第三引数に対象となる変数を指定する
# 第一引数にある"\d"はメタ文字と呼ばれる文字で"\d"は「0から9の数字のどれか」という意味
import re
text2 = re.sub(r"S\d\d\d: ","",text)
text2
Out[24]:
'Four score and seven years ago our fathers brought forth on this continent, a new nation, conceived in Liberty, and dedicated to the proposition that all men are created equal. \nNow we are engaged in a great civil war, testing whether that nation, or any nation so conceived and so dedicated, can long endure. \nWe are met on a great battle-field of that war.\nWe have come to dedicate a portion of that field, as a final resting place for those who here gave their lives that that nation might live.\nIt is altogether fitting and proper that we should do this.'

2.5.2 メタ文字¶

正規表現では以下のようなメタ文字を使用して文字列を検索する。

メタ文字 意味
. \n(改行)以外の全ての文字にマッチ
\w 文字と数字全部にマッチ [a-z A-Z 0-9]
\W \w以外にマッチ
\s スペース、改行、タブにマッチ [\n\r\t]
\S スペース以外にマッチ
\t タブにマッチ
\n 改行にマッチ
\r 改行にマッチ
\d 数字にマッチ[0-9]
^ 文字列の先頭にマッチ
$ 文字列の末尾にマッチ
\ 文字列の無効化
[^] ^の後ろの文字以外にマッチ
* 前の文字の0回以上の繰り返し
+ 前の文字の1回以上の繰り返し
? 前の文字の0回か1回の出現
[ ] 集合。例:[aiu](a,i,uのどれか)

2.5.3 reの他のメソッド¶

reには以下のメソッドがあります。

メソッド 意味
re.sub(pattern1,pattern2, string) stringにpattern1があったらpattern2で置き換える
re.search(pattern,string) patternの文字列がstringのどこにあるかを返す
re.match(pattern,string) patternの文字列がstringの先頭にあるか判定する
In [25]:
# 正規表現のパッケージのインポート
import re

# 対象とする文字列
text = "abcdef"

# search()の第一引数は検索するパターン、第二引数は検索対象の変数
re.search("b",text)

# 検索したパターンが対象の文字列にあれば、以下のような出力を返す
# 検索したパターンが対象の文字列になければ、何も返さない
Out[25]:
<re.Match object; span=(1, 2), match='b'>
In [26]:
# match()はパターンが先頭にあるかどうかを返す

# 対象とする文字列
text = "abcdef"

# match()の第一引数は検索するパターン、第二引数は検索対象の変数
re.match("a",text)
Out[26]:
<re.Match object; span=(0, 1), match='a'>
In [27]:
# このようなmatch()の機能を利用して特定のパターンを持つ文字列のみを取り出すことができる
# 以下はLの中から特定のパターン(大文字のSから始まり3桁の数字が続く文字列)を探して、Mに保存するコード

# 検索対象のリスト
L = ["S001","SW05","S002","S003","s091","S004","S9","S005"]

# 特定のパターンを持つ文字列を保存するリスト
M = []

# 以下ではiにmatchの第一引数に指定したパターンがあれば
# objに結果が代入され、なければobjは空となる
# "if obj:"はobjに何か代入されていればTrue、何も代入されて
# なければFalse
# group()は見つけた(マッチした)値を取り出すメソッド

for i in L:
    obj = re.match(r"S\d\d\d",i)
    if obj:
        match_obj = obj.group()
        M.append(match_obj)
M
Out[27]:
['S001', 'S002', 'S003', 'S004', 'S005']
In [28]:
# split()でも正規表現が使える
# "\n"は改行文字

text = "The club isn't the best place to find a lover\nSo the bar is where I go\nMe and my friends at the table doing shots\nDrinking fast and then we talk slow\nCome over and start up a conversation with just me\nAnd trust me I'll give it a chance now\nTake my hand, stop, put Van the Man on the jukebox\nAnd then we start to dance, and now I'm singing like"

# 改行で分ける
T = text.split("\n")
T
Out[28]:
["The club isn't the best place to find a lover",
 'So the bar is where I go',
 'Me and my friends at the table doing shots',
 'Drinking fast and then we talk slow',
 'Come over and start up a conversation with just me',
 "And trust me I'll give it a chance now",
 'Take my hand, stop, put Van the Man on the jukebox',
 "And then we start to dance, and now I'm singing like"]

練習問題¶

問題1

for文を使って以下の単語を複数形にしなさい。

["boy","girl", "pen","book","dish","watch","box","fox"]

問題2

inputされた値が3の倍数の場合は"Yes!"、そうでない場合は"No!"と出力するコードを書きなさい。

問題3

inputされた英単語が10文字以上の場合は"Long word"と出力されるコードを書きなさい。

問題4

fizzbuzzです。ルールは以下です。

  1. 1から100までの数字で
  2. 3で割り切れる時には"Fizz!"と表示
  3. 5で割り切れる時には"Buzz!と表示
  4. 3でも5でも割り切れる時には"Fizz! Buzz!"と表示
  5. それ以外の数字はそのまま表示

for文を使って出力してみましょう。

問題5

以下のリスト(L)の各要素を10で割ってリストMに保存しなさい。要素が数値ではない場合、リストMには"X"を追加しなさい。

L = [12,100,90,88,45,"32","25",12,"33",90,100]

問題6

任意の整数に関して、その値が偶数の場合は2で割り、奇数の場合は3をかけて1を足すという操作を繰り返すと必ず1になります(コラッツの問題)。

例1
13 -> 40 -> 20 -> 10 -> 5 -> 16 -> 8 -> 4 -> 2 -> 1

例2
22 -> 11 -> 34 -> 17 -> 52 -> 26 -> 13 -> 40 -> 20 -> 10 -> 5 -> 16 -> 8 -> 4 -> 2 -> 1

whileとifを用いて任意の整数を入力して、この過程を出力してみましょう。

問題7

+は前の文字の1文字以上の連続とマッチします。アルファベットの大文字は[A-Z]でマッチします。
以下の文字列からアルファベット大文字1文字で始まり数字が何文字かあり最後にアルファベットが1文字の文字列を取り出しなさい。

N = ["D928333f","S0120000","99","jjjjgk00","jjj","S1022220d","kl201922d","K10230t"]

問題8

以下のリストから過去形の動詞だけを取り出しなさい。

P = ["edit","worked","prediction","spinned","talked"]

問題9

強いパスワードとは以下の条件を満たします。

  1. 8文字以上で、
  2. 数字、大文字、小文字がすべて含まれる。

以下の7つのパスワードが強いパスワードか弱いパスワードかを判定するコードを書きなさい。

PWD = ["12Wxdde17","1234","Pythonbootcamp","ijKKT14379","GreatJourney","apple","abcdefghijk"]