Skip to content

Instantly share code, notes, and snippets.

View ycflame's full-sized avatar
Trilingual Life

Bob ycflame

Trilingual Life
View GitHub Profile
@ycflame
ycflame / aggregation.py
Created May 5, 2014 14:30
MongoDB Aggregation
"""
Example collection data:
{
_id: “9991f84c4b0a110af3830012”,
name: “John Smith”,
brands: [“Nike”, “Asics”, “Adidas”]
}
{
_id: “9991f84c4b0a110af3830012”,
@ycflame
ycflame / infinite_iter.py
Created April 15, 2014 11:14
create an infinite iterator
"""
The built-in function iter() can be called with two arguments
where the first argument must be a callable object (function)
and second is the sentinel. The iterator calls this function
until the returned value is equal to the sentinel.
"""
inf = iter(int,1)
@ycflame
ycflame / list_concatenation.py
Created March 19, 2014 07:04
concatenate sublist in a list to one list
>>> list1, list2, list3 = [1,2,3], ['a','b','c'], [7,8,9]
>>> all_lists = sum([list1, list2, list3], [])
>>> all_lists
[1, 2, 3, 'a', 'b', 'c', 7, 8, 9]
"""
The expression x and y first evaluates x; if x is false, its value is returned; otherwise, y is evaluated and the resulting value is returned.
The expression x or y first evaluates x; if x is true, its value is returned; otherwise, y is evaluated and the resulting value is returned.
"""
In [3]: True and ['a']
Out[3]: ['a']
In [4]: False and ['a']
@ycflame
ycflame / method_resolution_order
Created February 12, 2014 09:01
identify your method
def find_defining_class(obj,meth_name):
for ty in type(obj).mro():
if meth_name in ty.__dict__:
return ty
Here's an example:
>>>hand=Hand()
>>>print find_defining_class(hand,'shuffle')
<class'Card.Deck'>
from math import sqrt
N = 100
result = [p for p in range(2, N) if 0 not in [p % d for d in range(2, int(sqrt(p)) + 1)]]
@ycflame
ycflame / no_punctuation.py
Created January 15, 2014 10:29
replace punctuations with space
import string
replace_punctuation = string.maketrans(string.punctuation, ' ' * len(string.punctuation))
line = line.translate(replace_punctuation)
@ycflame
ycflame / no_micro.py
Last active June 13, 2018 12:16
datetime.now() without microseconds
import datetime
datetime.datetime.now().replace(microsecond=0)