Skip to content

Instantly share code, notes, and snippets.

@gennad
gennad / factorials.py
Created May 28, 2011 11:27
Factorials in Python
#First year programmer, Python
def Factorial(x):
res = 1
for i in xrange(2, x + 1):
res *= i
return res
print Factorial(6)
#Lazy Python programmer
@gennad
gennad / classstatic.py
Created May 28, 2011 11:45
Class method vs Static method
"""
A staticmethod is a method that knows
nothing about the class or instance it was
called on. It just gets the arguments that were
passed, no implicit first argument. It is
basically useless in Python -- you can just
use a module function instead of a
staticmethod.
A classmethod, on the other hand, is a
@gennad
gennad / yield.py
Created May 28, 2011 11:45
List compr, generators and yield
mylist = [x*x for x in range(3)]
for i in mylist :
print(i)
# Generators can be read only once
mygenerator = (x*x for x in range(3))
for i in mygenerator :
print(i)
Yield is a keyword that is used like return, except the function will return a generator.
@gennad
gennad / pylogging.py
Created May 28, 2011 18:40
Python logging
import logging
logging.basicConfig(filename='example.log', level=logging.DEBUG)
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
# create console handler and set level to debug
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
# create formatter
@gennad
gennad / singletone.py
Created May 28, 2011 18:58
Singletone Python
class Singleton(type):
def __init__(cls, name, bases, dict):
super(Singleton, cls).__init__(name, bases, dict)
cls.instance = None
def __call__(cls,*args,**kw):
if cls.instance is None:
cls.instance = super(Singleton, cls).__call__(*args, **kw)
return cls.instance
class MyClass(object):
@gennad
gennad / wrapper.py
Created May 28, 2011 19:32
Wrapper
#-*- coding: utf-8 -*-
"""
Написать функцию-фабрику, которая будет возвращать функцию сложения с аргументом.
>>> add5 = addition(5) # функция addition возвращает функцию сложения с 5
>>> add5(3) # вернет 3 + 5 = 8
8
>>> add5(8) # вернет 8 + 5 = 13
13
@gennad
gennad / meta.py
Created May 28, 2011 19:54
Metaclasses in Python
def make_hook(f):
"""Decorator to turn 'foo' method into '__foo__'"""
f.is_hook = 1
return f
class MyType(type):
def __new__(cls, name, bases, attrs):
if name.startswith('None'):
return None
@gennad
gennad / decorators.py
Created May 28, 2011 20:01
Decorators
class myDecorator(object):
def __init__(self, f):
print "inside myDecorator.__init__()"
f() # Prove that function definition has completed
def __call__(self):
print "inside myDecorator.__call__()"
@myDecorator
@gennad
gennad / mergesort.py
Created May 29, 2011 15:55
Mergesort Python
#Merges two sorted lists into one sorted list. recursively
def merge(left, right):
if len(left) == 0 and len(right) == 0:
return []
elif len(left) == 0:
return right
elif len(right) == 0:
return left
else:
if left[0] <= right[0]:
@gennad
gennad / quicksort.py
Created May 29, 2011 15:56
Quikcosrt Python
#Three-way QuickSort in Python
def quicksort(a):
if len(a) == 0:
return []
p = a[(len(a)-1)//2]
less = quicksort([x for x in a if x < p])
greater = quicksort([x for x in a if x > p])
equal = [x for x in a if x == p]
return less + equal + greater