In [1]:
def add(num1, num2):
return num1 + num2
result = add(232, 323)
print result
In [3]:
print add('abcd', 'efg')
In [6]:
#함수이름으로부터 기능이 명시되면 좋다.
def test_substraction(a, b):
return a - b
print test_substraction(5, 3)
In [2]:
#parameter(argument)
#int, string, float, list 등 어떤 파이썬 객체도 전달 가능
def len2(string):
return len(string)
def sum2(nums):
return sum(nums)
print len2('test')
print sum2([1, 2, 3, 4])
In [7]:
#optional parameter
#기본값 지정가능, 인자 값을 전달하지 않을 경우 위에서 정한 기본값 전달
def print_hello(nums = 'hello world'):
return 1 + 3 + 4
print_hello('hello world')
print_hello()
Out[7]:
In [9]:
def increment_by(a, b = 1):
return a + b
print increment_by(45)
print increment_by(34, 10)
In [1]:
def simple():
return 1
a = simple()
print a
In [7]:
def just_return():
a = 1
b = 1
return
c = just_return()
print c
In [8]:
def add_sub(a, b):
return a+b, a-b
add_sub(9, 3)
Out[8]:
In [9]:
def c_to_f(c):
f = 1.8 * c + 32
return f
print c_to_f(36.5)
In [10]:
def odd_sum(nums):
odd_sum = 0
for i in nums:
if i % 2 == 1:
odd_sum += i
return odd_sum
def odd_sum2(nums):
return sum([i for i in nums if i % 2 == 1])
a = [1, 2, 3, 7, 8, 10, 11, 13, 15, 29, 100, 201, 300]
print odd_sum(a)
print odd_sum2(a)
In [11]:
def max_val(nums):
mval = nums[0]
for i in nums:
if mval < i:
mval = i
return mval
print max_val(a)
In [12]:
def factorial(n):
mul = 1
for i in range(1, n + 1):
mul *= i
return mul
factorial(6)
Out[12]:
In [13]:
str1 = 'Hi my name is {} and the weather is {}'.format('younghyo', 'clear')
print str1
In [14]:
def test1():
print 23
def run_something(func):
func()
test2 = test1
test2()
print test1, type(test1)
run_something(test1)
def bubble_sort():
pass
def quick_sort():
pass
def sort(sort_method):
return sort_method()
sort(bubble_sort)
sort(quick_sort)
In [15]:
def factorial(n):
mul = 1
for i in range(2, n+1):
mul *= i
return mul
assert(factorial(5) == 120)
In [19]:
#fibonacci sequence
def fibonacci(n):
fibo = [1, 1]
for i in range(2, n):
fibo.append(fibo[i-1] + fibo[i-2])
return fibo
print fibonacci(5)
In [18]:
#fibonacci recursive
def recursive_fibonacci(n):
if n == 1 or n ==2:
return 1
return recursive_fibonacci(n-1) + recursive_fibonacci(n-2)
print recursive_fibonacci(5)
In [2]:
def square(x):
return x ** 2
#lambda x : x ** 2
square2 = lambda x : x ** 2
print square(4), square2(4)
In [3]:
add3 = lambda x, y : x + y
print add3(20, 30)
filter, map ,reduce
In [8]:
nums = range(2, 100)
print filter(None, nums)
print filter(lambda x : x % 2 == 0, nums)
In [9]:
a = ['apple', 'cat', 'banana', 'hat', 'orange', 'carrot', 'python']
print filter(lambda x : len(x) <=5, a)
print [x for x in a if len(x) <=5]
In [10]:
nums = range(2, 20)
print map(lambda x : x ** 2, nums)
In [11]:
nums = [1, 2, 9, 8, 5, 4, 7, 10, 3]
print reduce(lambda x, y : x + y, nums)
In [12]:
print reduce(lambda x, y : x if x > y else y, nums)
In [ ]:
In [ ]:
In [ ]:
In [ ]:
In [ ]:
In [ ]:
In [ ]:
In [ ]:
In [ ]:
In [ ]:
In [ ]:
In [ ]: