Skip to content

Instantly share code, notes, and snippets.

# coding=UTF-8
a = "s"
b = "s"
print(id(a)) # python use string interning for short strings
print(id(b))
assert a is b
assert a == b
c = "x" * 100
# coding=UTF-8
i = 1
++i # <==> +(+i), no ++ operator in Python
assert i == 2 # AssertionError
# coding=UTF-8
# for...else...
def printPrime1(n):
for i in xrange(2, n):
found = False
for j in xrange(2, i):
if i % j == 0:
found = True
break
# coding=UTF-8
def lost_exception():
while True:
try:
print("hello world")
raise IndexError("rrr")
except NameError as e:
print 'NameError happened'
print e
# coding=UTF-8
class User(object):
def __init__(self, id):
self.id = id
def __nonzero__(self):
return self.id not in (None, 0)
@EdisonChendi
EdisonChendi / default_params.py
Created November 27, 2016 08:25
don't use mutable types as default parameters
# coding=UTF-8
def append(newitem, l = []):
l.append(newitem)
print(l)
print(append.func_defaults) # []
append(10)
print(append.func_defaults) # [10]
append(20)
@EdisonChendi
EdisonChendi / print_vs_repr.py
Created November 28, 2016 14:04
repr is for developers, print is for software users
# coding=UTF-8
class Engineer(object):
def __init__(self, name, specialty):
self.name = name
self.specialty = specialty
def __repr__(self):
# __repr__ is for developers
@EdisonChendi
EdisonChendi / master_str.py
Created December 9, 2016 15:38
mastering string manipulation is extremely important
# coding=UTF-8
import types
# multi-line string
def multi_line_str():
s = ('select * '
'from atable '
'where afiled="value"')
print(s)
# coding=UTF-8
import operator
engineers = [{"name": "John", "age": 28}, {"name": "Peter", "age": 20}, {"name": "Paul", "age": 33}]
engineers_sorted_by_age = sorted(engineers, key=operator.itemgetter("age"))
print(engineers_sorted_by_age)
print(engineers)
engineers.sort(key=operator.itemgetter("age"), reverse=True)
print(engineers)
@EdisonChendi
EdisonChendi / event.js
Last active January 6, 2017 06:50
A good example of using ES6 WeakMap
// https://github.com/hugeen/burst/blob/master/core/event.js
// http://stackoverflow.com/questions/29413222/what-are-the-actual-uses-of-es6-weakmap
// the main strength of WeakMap is that it does not interfere with garbage collection given that they do not keep a reference
var listenableMap = new WeakMap();
export function getListenable (object) {
if (!listenableMap.has(object)) {
listenableMap.set(object, {});
}