Skip to content

Instantly share code, notes, and snippets.

@ph87
ph87 / permutations.py
Created June 20, 2017 14:40
from python itertools
def permutations(iterable, r=None):
# permutations('ABCD', 2) --> AB AC AD BA BC BD CA CB CD DA DB DC
# permutations(range(3)) --> 012 021 102 120 201 210
pool = tuple(iterable)
n = len(pool)
r = n if r is None else r
if r > n:
return
indices = range(n)
cycles = range(n, n-r, -1)
@ph87
ph87 / deadlock.py
Created May 31, 2017 10:07
死锁示例
#!/usr/bin/env python
# encoding: utf-8
import time
def multi_acquire_worker(mutex):
''' 同一线程多次请求同一资源,直接造成死锁
为了解决在同一线程中多次请求同一资源,使用可重入锁 threading.RLock
def grep(pattern_str):
''' Using yield receive data inside generator
:param pattern_str: rex string
Demo::
>>> finder = grep('target \d+')
>>> next(finder)
>>> print(finder.send('target 1234'))
target 1234
@ph87
ph87 / map_reduce.scala
Last active May 1, 2017 17:02
A map reduce based product currying
object exercise {
def mapReduce(
func: Int=>Int, combine: (Int, Int) => Int, zero: Int
)(a: Int, b: Int): Int = {
if (a > b) zero
else combine(
func(a),
mapReduce(func, combine, zero)(a + 1, b)
)
}
@ph87
ph87 / recfun_Main.scala
Last active April 23, 2017 15:09
Functional Programming in Scala, Course 1, Exercises
package recfun
object Main {
def main(args: Array[String]) {
println("Pascal's Triangle")
for (row <- 0 to 10) {
for (col <- 0 to row)
print(pascal(col, row) + " ")
println()
}
@ph87
ph87 / vimrc
Last active April 16, 2017 16:06
保存 python 文件时执行测试
autocmd BufWritePost *.py exec ":call PyFlakeTest()"
function! PyFlakeTest()
silent exec "!flake8 % > /dev/null"
if v:shell_error
echohl ErrorMsg
echomsg "不好!有毛病!"
exec "!flake8 %"
echohl None
endif
endfunc
import sys
data = {}
for i in xrange(0, 1000000):
lst.append(i)
size = sys.getsizeof(list)
if data.get(size):
pass
else:
data[size] = i
rev_data = {i[1]: i[0] for i in data.items()}
@ph87
ph87 / merge_sort.py
Last active January 19, 2017 11:37
implementation of merge sorting
from unittest import (
main,
TestCase,
)
from random import Random
def merge(lst):
if len(lst) <= 1:
return lst
import re
import logging
from logging import handlers as logging_handlers
import email
from email.parser import Parser
from email.header import decode_header
from email.utils import parseaddr
from StringIO import StringIO
logger = logging.getLogger(__name__)
@ph87
ph87 / v2ex_309785.py
Last active October 1, 2016 10:06
A script handle the quiz from https://www.v2ex.com/t/309785
from md5 import md5
PREFIX = 'v2ex'
LETTERS = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'
TARGET = '3bed22f7f496e84b035a996522baa7594c27c7e5718a78bfddf9012904b70eb755d67f90c8de149ead7ee674b024f38c216642030c2d54cb1dd657dd66342c99c239f3c31fd399fc052a9b7861f2073d2b9f47811dd77fd544d570c34bf5f349d110389979571714694a5054238465ca38ba26c25fb1a32b4d0a3b93666b09b3'
prefix_md5 = md5(PREFIX).hexdigest()