開発環境
- OS X Mavericks - Apple(OS)
- Emacs (CUI)、BBEdit - Bare Bones Software, Inc. (GUI) (Text Editor)
- Python (プログラミング言語)
Learning Python (Mark Lutz (著)、Oreilly & Associates Inc)のPART III.(Functions and Generators)、CHAPTER 19(Advanced Function Topics)、Test Your Knowledge: Quizを解いてみる。
その他参考書籍
Test Your Knowledge: Quiz
コード(BBEdit)
sample.py
#!/usr/bin/env python3
#-*- coding: utf-8 -*-
import functools
# 1.
# defもlambdaも関数の定義に使う
def func1(x, y):
return x + y
func2 = lambda x, y: x + y
for func in [func1, func2]:
print(func(5, 10))
# 2
# 関数を再利用しない時や、式しか使えない場所(listの要素等)でlambdaが最適
for func in [lambda x: x ** 1, lambda x: x ** 2]:
print(func(2))
# 3
m = map(lambda x:x ** 2, range(10))
print(m, list(m))
f = filter(lambda x: x % 2 == 0, range(10))
print(f, list(f))
r = functools.reduce(lambda x, y: x + y, range(10), 10)
print(r)
def g(n:'n_annotation') -> str:
s = 'spam'
return s * n
# 4
print(g(10))
print(g.__annotations__)
# 5. 再帰関数で階乗
def fact(n):
if n <= 1:
return n
return n * fact(n - 1)
print(fact(10))
# 7.
# return文
def f1(a):
return a + 1
print(f1(10))
# mutableなオブジェクトを引数に渡す
def f2(a):
a[0] = 'Python'
l = [1,2,3,4,5]
f2(l)
print(l)
# globalの使用
x = 10
def f3():
global x
x = 100
f3()
print(x)
入出力結果(Terminal)
$ ./sample.py
15
15
2
4
<map object at 0x1067d7110> [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
<filter object at 0x1067d7210> [0, 2, 4, 6, 8]
55
spamspamspamspamspamspamspamspamspamspam
{'return': <class 'str'>, 'n': 'n_annotation'}
3628800
11
['Python', 2, 3, 4, 5]
100
$
0 コメント:
コメントを投稿