Skip to content

Instantly share code, notes, and snippets.

@EdisonChendi
EdisonChendi / fizzbuzz_imperative_fancyfunctional.js
Last active August 29, 2015 14:26
try some functional js on FizzBuzz...
/*
* rely on underscore
*/
// ============ imperative ============
function fizzbuzz(arr) {
var i = 0,
len = arr.length,
curr = null;
for (; i < len; i++) {
@EdisonChendi
EdisonChendi / oneline_quicksort.py
Last active April 19, 2021 20:50
toy quick sort in python, just one line!
# -*- coding: UTF-8 -*-
quicksort = lambda l: quicksort([i for i in l[1:] if i < l[0]]) + [l[0]] + quicksort([j for j in l[1:] if j >= l[0]]) if l else []
## but readability counts
# def quicksort(l):
# if not l: return []
# pivot = l.pop()
# less = [i for i in l if i < pivot]
# greater = [j for j in l if j >= pivot]
@EdisonChendi
EdisonChendi / codedrinker.py
Created September 28, 2016 15:13
Code Drinker
# -*- coding: UTF-8 -*-
class ColaDrinker(object):
def __init__(self, money, cola_price, redeem_num):
self.cola_price = cola_price
self.redeem_num = redeem_num
self.bottles = 0
self.money = money
# coding=utf-8
def trunc(s, limit, coding="UTF-8", postfix="..."):
'''
works both on python2 and python3
'''
unicode_s = s.decode(coding) if type(s) == bytes else s
nums = (len(u.encode(coding)) for u in unicode_s)
sum, i = 0, 0
use_postfix = ""
# coding=utf-8
def trunc(s, limit, coding="UTF-8", postfix="..."):
'''
works both on python2 and python3
'''
unicode_s = s.decode(coding) if type(s) == bytes else s
nums = (len(u.encode(coding)) for u in unicode_s)
sum, i = 0, 0
use_postfix = ""
# coding=utf-8
def trunc(s, limit, coding="UTF-8", postfix="..."):
'''
works both on python2 and python3
'''
unicode_s = s.decode(coding) if type(s) == bytes else s
nums = (len(u.encode(coding)) for u in unicode_s)
sum, i = 0, 0
use_postfix = ""
@EdisonChendi
EdisonChendi / trunc.py
Last active October 20, 2016 05:15
sensibly trunc a str/bytes(py3) or str/unicode string(py2) to some limit by counting bytes
# coding=utf-8
def trunc(s, limit, coding="UTF-8", postfix="..."):
'''
sensibly trunc a str/bytes(py3) or str/unicode string(py2) to some limit by counting bytes
'''
unicode_s = s.decode(coding) if type(s) == bytes else s
nums = (len(u.encode(coding)) for u in unicode_s)
sum, i = 0, 0
use_postfix = ""
@EdisonChendi
EdisonChendi / fib.py
Created October 24, 2016 14:17
python lazy evaluation
# coding=utf-8
from itertools import islice
def fib():
a, b = 0, 1
while True:
yield a # lazy evaluation
a, b = b, a+b
# coding:utf-8
class _Const(object):
class ConstantError(TypeError): pass
def __setattr__(self, name, value):
if self.__dict__.has_key(name):
raise self.ConstantErrorr("can't change const value '%s'." % name)
if not name.isupper():
# coding=utf-8
# py2
from __future__ import division
import types
# prefer isinstance to type
assert isinstance(10/2, types.FloatType)