my_str = 'I am Hen-er-y the Eighth,' ' I am!'
print(my_str)
I am Hen-er-y the Eighth, I am!
my_str = 'I am Hen-er-y the Eighth,' \
' I am!'
my_str
'I am Hen-er-y the Eighth, I am!'
my_str = ('I am Hen-er-y the Eighth, '
'I am! I am not just any Henry VIII, '
'I really am!')
my_str
'I am Hen-er-y the Eighth, I am! I am not just any Henry VIII, I really am!'
a = 10, 5
type(a)
tuple
side1, side2 = a
side1
10
side2
5
side1, side2 = 10, 5
length_of_hypotenuse = ( (side1 * side1 + side2 * side2)
** 0.5 )
length_of_hypotenuse
11.180339887498949
side1, side2 = 10, 5
length_of_hypotenuse = (side1 * side1 + side2 * side2) \
** 0.5
length_of_hypotenuse
11.180339887498949
beat_list = ['John', 'Paul', 'George', 'Ringo']
for i in range(len(beat_list)):
print(beat_list[i])
John Paul George Ringo
beat_list = ['John', 'Paul', 'George', 'Ringo']
for guy in beat_list:
print(guy)
John Paul George Ringo
beat_list = ['John', 'Paul', 'George', 'Ringo']
for i, name in enumerate(beat_list, 1):
print(i, '. ', name, sep='')
1. John 2. Paul 3. George 4. Ringo
s1 = s2 = 'A string.'
s1 += '...with more stuff!'
print('s1:', s1)
print('s2:', s2)
s1: A string....with more stuff! s2: A string.
a_list = b_list = [10, 20]
a_list += [30, 40]
print('a_list:', a_list)
print('b_list:', b_list)
a_list: [10, 20, 30, 40] b_list: [10, 20, 30, 40]
str_list = []
n = ord('a')
for i in range(n, n + 26):
str_list += chr(i)
alphabet_str = ''.join(str_list)
alphabet_str
'abcdefghijklmnopqrstuvwxyz'
a = b = c = d = e = 0
a is b
True
a = 1
b = 0
a, b = 1, 0
a = 4, 8, 12 # a는 이제 3개 값을 지닌 튜플이다.
a
(4, 8, 12)
a, b = 10, 20
temp = a # a 기존 값 보존
a = a + b # a에 신규 값 설정
b = temp # b에 a 기존 값 저장
print(a, b)
30 10
a, b = 10, 20
a, b = a + b, a
print(a, b)
30 10
def fibo(n):
a, b = 1, 0
while a <= n:
print(a, end=' ')
a, b = a + b, a
fibo(10)
1 1 2 3 5 8
x, y = 1, 25
print(x, y) # 1 25 출력
x, y = y, x
print(x, y) # 25 1 출력
1 25 25 1
a, b, c = [1, 2, 3]
print(a, b, c)
1 2 3
tup = 10, 20, 30 # 패킹 (Packing)
a, b, c = tup # 언패킹 (Unpacking)
print(a, b, c) # 10, 20, 30 출력
10 20 30
tup = 10, 20, 30
a, b = tup # 에러: 언팩 대상 값이 너무 많음
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-21-25968d856f41> in <module> 1 tup = 10, 20, 30 ----> 2 a, b = tup # 에러: 언팩 대상 값이 너무 많음 ValueError: too many values to unpack (expected 2)
my_list = [3]
my_tup = (3)
print(type(my_tup))
<class 'int'>
my_tup = (3,) # 한 항목 3을 가진 튜플 만들기
print(type(my_tup))
<class 'tuple'>
a, *b = 2, 4, 6, 8
print(a, b)
2 [4, 6, 8]
a, *b, c = 10, 20, 30, 40, 50
print(a, b, c)
10 [20, 30, 40] 50
big, bigger, *many = 100, 200, 300, 400, 500, 600
print(big, bigger, many, sep='\n')
100 200 [300, 400, 500, 600]
my_list = [0] * 10000
len(my_list)
10000
my_list = 1999 * [12]
len(my_list)
1999
trip_list = [1, 2, 3] * 100
len(trip_list)
300
divider_str = '_' * 40
divider_str
'________________________________________'
def double_me(n):
n *= 2
a = 10
double_me(a)
print(a) # a 값이 두배가 되지 않는다!!
10
def double_me(n):
return n * 2
a = 10
a = double_me(a)
print(a)
20
def quad(a, b, c):
determin = (b * b - 4 * a * c) ** .5
x1 = (-b + determin) / (2 * a)
x2 = (-b - determin) / (2 * a)
return x1, x2
x1, x2 = quad(1, -1, -1)
x = quad(1, -1, -1)
x
(1.618033988749895, -0.6180339887498949)
def find_divisor(n, max):
for i in range(2, max + 1):
if n % i == 0:
print(i, 'divides evenly into', n)
break
else: # break를 만나서 일찍 빠져나오지 않는 한 루프 종료시 수행된다.
print('No divisor found')
find_divisor(49, 6)
No divisor found
find_divisor(49, 7)
7 divides evenly into 49
my_str = ''
while True:
if len(my_str) == 0:
break
while True:
if not my_str:
break
test_str = input('Enter test string: ')
a_list = [c.upper() for c in test_str if c.isalnum()]
print(a_list)
print(a_list == a_list[::-1])
['A', 'B', 'C', 'B', 'A'] True
s = '1 / 2'
s = s.replace(' ', '')
s
'1/2'
s = 'same day'
a_list = [c for c in s if c not in 'aeiou']
s = ''.join(a_list)
s
'sm dy'
s = 'same day'
s = s.replace('a', '').replace('e', '').replace('i', '').replace('o', '').replace('u', '')
s
'sm dy'
def calc_triangle_num(n):
s = 0
for i in range(n + 1):
s += i
return s
calc_triangle_num(10)
55
def calc_triangle_num(n):
return sum(range(n + 1))
calc_triangle_num(10)
55
def get_avg(a_list):
s = 0
for i in a_list:
s += i
return s / len(a_list)
get_avg([10, 20, 30, 40])
25.0
def get_avg(a_list):
return sum(a_list) / len(a_list)
get_avg([10, 20, 30, 40])
25.0
x = 55
if 0 < x and x < 100:
print('x is in range.')
x is in range.
if 0 < x < 100: # 연결된(chained) 비교 연산자 사용
print('x is in range.')
x is in range.
a, b, c = 5, 10, 15
if 0 < a <= c > b > 1:
print('All these comparisons are true!')
print('c is equal or greater than all the rest!')
All these comparisons are true! c is equal or greater than all the rest!
a = b = c = d = e = 100
if a == b == c == d == e:
print('All the variables are equal to each other.')
All the variables are equal to each other.
a_list = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ,1 ,1]
if min(a_list) == max(a_list):
print('All the elements are equal to each other.')
All the elements are equal to each other.
n = 1
def test(name='init'):
print('hello,', name)
do_plot = do_highlow_plot = do_volume_subplot = do_movingavg_plot = test
stockdf = 'insuk'
if n == 1:
do_plot(stockdf)
elif n == 2:
do_highlow_plot(stockdf)
elif n == 3:
do_volume_subplot(stockdf)
elif n == 4:
do_movingavg_plot(stockdf)
hello, insuk
n = 1
fn = [do_plot, do_highlow_plot, do_volume_subplot, do_movingavg_plot][n - 1]
fn(stockdf) # 함수 호출
hello, insuk
n = 1
f_list = [do_plot, do_highlow_plot, do_volume_subplot, do_movingavg_plot]
fn = f_list[n - 1]
fn(stockdf) # 함수 호출
hello, insuk
load_fn = save_fn = exit_fn = update_fn = test
menu_dict = {'load':load_fn, 'save':save_fn, 'exit':exit_fn, 'update':update_fn}
selector = 'exit'
(menu_dict[selector])() # 함수 호출
hello, init
a = 'cat'
b = 'cat'
a == b # 반드시 True 반환
True
s1 = 'I am what I am and that is all that I am.'
s2 = 'I am what I am' + ' and that is all that I am.'
s1 == s2
True
s1 is s2
False
def my_function():
return None
a_value = my_function()
if a_value is None: # 이곳에 if a_value == None 은 불가!!!
# None이 반환되면 특별한 행동을 취해라.
print('a_value 함수의 반환값은 None이다.')
a_value 함수의 반환값은 None이다.
for i in range(10): print(i, end=' ')
0 1 2 3 4 5 6 7 8 9
for i in range(5): n=i*2; m = 5; print(n+m, end=' ')
5 7 9 11 13
a = 1; b = 2; c = a + b; print(c)
3
turn = 0
if turn % 2:
cell = 'X'
else:
cell = 'O'
cell
'O'
cell = 'X' if turn % 2 else 'O'
cell
'O'
red = 0
blue = 1
green = 2
black = 3
white = 4
print(red, blue, green, black, white)
0 1 2 3 4
red, blue, green, black, white = range(5)
print(red, blue, green, black, white)
0 1 2 3 4
red, blue, green, black, white = range(1, 6)
print(red, blue, green, black, white)
1 2 3 4 5
import enum
help(enum)
Help on module enum: NAME enum MODULE REFERENCE https://docs.python.org/3.9/library/enum The following documentation is automatically generated from the Python source files. It may be incomplete, incorrect or include features that are considered implementation detail and may vary between Python implementations. When in doubt, consult the module reference at the location listed above. CLASSES builtins.int(builtins.object) IntEnum(builtins.int, Enum) IntFlag(builtins.int, Flag) builtins.object Enum Flag IntFlag(builtins.int, Flag) IntEnum(builtins.int, Enum) auto builtins.type(builtins.object) EnumMeta class Enum(builtins.object) | Enum(value, names=None, *, module=None, qualname=None, type=None, start=1) | | Generic enumeration. | | Derive from this class to define new enumerations. | | Data descriptors defined here: | | name | The name of the Enum member. | | value | The value of the Enum member. | | ---------------------------------------------------------------------- | Readonly properties inherited from EnumMeta: | | __members__ | Returns a mapping of member name->value. | | This mapping lists all enum members, including aliases. Note that this | is a read-only view of the internal mapping. class EnumMeta(builtins.type) | EnumMeta(cls, bases, classdict) | | Metaclass for Enum | | Method resolution order: | EnumMeta | builtins.type | builtins.object | | Methods defined here: | | __bool__(self) | classes/types should always be True. | | __call__(cls, value, names=None, *, module=None, qualname=None, type=None, start=1) | Either returns an existing member, or creates a new enum class. | | This method is used both when an enum class is given a value to match | to an enumeration member (i.e. Color(3)) and for the functional API | (i.e. Color = Enum('Color', names='RED GREEN BLUE')). | | When used for the functional API: | | `value` will be the name of the new class. | | `names` should be either a string of white-space/comma delimited names | (values will start at `start`), or an iterator/mapping of name, value pairs. | | `module` should be set to the module this class is being created in; | if it is not set, an attempt to find that module will be made, but if | it fails the class will not be picklable. | | `qualname` should be set to the actual location this class can be found | at in its module; by default it is set to the global scope. If this is | not correct, unpickling will fail in some circumstances. | | `type`, if set, will be mixed in as the first base class. | | __contains__(cls, member) | | __delattr__(cls, attr) | Implement delattr(self, name). | | __dir__(self) | Specialized __dir__ implementation for types. | | __getattr__(cls, name) | Return the enum member matching `name` | | We use __getattr__ instead of descriptors or inserting into the enum | class' __dict__ in order to support `name` and `value` being both | properties for enum members (which live in the class' __dict__) and | enum members themselves. | | __getitem__(cls, name) | | __iter__(cls) | | __len__(cls) | | __repr__(cls) | Return repr(self). | | __reversed__(cls) | | __setattr__(cls, name, value) | Block attempts to reassign Enum members. | | A simple assignment to the class namespace only changes one of the | several possible ways to get an Enum member from the Enum class, | resulting in an inconsistent Enumeration. | | ---------------------------------------------------------------------- | Class methods defined here: | | __prepare__(cls, bases) from builtins.type | __prepare__() -> dict | used to create the namespace for the class statement | | ---------------------------------------------------------------------- | Static methods defined here: | | __new__(metacls, cls, bases, classdict) | Create and return a new object. See help(type) for accurate signature. | | ---------------------------------------------------------------------- | Readonly properties defined here: | | __members__ | Returns a mapping of member name->value. | | This mapping lists all enum members, including aliases. Note that this | is a read-only view of the internal mapping. | | ---------------------------------------------------------------------- | Methods inherited from builtins.type: | | __getattribute__(self, name, /) | Return getattr(self, name). | | __init__(self, /, *args, **kwargs) | Initialize self. See help(type(self)) for accurate signature. | | __instancecheck__(self, instance, /) | Check if an object is an instance. | | __sizeof__(self, /) | Return memory consumption of the type object. | | __subclasscheck__(self, subclass, /) | Check if a class is a subclass. | | __subclasses__(self, /) | Return a list of immediate subclasses. | | mro(self, /) | Return a type's method resolution order. | | ---------------------------------------------------------------------- | Data descriptors inherited from builtins.type: | | __abstractmethods__ | | __dict__ | | __text_signature__ | | ---------------------------------------------------------------------- | Data and other attributes inherited from builtins.type: | | __base__ = <class 'type'> | type(object_or_name, bases, dict) | type(object) -> the object's type | type(name, bases, dict) -> a new type | | | __bases__ = (<class 'type'>,) | | __basicsize__ = 880 | | __dictoffset__ = 264 | | __flags__ = 2148292096 | | __itemsize__ = 40 | | __mro__ = (<class 'enum.EnumMeta'>, <class 'type'>, <class 'object'>) | | __weakrefoffset__ = 368 class Flag(Enum) | Flag(value, names=None, *, module=None, qualname=None, type=None, start=1) | | Support for flags | | Method resolution order: | Flag | Enum | builtins.object | | Data descriptors inherited from Enum: | | name | The name of the Enum member. | | value | The value of the Enum member. | | ---------------------------------------------------------------------- | Readonly properties inherited from EnumMeta: | | __members__ | Returns a mapping of member name->value. | | This mapping lists all enum members, including aliases. Note that this | is a read-only view of the internal mapping. class IntEnum(builtins.int, Enum) | IntEnum(value, names=None, *, module=None, qualname=None, type=None, start=1) | | Enum where members are also (and must be) ints | | Method resolution order: | IntEnum | builtins.int | Enum | builtins.object | | Data descriptors inherited from Enum: | | name | The name of the Enum member. | | value | The value of the Enum member. | | ---------------------------------------------------------------------- | Readonly properties inherited from EnumMeta: | | __members__ | Returns a mapping of member name->value. | | This mapping lists all enum members, including aliases. Note that this | is a read-only view of the internal mapping. class IntFlag(builtins.int, Flag) | IntFlag(value, names=None, *, module=None, qualname=None, type=None, start=1) | | Support for integer-based Flags | | Method resolution order: | IntFlag | builtins.int | Flag | Enum | builtins.object | | Data descriptors inherited from Enum: | | name | The name of the Enum member. | | value | The value of the Enum member. | | ---------------------------------------------------------------------- | Readonly properties inherited from EnumMeta: | | __members__ | Returns a mapping of member name->value. | | This mapping lists all enum members, including aliases. Note that this | is a read-only view of the internal mapping. class auto(builtins.object) | Instances are replaced with an appropriate value in Enum class suites. | | Data descriptors defined here: | | __dict__ | dictionary for instance variables (if defined) | | __weakref__ | list of weak references to the object (if defined) | | ---------------------------------------------------------------------- | Data and other attributes defined here: | | value = <object object> FUNCTIONS unique(enumeration) Class decorator for enumerations ensuring unique member values. DATA __all__ = ['EnumMeta', 'Enum', 'IntEnum', 'Flag', 'IntFlag', 'auto', '... FILE /Users/yhhan/anaconda3/envs/minimal_rl/lib/python3.9/enum.py
from enum import Enum
class Color(Enum):
red = 1
blue = 2
a = Color.red
b = Color.blue
print(a, ":", a.value)
Color.red : 1
for i in range(20):
for j in range(40):
print('*', end='')
print()
**************************************** **************************************** **************************************** **************************************** **************************************** **************************************** **************************************** **************************************** **************************************** **************************************** **************************************** **************************************** **************************************** **************************************** **************************************** **************************************** **************************************** **************************************** **************************************** ****************************************
row_of_asterisks = '*' * 40
for i in range(20):
print(row_of_asterisks)
**************************************** **************************************** **************************************** **************************************** **************************************** **************************************** **************************************** **************************************** **************************************** **************************************** **************************************** **************************************** **************************************** **************************************** **************************************** **************************************** **************************************** **************************************** **************************************** ****************************************
row_of_asterisks = '*' * 40
s = ''
for i in range(20):
s += row_of_asterisks + '\n'
print(s)
**************************************** **************************************** **************************************** **************************************** **************************************** **************************************** **************************************** **************************************** **************************************** **************************************** **************************************** **************************************** **************************************** **************************************** **************************************** **************************************** **************************************** **************************************** **************************************** ****************************************
row_of_asterisks = '*' * 40
list_of_str = []
for i in range(20):
list_of_str.append(row_of_asterisks)
print('\n'.join(list_of_str))
**************************************** **************************************** **************************************** **************************************** **************************************** **************************************** **************************************** **************************************** **************************************** **************************************** **************************************** **************************************** **************************************** **************************************** **************************************** **************************************** **************************************** **************************************** **************************************** ****************************************
print('\n'.join(['*' * 40] * 20))
**************************************** **************************************** **************************************** **************************************** **************************************** **************************************** **************************************** **************************************** **************************************** **************************************** **************************************** **************************************** **************************************** **************************************** **************************************** **************************************** **************************************** **************************************** **************************************** ****************************************
CEO_salary = 1500000
CEO_salary = 1_500_000
CEO_salary
1500000
x = y = z = 100
print(x is y)
print(y is z)
True True
del x
y = 200
z = 300
!python test.py
python: can't open file '/Users/yhhan/git/supercharged_python/test.py': [Errno 2] No such file or directory
!python -V
Python 3.9.0
!conda install numpy
Collecting package metadata (repodata.json): done Solving environment: done ==> WARNING: A newer version of conda exists. <== current version: 4.8.0 latest version: 4.10.3 Please update conda by running $ conda update -n base -c defaults conda ## Package Plan ## environment location: /Users/yhhan/anaconda3/envs/minimal_rl added / updated specs: - numpy The following packages will be downloaded: package | build ---------------------------|----------------- ca-certificates-2021.9.30 | hecd8cb5_1 123 KB certifi-2021.10.8 | py39hecd8cb5_0 155 KB numpy-1.21.2 | py39h0fa1045_0 22 KB numpy-base-1.21.2 | py39hbbe2e76_0 5.8 MB ------------------------------------------------------------ Total: 6.1 MB The following NEW packages will be INSTALLED: blas pkgs/main/osx-64::blas-1.0-openblas numpy-base pkgs/main/osx-64::numpy-base-1.21.2-py39hbbe2e76_0 The following packages will be UPDATED: ca-certificates 2021.7.5-hecd8cb5_1 --> 2021.9.30-hecd8cb5_1 certifi 2021.5.30-py39hecd8cb5_0 --> 2021.10.8-py39hecd8cb5_0 The following packages will be SUPERSEDED by a higher-priority channel: numpy conda-forge::numpy-1.21.2-py39h7eed0a~ --> pkgs/main::numpy-1.21.2-py39h0fa1045_0 Proceed ([y]/n)? ^C CondaSystemExit: Operation aborted. Exiting.
!pip install numpy
Requirement already satisfied: numpy in /Users/yhhan/anaconda3/envs/minimal_rl/lib/python3.9/site-packages (1.21.2)
def quad(a, b, c):
'''Quadratic Formula function.
This function applies the Quadratic Formula
to determine the roots of x in a quadratic
equation of the form ax^2 + bx + c = 0.
'''
determin = (b * b - 4 * a * c) ** .5
x1 = (-b + determin) / (2 * a)
x2 = (-b - determin) / (2 * a)
return x1, x2
help(quad)
Help on function quad in module __main__: quad(a, b, c) Quadratic Formula function. This function applies the Quadratic Formula to determine the roots of x in a quadratic equation of the form ax^2 + bx + c = 0.
def quad(a, b, c):
'''Quadratic Formula function.
This function applies the Quadratic Formula
to determine the roots of x in a quadratic
equation of the form ax^2 + bx + c = 0.
'''
determin = (b * b - 4 * a * c) ** .5
x1 = (-b + determin) / (2 * a)
x2 = (-b - determin) / (2 * a)
return x1, x2
help(quad)
Help on function quad in module __main__: quad(a, b, c) Quadratic Formula function. This function applies the Quadratic Formula to determine the roots of x in a quadratic equation of the form ax^2 + bx + c = 0.
!python -m pydoc queens
No Python documentation found for 'queens'. Use help() to get the interactive help utility. Use help(str) for help on the str class.
import math
help(math)
Help on module math: NAME math MODULE REFERENCE https://docs.python.org/3.9/library/math The following documentation is automatically generated from the Python source files. It may be incomplete, incorrect or include features that are considered implementation detail and may vary between Python implementations. When in doubt, consult the module reference at the location listed above. DESCRIPTION This module provides access to the mathematical functions defined by the C standard. FUNCTIONS acos(x, /) Return the arc cosine (measured in radians) of x. The result is between 0 and pi. acosh(x, /) Return the inverse hyperbolic cosine of x. asin(x, /) Return the arc sine (measured in radians) of x. The result is between -pi/2 and pi/2. asinh(x, /) Return the inverse hyperbolic sine of x. atan(x, /) Return the arc tangent (measured in radians) of x. The result is between -pi/2 and pi/2. atan2(y, x, /) Return the arc tangent (measured in radians) of y/x. Unlike atan(y/x), the signs of both x and y are considered. atanh(x, /) Return the inverse hyperbolic tangent of x. ceil(x, /) Return the ceiling of x as an Integral. This is the smallest integer >= x. comb(n, k, /) Number of ways to choose k items from n items without repetition and without order. Evaluates to n! / (k! * (n - k)!) when k <= n and evaluates to zero when k > n. Also called the binomial coefficient because it is equivalent to the coefficient of k-th term in polynomial expansion of the expression (1 + x)**n. Raises TypeError if either of the arguments are not integers. Raises ValueError if either of the arguments are negative. copysign(x, y, /) Return a float with the magnitude (absolute value) of x but the sign of y. On platforms that support signed zeros, copysign(1.0, -0.0) returns -1.0. cos(x, /) Return the cosine of x (measured in radians). cosh(x, /) Return the hyperbolic cosine of x. degrees(x, /) Convert angle x from radians to degrees. dist(p, q, /) Return the Euclidean distance between two points p and q. The points should be specified as sequences (or iterables) of coordinates. Both inputs must have the same dimension. Roughly equivalent to: sqrt(sum((px - qx) ** 2.0 for px, qx in zip(p, q))) erf(x, /) Error function at x. erfc(x, /) Complementary error function at x. exp(x, /) Return e raised to the power of x. expm1(x, /) Return exp(x)-1. This function avoids the loss of precision involved in the direct evaluation of exp(x)-1 for small x. fabs(x, /) Return the absolute value of the float x. factorial(x, /) Find x!. Raise a ValueError if x is negative or non-integral. floor(x, /) Return the floor of x as an Integral. This is the largest integer <= x. fmod(x, y, /) Return fmod(x, y), according to platform C. x % y may differ. frexp(x, /) Return the mantissa and exponent of x, as pair (m, e). m is a float and e is an int, such that x = m * 2.**e. If x is 0, m and e are both 0. Else 0.5 <= abs(m) < 1.0. fsum(seq, /) Return an accurate floating point sum of values in the iterable seq. Assumes IEEE-754 floating point arithmetic. gamma(x, /) Gamma function at x. gcd(*integers) Greatest Common Divisor. hypot(...) hypot(*coordinates) -> value Multidimensional Euclidean distance from the origin to a point. Roughly equivalent to: sqrt(sum(x**2 for x in coordinates)) For a two dimensional point (x, y), gives the hypotenuse using the Pythagorean theorem: sqrt(x*x + y*y). For example, the hypotenuse of a 3/4/5 right triangle is: >>> hypot(3.0, 4.0) 5.0 isclose(a, b, *, rel_tol=1e-09, abs_tol=0.0) Determine whether two floating point numbers are close in value. rel_tol maximum difference for being considered "close", relative to the magnitude of the input values abs_tol maximum difference for being considered "close", regardless of the magnitude of the input values Return True if a is close in value to b, and False otherwise. For the values to be considered close, the difference between them must be smaller than at least one of the tolerances. -inf, inf and NaN behave similarly to the IEEE 754 Standard. That is, NaN is not close to anything, even itself. inf and -inf are only close to themselves. isfinite(x, /) Return True if x is neither an infinity nor a NaN, and False otherwise. isinf(x, /) Return True if x is a positive or negative infinity, and False otherwise. isnan(x, /) Return True if x is a NaN (not a number), and False otherwise. isqrt(n, /) Return the integer part of the square root of the input. lcm(*integers) Least Common Multiple. ldexp(x, i, /) Return x * (2**i). This is essentially the inverse of frexp(). lgamma(x, /) Natural logarithm of absolute value of Gamma function at x. log(...) log(x, [base=math.e]) Return the logarithm of x to the given base. If the base not specified, returns the natural logarithm (base e) of x. log10(x, /) Return the base 10 logarithm of x. log1p(x, /) Return the natural logarithm of 1+x (base e). The result is computed in a way which is accurate for x near zero. log2(x, /) Return the base 2 logarithm of x. modf(x, /) Return the fractional and integer parts of x. Both results carry the sign of x and are floats. nextafter(x, y, /) Return the next floating-point value after x towards y. perm(n, k=None, /) Number of ways to choose k items from n items without repetition and with order. Evaluates to n! / (n - k)! when k <= n and evaluates to zero when k > n. If k is not specified or is None, then k defaults to n and the function returns n!. Raises TypeError if either of the arguments are not integers. Raises ValueError if either of the arguments are negative. pow(x, y, /) Return x**y (x to the power of y). prod(iterable, /, *, start=1) Calculate the product of all the elements in the input iterable. The default start value for the product is 1. When the iterable is empty, return the start value. This function is intended specifically for use with numeric values and may reject non-numeric types. radians(x, /) Convert angle x from degrees to radians. remainder(x, y, /) Difference between x and the closest integer multiple of y. Return x - n*y where n*y is the closest integer multiple of y. In the case where x is exactly halfway between two multiples of y, the nearest even value of n is used. The result is always exact. sin(x, /) Return the sine of x (measured in radians). sinh(x, /) Return the hyperbolic sine of x. sqrt(x, /) Return the square root of x. tan(x, /) Return the tangent of x (measured in radians). tanh(x, /) Return the hyperbolic tangent of x. trunc(x, /) Truncates the Real x to the nearest Integral toward 0. Uses the __trunc__ magic method. ulp(x, /) Return the value of the least significant bit of the float x. DATA e = 2.718281828459045 inf = inf nan = nan pi = 3.141592653589793 tau = 6.283185307179586 FILE /Users/yhhan/anaconda3/envs/minimal_rl/lib/python3.9/lib-dynload/math.cpython-39-darwin.so
math.sqrt(2)
1.4142135623730951
math.atan(1) * 4
3.141592653589793
math.pi
3.141592653589793
import matplotlib.pyplot as plt
from math import pi
print(pi)
3.141592653589793
from math import *
print(pi)
print(sqrt(2))
3.141592653589793 1.4142135623730951
일급 객체는 OOP에서 사용되는 개념 중 하나로 아래의 조건을 만족하는 객체를 의미함
def avg(a_list):
'''리스트 항목들의 평균값을 반환한다'''
x = (sum(a_list) / len(a_list))
print('The average is:', x)
return x
type(avg)
function
help(avg)
Help on function avg in module __main__: avg(a_list) 리스트 항목들의 평균값을 반환한다
def new_func(a_list):
return (sum(a_list) / len(a_list))
old_avg = avg
avg = new_func
old_avg([4, 6])
The average is: 5.0
5.0
def func_info(func):
print('Function name:', func.__name__)
print('Function documentation:')
help(func)
func_info(old_avg)
Function name: avg Function documentation: Help on function avg in module __main__: avg(a_list) 리스트 항목들의 평균값을 반환한다
def my_var_func(*args):
print('The number of args is', len(args))
print('The type of args is', type(args))
for item in args:
print(item)
my_var_func(10, 20, 30, 40)
The number of args is 4 The type of args is <class 'tuple'> 10 20 30 40
def avg(*args):
return sum(args)/len(args)
avg(11, 22, 33)
22.0
avg(1, 2)
1.5
def avg(units, *args):
print (sum(args)/len(args), units)
avg('inches', 11, 22, 33)
22.0 inches
ls = [1, 2, 3] # 언팩된 리스트
print(*ls) # 언팩 버전 출력하기
1 2 3
print(ls) # 패킹된 버전 출력하기 (일반 리스트)
[1, 2, 3]
print(10, 20, 30, end='.', sep=',')
10,20,30.
def pr_named_vals(**kwargs):
print("The length of kwargs is", len(kwargs))
print("The type of kwargs is", type(kwargs))
for k in kwargs:
print(k, ':', kwargs[k])
pr_named_vals(a=10, b=20, c=30)
The length of kwargs is 3 The type of kwargs is <class 'dict'> a : 10 b : 20 c : 30
def pr_vals_2(*args, **kwargs):
for i in args:
print(i)
for k in kwargs:
print(k, ':', kwargs[k])
pr_vals_2(1, 2, 3, -4, a=100, b=200)
1 2 3 -4 a : 100 b : 200
import time
def make_timer_wrapper(func):
def wrapper():
t1 = time.time()
ret_val = func()
t2 = time.time()
print('소요 시간 :', t2 - t1)
return ret_val
return wrapper
def count_nums():
s = 0
for i in range(10):
for j in range(1000):
s += i * j
return s
count_nums = make_timer_wrapper(count_nums)
count_nums()
소요 시간 : 0.0006380081176757812
22477500
import time
def make_timer_wrapper(func):
def wrapper(*args, **kwargs):
t1 = time.time()
ret_val = func(*args, **kwargs)
t2 = time.time()
print('소요 시간 :', t2 - t1)
return ret_val
return wrapper
def count_nums(n):
s = 0
for i in range(n):
for j in range(1000):
s += i * j
return s
count_nums = make_timer_wrapper(count_nums)
count_nums(10)
소요 시간 : 0.0006289482116699219
22477500
@make_timer_wrapper
def count_nums(n):
s = 0
for i in range(n):
for j in range(1000):
s += i * j
return s
count_nums(10)
소요 시간 : 0.000682830810546875
22477500
def decoratorExample(func):
def wrapFunc(*args, **kargs):
print("Start", func.__name__)
func(*args, **kargs)
print("End", func.__name__)
return wrapFunc
@decoratorExample
def test(a, b, c):
print("Variables :", a,b,c)
test("1", 2, c="345")
Start test Variables : 1 2 345 End test
def smart_divide(func):
def inner(a, b):
print("I am going to divide", a, "and", b)
if b == 0:
print("Whoops! cannot divide")
return
return func(a, b)
return inner
@smart_divide
def divide(a, b):
print(a / b)
divide(2, 5)
I am going to divide 2 and 5 0.4
divide(2, 0)
I am going to divide 2 and 0 Whoops! cannot divide
이터레이터 객체 정의
임의의 객체에 대해 반복자 객체를 얻어오는 방법
집합적 객체 A --> iter(A) --> 반복자 객체 B 반환 --> next(B) --> 집합적 자료형 안의 내부 원소를 하나씩 반환
I = iter([1, 2, 3])
print(I)
<list_iterator object at 0x7f9ac8b45c18>
print(next(I))
print(next(I))
print(next(I))
print(next(I))
1 2 3
--------------------------------------------------------------------------- StopIteration Traceback (most recent call last) <ipython-input-2-a2181eb3f09a> in <module> 2 print(next(I)) 3 print(next(I)) ----> 4 print(next(I)) 5 StopIteration:
def f(x):
print(x + 1)
t = iter([1, 2, 3])
while True:
try:
x = next(t)
except StopIteration:
break
f(x)
2 3 4
def f(x):
print(x + 1)
for x in [1, 2, 3]:
f(x)
2 3 4
iter1 = reversed([1, 2, 3, 4])
print(iter1)
<list_reverseiterator object at 0x7f9a78022438>
print(list(iter1))
[4, 3, 2, 1]
iter1 = reversed([1, 2, 3, 4])
for i in iter1:
print(i, end=' ')
4 3 2 1
def f(x):
print(x + 1)
t = iter([1, 2, 3])
for x in t:
f(x)
2 3 4
def f(x):
print(x + 1)
for x in iter([1, 2, 3]):
f(x)
2 3 4
def f(x):
print(x + 1)
for x in iter((1, 2, 3)):
f(x)
2 3 4
d = {'one':1, 'two':2, 'three':3, 'four':4, 'five':5}
for key in d:
print(key, d[key])
one 1 two 2 three 3 four 4 five 5
d = {'one':1, 'two':2, 'three':3, 'four':4, 'five':5}
for key in iter(d):
print(key, d[key])
one 1 two 2 three 3 four 4 five 5
print(type(d.keys()))
print(type(iter(d.keys())))
<class 'dict_keys'> <class 'dict_keyiterator'>
next(d.keys())
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-14-13463cadfc2a> in <module> 1 ----> 2 next(d.keys()) 3 TypeError: 'dict_keys' object is not an iterator
next(iter(d.keys()))
'one'
for key in d.keys(): # 키에 대한 반복자, iter(d.keys()) 가 반환한 반복자에 대해 __next__(self) 함수가 순차적으로 불리워짐
print(key, end=" ")
print()
for key in iter(d.keys()): # 키에 대한 반복자, iter(d.keys()) 가 반환한 반복자에 대해 __next__(self) 함수가 순차적으로 불리워짐
print(key, end=" ")
one two three four five one two three four five
keyset = iter(d)
print(next(keyset)) # 반복자 객체는 항상 next() 내장 함수에 값을 반환할 수 있음 (내부적으로 __next__(self) 호출)
for key in keyset: # keyset 반복자에 대해 next() 메소드가 순차적으로 호출됨
print(key, end=" ")
one two three four five
print(type(d.values()))
print(type(iter(d.values())))
<class 'dict_values'> <class 'dict_valueiterator'>
for key in d.values(): # 키에 대한 반복자, iter(d.keys()) 가 반환한 반복자에 대해 __next__(self) 함수가 순차적으로 불리워짐
print(key, end=" ")
print()
for key in iter(d.values()): # 키에 대한 반복자, iter(d.keys()) 가 반환한 반복자에 대해 __next__(self) 함수가 순차적으로 불리워짐
print(key, end=" ")
1 2 3 4 5 1 2 3 4 5
print(type(d.items()))
print(type(iter(d.items())))
<class 'dict_items'> <class 'dict_itemiterator'>
for key, value in d.items():
print(key, value, end=" ")
print()
for key, value in iter(d.items()):
print(key, value, end=" ")
one 1 two 2 three 3 four 4 five 5 one 1 two 2 three 3 four 4 five 5
f = open('readme.txt')
print(next(f))
for line in f: # f.next() 가 순차적으로 호출됨
print(line)
abc def ghi
def f(a, b):
c = a * b
d = a + b
return c, d
x, y = f(1, 2)
print(x, y)
2 3
yield 키워드
발생자는 곧 반복자이다!!!
def f(a, b):
c = a * b
d = a + b
yield c, d
g = f(1, 2)
x, y = next(g)
print(x, y)
x, y = next(g)
print(x, y)
2 3
--------------------------------------------------------------------------- StopIteration Traceback (most recent call last) <ipython-input-28-43965b3e1aa9> in <module> 10 print(x, y) 11 ---> 12 x, y = next(g) 13 print(x, y) 14 StopIteration:
def f(a, b):
for _ in range(2):
c = a * b
d = a + b
yield c, d
g = f(1, 2)
x, y = next(g)
print(x, y)
x, y = next(g)
print(x, y)
발생자 함수와 일반 함수의 차이점
발생자가 유용하게 사용되는 경우
def print_evens():
for n in range(2, 11, 2):
print(n)
print_evens()
2 4 6 8 10
def make_evens_gen():
for n in range(2, 11, 2):
yield n
my_gen = make_evens_gen()
next(my_gen)
2
next(my_gen)
4
next(my_gen)
6
my_gen = make_evens_gen() # 다시 시작
next(my_gen)
2
next(my_gen)
4
next(my_gen)
6
my_gen = make_evens_gen() # 다시 시작
next(my_gen)
2
next(my_gen)
4
next(my_gen)
6
next(make_evens_gen())
2
next(make_evens_gen())
2
next(make_evens_gen())
2
for i in make_evens_gen():
print(i, end=' ')
2 4 6 8 10
my_gen = make_evens_gen()
for i in my_gen:
print(i, end=' ')
2 4 6 8 10
my_gen = make_evens_gen()
a_list = list(my_gen)
a_list
[2, 4, 6, 8, 10]
a_list = list(my_gen) # 앗! 다시 초기화(reset)를 안했군!
a_list
[]
a_list = list(make_evens_gen())
a_list
[2, 4, 6, 8, 10]
def make_fibo_gen(n):
a, b = 1, 1
while a <= n:
yield a
a, b = a + b, a
my_fibo_gen = make_fibo_gen(10)
print(my_fibo_gen)
print(list(my_fibo_gen))
<generator object make_fibo_gen at 0x7f9ac8c15728> [1, 2, 3, 5, 8]
n = int(input('Enter number: '))
if n in make_fibo_gen(n):
print('number is a Fibonacci. ')
else:
print('number is not a Fibonacci. ')
number is not a Fibonacci.
n = int(input('Enter number: '))
my_fibo_gen = make_fibo_gen(n)
if n in my_fibo_gen:
print('number is a Fibonacci. ')
else:
print('number is not a Fibonacci. ')
number is a Fibonacci.
def generate_ints(N):
for i in range(N):
yield i
gen = generate_ints(3) # 발생자 객체를 얻는다. generate_ints() 함수에 대한 초기 스택 프레임이 만들어지나 실행은 중단되어 있는 상태임
print(gen)
# print(gen.next())
# print(gen.next())
# print(gen.next())
# print(gen.next())
print(next(gen)) # 발생자 객체는 반복자 인터페이스를 가진다. 발생자의 실행이 시작됨. yield에 의해 값 반환 후 실행이 중단됨
print(next(gen)) # 발생자 실행 재개. yield에 의해 값 반환 후 다시 중단
print(next(gen)) # 발생자 실행 재개. yield에 의해 값 반환 후 다시 중단
print(next(gen)) # 발생자 실행 재개. yield에 의해 더 이상 반환할 값이 없다면 StopIteration 예외를 던짐
<generator object generate_ints at 0x7f9ac8c15938> 0 1 2
--------------------------------------------------------------------------- StopIteration Traceback (most recent call last) <ipython-input-65-78d70db003e1> in <module> 11 print(next(gen)) # 발생자 실행 재개. yield에 의해 값 반환 후 다시 중단 12 print(next(gen)) # 발생자 실행 재개. yield에 의해 값 반환 후 다시 중단 ---> 13 print(next(gen)) # 발생자 실행 재개. yield에 의해 더 이상 반환할 값이 없다면 StopIteration 예외를 던짐 14 StopIteration:
for i in generate_ints(5):
print(i, end=" ")
0 1 2 3 4
a = [k for k in range(100) if k % 5 == 0]
print(a)
type(a)
[0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95]
list
a = (k for k in range(100) if k % 5 == 0)
print(a)
type(a)
<generator object <genexpr> at 0x7f9ac8c15a98>
generator
print(next(a))
print(next(a))
print(next(a))
for i in a:
print(i, end=" ")
0 5 10 15 20 25 30 35 40 45 50 55 60 65 70 75 80 85 90 95
a = (k for k in range(100) if k % 5 == 0)
print(sum(a))
950
def fibonacci(a = 1, b = 1):
while 1:
yield a
a, b = b, a + b
for k in fibonacci(): # 발생자를 직접 for ~ in 구문에 활용
if k > 100:
break
print(k, end=" ")
1 1 2 3 5 8 13 21 34 55 89
def odds(limit=None):
k = 1
while not limit or limit >= k:
yield k
k += 2
for k in odds(20):
print(k, end=" ")
print()
print(list(odds(20))) # list() 내장 함수가 발생자를 인수로 받으면 해당 발생자의 next()를 매번 호출하여 각 원소를 얻어온다.
1 3 5 7 9 11 13 15 17 19 [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
import sys
import sys
for thing in sys.argv:
print(thing, end='||||')
/Users/yhhan/anaconda3/lib/python3.6/site-packages/ipykernel_launcher.py||||-f||||/Users/yhhan/Library/Jupyter/runtime/kernel-47b361ac-2964-463e-afaf-ef9133d4ae86.json||||
phone = {'a': [1,2,3], 'b': 4}
phone2 = phone.copy()
print(phone)
print(phone2)
print()
phone['b'] = 100
print(phone)
print(phone2)
print()
phone['a'][0] = 100
print(phone)
print(phone2)
{'a': [1, 2, 3], 'b': 4} {'a': [1, 2, 3], 'b': 4} {'a': [1, 2, 3], 'b': 100} {'a': [1, 2, 3], 'b': 4} {'a': [100, 2, 3], 'b': 100} {'a': [100, 2, 3], 'b': 4}