2020-05-10 課題

はじめに

自分用メモ

プログラミングの一般論

イテレーターとジェネレーター

基本

1 つ 1 つ作る?

1
2
3
4
xs = range(0, 10)
print(type(xs))
for x in xs:
    print(x)
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
<class 'range'>
0
1
2
3
4
5
6
7
8
9

Python のジェネレーターの簡単な例

1
2
3
4
5
6
7
def my_generator():
    yield 1
    yield 2
    yield 3

gen = my_generator()
print(type(gen))
1
<class 'generator'>
1
2
3
4
5
6
7
8
9
def my_generator():
    yield 1
    yield 2
    yield 3

gen = my_generator()
print(gen.__next__())  # 1
print(gen.__next__())  # 2
print(gen.__next__())  # 3
1
2
3
1
2
3
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
"""4 回呼ぶと怒られる"""
def my_generator():
    yield 1
    yield 2
    yield 3

gen = my_generator()
gen.__next__()  # 1
gen.__next__()  # 2
gen.__next__()  # 3
gen.__next__()  # StopIteration
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
---------------------------------------------------------------------------

StopIteration                             Traceback (most recent call last)

<ipython-input-1-f379ec6e011a> in <module>()
      8 gen.__next__()  # 2
      9 gen.__next__()  # 3
---> 10 gen.__next__()  # StopIteration


StopIteration:
1
2
3
4
5
6
7
8
def my_generator():
    yield 1
    yield 2
    yield 3

gen = my_generator()
for a in gen:
    print(a)
1
2
3
1
2
3

クラス

1
2
3
4
5
s_scores = [10, 20, 30, 40, 50] # 国語・数学・英・理科・社会の順
def calc_mean(s_scores):
    return sum(s_scores) / len(s_scores)
s_mean = calc_mean(s_scores)
print(s_mean)
1
30.0
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
s_scores = {
    "ja": 10,
    "math": 20,
    "eng": 30,
    "science": 40,
    "society": 50
}

def calc_mean(s_scores):
    s_sum = sum([v for v in s_scores.values()])
    return s_sum / len(s_scores)

s_mean = calc_mean(s_scores)
print(s_mean)
1
30.0
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Score():
    def __init__(self, ja, math, eng, sci, soc):
        self.ja = ja
        self.math = math
        self.eng = eng
        self.sci = sci
        self.soc = soc

    def calc_mean(self):
        return (self.ja + self.math + self.eng + self.sci + self.soc) / 5

s = Score(10, 20, 30, 40, 50)
print(s.calc_mean())
1
30.0
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Score():
    def __init__(self, ja, math, eng, sci, soc):
        self.ja = ja
        self.math = math
        self.eng = eng
        self.sci = sci
        self.soc = soc

    def calc_mean(self):
        return (self.ja + self.math + self.eng + self.sci + self.soc) / 5

s1 = Score(10, 20, 30, 40, 50)
print(s1.calc_mean())

s2 = Score(1, 2, 3, 4, 5)
print(s2.calc_mean())
1
2
30.0
3.0

アルゴリズムとデータ構造

アルゴリズムとデータ構造でプログラミングを勉強する

いいところ

自分に合った勉強法・勉強内容を探そう