Skip to content

Instantly share code, notes, and snippets.

# 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
# 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
i = 1
++i # <==> +(+i), no ++ operator in Python
assert i == 2 # AssertionError
# 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
# py2
from __future__ import division
import types
# prefer isinstance to type
assert isinstance(10/2, types.FloatType)
# 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():
@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
@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 = ""
# 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 = ""