Skip to content

Instantly share code, notes, and snippets.

@ericzhong
ericzhong / binary_search.py
Last active May 17, 2017 11:47
二分查找
def binary_search(lst, num):
if num not in lst:
return None
last = len(lst)
first = 0
while(last>first):
mid = (last + first) / 2
if lst[mid] == num:
return mid
elif lst[mid] > num:
@ericzhong
ericzhong / count.py
Created May 17, 2017 12:28
统计列表中各元素出现的次数
def count(lst):
r = {}
for i in lst:
if i in r:
r[i] += 1
else:
r[i] = 1
return r
@ericzhong
ericzhong / concurrent.sh
Created May 19, 2017 10:17
Bash多进程
### run.sh ###
#!/bin/bash
for((n=0; n<2; n++))
do
./print.sh $n &
done
wait
@ericzhong
ericzhong / docker-compose.yml
Created May 20, 2017 14:46
Docker - 创建 MySQL 容器
version: '3'
services:
mysql:
image: mysql:latest
restart: always
ports:
- 3306:3306
environment:
MYSQL_ROOT_PASSWORD: 123
MYSQL_DATABASE: test
@ericzhong
ericzhong / partial-function.py
Created May 23, 2017 04:18
偏函数的原理
a = int('101', base=2)
from functools import partial
b2i = partial(int, base=2)
b = b2i('101')
def btoi(x, base=2):
return int(x, base)
from collections import Iterator
class Foo(Iterator):
def __init__(self, stop):
self.x = 0
self.stop = stop
def __iter__(self):
return self
def gen(stop):
for i in range(stop):
yield i
f = gen(10)
print(type(f))
for i in f:
print(i),
@ericzhong
ericzhong / generator-send.py
Created May 23, 2017 12:41
生成器 send() 方法
def gen(stop):
i = 0
while True:
if i >= stop:
raise StopIteration
i = (yield i) or i+1
g = gen(100)
print(next(g)) # Python 3 compatibility
print(next(g))
def log(func):
def foo():
print('call %s' % func.__name__)
return func()
return foo
@log
def test():
pass
@ericzhong
ericzhong / singleton.py
Created May 24, 2017 00:41
单例模式
# Method-1
class Foo(object):
__instance = None
def __new__(cls, *args, **kwargs):
if Foo.__instance is None:
Foo.__instance = object.__new__(cls, *args, **kwargs)
return Foo.__instance
a = Foo()
b = Foo()