python small story collection

Introduction

I'm studying python, and the number of small stories has increased, so I'll briefly summarize it. Please forgive me, although some parts have not been investigated in depth.

List of small stories

Small story

I will explain in order from the top of the list.

Identity and equivalence

Identity means that the objects are the same, and equivalence means that the values are the same. Identity is evaluated by is, and equivalence is evaluated by `` = essentially. Now, let's check the result for each type.

int

-5 to 256 integers use the same object to save memory. Other integers are not the same even if they are equivalent.

a = 256
b = 256
a is b # True

c = 257
d = 257
c is d # False

e = -5
f = -5
e is f # True

g = -6
h = -6
g is h # False

float, long, complex

This behaves differently than an integer. Even if they are the same value, they are not the same because the stored memory is different.

a = 1.0
b = 1.0
a == b # True
a is b # False

a = 1L
a = 1L
a == b # True
a is b # False

a = 1 + 2j
b = 1 + 2j
a == b # True
a is b # False

bool

There is only one True / False.

a = True
b = True
a is b # True

a = False
b = False
a is b # True

By the way, bool is a subclass of int, and `False``` can be treated as` `0```, and True``` can be treated as `1```.

isinstance(False, bool) # True
isinstance(False, int) # True

False == 0 # True
False is 0 # False

True == 1 # True
True is 1 # False

True + True # 2

result = -1
'OK' if result == 0 else 'NG' # 'NG'
('NG', 'OK')[result == 0] # 'NG'
result = 0
('NG', 'OK')[result == 0] # 'OK'

string

Strings that do not contain special characters are the same because they are interned in the name list. If special characters such as spaces and operators are included, they are not the same even if they have the same value. However, if there is only one special character, it will be the same.

a = 'foo'
b = 'foo'
a == b # True
a is b # True

a = 'f o o'
b = 'f o o'
a == b # True
a is b # False

a = 'x+y'
b = 'x+y'
a == b # True
a is b # False

a = '/'
b = '/'
a == b # True
a is b # True

Also, it will not be the same in the following cases.

a = 'f'
a += 'oo'
b = 'foo'
a == b # True
a is b # False

list, tuple, dictionary

Like strings, list, tuple, and dictionary are not the same even if they have the same value.

a = [1, 2, 3]
b = [1, 2, 3]
a == b # True
a is b # False

a = (1, 2, 3)
b = (1, 2, 3)
a == b # True
a is b # False

a = {'x': 1, 'y': 2}
b = {'x': 1, 'y': 2}
a == b # True
a is b # False

set

set is a set with unique values. The feature is that there is no guarantee of order. Even if set has the same value, it is not the same.

a = set([1, 3, 2])
b = set([1, 3, 2])
c = set([1, 2, 3, 2])

a == b # True
a is b # False

a == c # True ->True because it does not retain order information and only unique values
a is c # False

Copy of list

As a caveat to list, if you copy using ```, changing one element will change the other element as well.

a = [1, 2, 3]
b = a
a[0] = [0, 0] # a: [[0, 0], 2, 3], b: [[0, 0], 2, 3] -> a[0]If you change b[0]Will also change

If you copy using slices, it will be a deep copy and you can prevent the above problem.

a = [1, 2, 3]
b = a[:]
a[0] = 0 # a: [0, 2, 3], b: [1, 2, 3] -> a[0]Only change
b[1] = 0 # a: [0, 2, 3], b: [1, 0, 3] -> b[1]Only change

By the way, the elements of string and tuple cannot be changed.

b = 'foo'
b[0] = 'h' # TypeError: 'str' object does not support item assignment

a = (1, 2, 3)
a[0] = 0 # TypeError: 'tuple' object does not support item assignment

A function that takes a function as an argument

In python, you can define a "function that takes a function as an argument".

def higher(func, x, y):
    return func(x, y)

def add(a, b):
    return a + b

def sub(a, b):
    return a - b

print higher(add, 4, 3) # 7
print higher(sub, 4, 3) # 1

By the way, using `lambda``` saves you the trouble of defining functions like ```add``` and `sub```.

def higher(func, x, y):
    return fun(x, y)

print higher(lambda a, b: a + b, 4, 3) # 7
print higher(lambda a, b: a - b, 4, 3) # 1

Function that returns a function

Define a function within a function and define it to return. Executing the outer function f will return _fin f. The returned _fis a function, so you can pass more values to execute it. Therefore, the execution method is as follows: f (1) (2)` ``.

def f(x):
    def _f(y):
        return x + y
    return _f

print f(1) # <function _f at 0x10e45b140>
print f(1)(2) # 3

Granting properties to functions

Since functions in python are objects, you can freely add properties. I didn't know how to use it. Please let me know.

def foo():
    return '!!!'

foo.x = 1
foo.y = 2
foo.f = lambda x: x + 1

print foo() # !!!
print foo.x # 1
print foo.y # 2.000000
print foo.f(9) # 10

Access restrictions

Python does not have a mechanism for restricting access like `private``` and protected``` found in C ++ and Java. Therefore, access restrictions are applied in a pseudo manner by adding an underscore at the beginning of the variable name or method name. In the case of one underscore, it can actually be called, but it indicates the intention of implementing it as a private method. In the case of two underscores, it cannot be called with the defined method name, and access is restricted. Strictly speaking, it's not that you can't call it, it's just that the method name has been changed to ``` _ (class name) __ (method name) . Therefore, it can be called in the form of ``` _ (class name) __ (method name)` .

class Foo(object):
    def __init__(self, x):
        self.x = x
    def f(self, y):
        return self.x + y
    def _f(self, y):
        return self.x + y + 1
    def __f(self, y):
        return self.x + y + 2

foo = Foo(1)
print foo.f(1) # 2
print foo._f(1) # 3
print foo.__f(1) # AttributeError: 'Foo' object has no attribute '__f'
print foo._Foo__f(1) # 4

division of int

The calculation of int $ \ div $ int in python 2.x is not "integer with decimal point truncated" but "maximum integer not exceeding the result of division". That's why it feels like.

print 1 / 2 # 0
print -1 / 2 # -1

By the way, in python 3.x, the calculation of int $ \ div $ int is a decimal. Also, to make python 3.x behave the same as python 2.x, use `//`.

//Is python 2.It can also be used with x.




#### **`Python3.x`**
```python

1 / 2 # 0.5
1 // 2 # 0
-1 / 2 # -0.5
-1 // 2 # -1

numpy small story

Everyone loves numpy.

One-dimensional array transformation

If you check the one-dimensional array with the number of elements $ n $ with `shape```, it will be ``` (n,) . Use `` reshapeto transform this into a row vector `` `(1, n) or a column vector (n, 1) `` `.

arr = numpy.arange(10) # array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
arr.shape # (10, )

arr.reshape((1, -1))
# array([[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]])

arr.reshape((-1, 1))
# array([[0],
#        [1],
#        [2],
#        [3],
#        [4],
#        [5],
#        [6],
#        [7],
#        [8],
#        [9]])

Inversion using slices

It can be flipped using slices. Slices are operated by (start index): (end index): (interval). Negative values refer to the index from the back.

[-1::-1]You can slice from the end to the beginning with.


 The first ``` -1``` can be omitted.

```py
X = numpy.arange(9).reshape((3, 3))
# array([[0, 1, 2],
#        [3, 4, 5],
#        [6, 7, 8]])

X[::-1, :]
# array([[6, 7, 8],
#        [3, 4, 5],
#        [0, 1, 2]])

X[:, ::-1]
# array([[2, 1, 0],
#        [5, 4, 3],
#        [8, 7, 6]])

vectorize

In numpy's universal functions, four arithmetic operations between ndarrays, trigonometric functions of each element, and functions that take logarithms are defined. Use vectorize to define a function that applies your own function to each element. For example, pass a function that returns the remainder when divided by 10 to vectorize, and pass ndarray to that function.

X = numpy.arange(25).reshape((5, 5))
# array([[ 0,  1,  2,  3,  4],
#        [ 5,  6,  7,  8,  9],
#        [10, 11, 12, 13, 14],
#        [15, 16, 17, 18, 19],
#        [20, 21, 22, 23, 24]])

numpy.vectorize(lambda x: x % 10)(X)
# array([[0, 1, 2, 3, 4],
#        [5, 6, 7, 8, 9],
#        [0, 1, 2, 3, 4],
#        [5, 6, 7, 8, 9],
#        [0, 1, 2, 3, 4]])

in conclusion

I tried to summarize the small story of python. Please let me know if there are other things like this. If you find something, I will add it as needed.

Additional information

Corrected by referring to the comments of @ Tsutomu-KKE @ github, @shiracamus, and @kochory. (2016/06/04)

Recommended Posts

python small story collection
App Service Small story collection
[Small story] Get timestamp with Python
python (3) dominer ORM collection
[Python] Sort collection types
[Small story] Test image generation with Python / OpenCV
[Small story] In Python, i = i + 1 is slightly faster than i + = 1.
[Small story] Synchronize with Python without multithreading (limited use)
Story when iterating python tuple
Stumble story with Python array
python snippet collection with cinema4d
GAE + python + Django addictive story
Image Processing Collection in Python
Small story: numpy flatten mechanism
[Small story] [Python] Replace strings in 2D arrays with numbers
The story of Python and the story of NaN
Perform Scala-like collection operations in Python
[Memo] Small story of pandas, numpy
Strange and horrifying Python error story
Story of power approximation by Python
Generate a first class collection in Python
Automatic collection of stock prices using python
The story of making Python an exe
[Python] Sorting collection types as a reference
The story of manipulating python global variables
Scientific Programming Petit Tech Collection in Python
A story about Python pop and append
ModuleNotFoundError in Python: No module named story
Tips for making small tools in python
The story of blackjack A processing (python)