Skip to content

Instantly share code, notes, and snippets.

@eirenik0
eirenik0 / search_min_On.py
Last active August 29, 2015 13:57
O(n) min search
l=[3,11,4,3,4,62,6,67,8,3,2246]
tmp = l[0]
for i in range(len(l)):
if l[i]<tmp:
tmp = l[i]
print tmp
@eirenik0
eirenik0 / stack_list.py
Last active August 29, 2015 13:58
Recall that the list class in Python provides an ordered collection mechanism and a set of methods. For example, if we have the list [2,5,3,6,7,4], we need only to decide which end of the list will be considered the top of the stack and which will be the base. Once that decision is made, the operations can be implemented using the list methods s…
class Stack:
def __init__(self):
self.items = []
def isEmpty(self):
return self.items == []
def push(self, item):
self.items.append(item)
@eirenik0
eirenik0 / BalancedSymbols.py
Created April 3, 2014 07:45
The balanced parentheses problem shown above is a specific case of a more general situation that arises in many programming languages. The general problem of balancing and nesting different kinds of opening and closing symbols occurs frequently. For example, in Python square brackets, [ and ], are used for lists; curly braces, { and }, are used …
def parChecker(symbolString):
s = Stack()
balanced = True
index = 0
while index < len(symbolString) and balanced:
symbol = symbolString[index]
if symbol in "([{":
s.push(symbol)
else:
if s.isEmpty():
@eirenik0
eirenik0 / divideBy2.py
Created April 3, 2014 07:56
In your study of computer science, you have probably been exposed in one way or another to the idea of a binary number. Binary representation is important in computer science since all values stored within a computer exist as a string of binary digits, a string of 0s and 1s. Without the ability to convert back and forth between common representa…
def divideBy2(decNumber):
remstack = Stack()
while decNumber > 0:
rem = decNumber % 2
remstack.push(rem)
decNumber = decNumber // 2
binString = ""
while not remstack.isEmpty():
@eirenik0
eirenik0 / baseConvertor.py
Created April 3, 2014 08:07
The algorithm for binary conversion can easily be extended to perform the conversion for any base. In computer science it is common to use a number of different encodings. The most common of these are binary, octal (base 8), and hexadecimal (base 16).
def baseConverter(decNumber,base):
digits = "0123456789ABCDEF"
remstack = Stack()
while decNumber > 0:
rem = decNumber % base
remstack.push(rem)
decNumber = decNumber // base
def reverse(s):
if len(s)<=1:
return s
else:
return reverse(s[1:]) + s[0]
import os
# here() gives us file paths from the root of the system to the directory
# holding the current file.
here = lambda * x: os.path.join(os.path.abspath(os.path.dirname(__file__)), *x)
PROJECT_ROOT = here("..")
# root() gives us file paths from the root of the system to whatever
# folder(s) we pass it starting at the parent directory of the current file.
root = lambda * x: os.path.join(os.path.abspath(PROJECT_ROOT), *x)
@eirenik0
eirenik0 / reloadall.py
Last active August 29, 2015 14:03
транзитивная перезагрузка вложенных модулей
"""
reloadall.py: транзитивная перезагрузка вложенных модулей
"""
import types
from imp import reload
# требуется в версии 3.0
def status(module):
print('reloading' + module.__name__)
@eirenik0
eirenik0 / classtools.py
Last active August 29, 2015 14:03
Реализует наследуемый метод перегрузки операции вывода, отображающий имена классов экземпляров и все атрибуты в виде пар имя=значение, имеющиеся в экземплярах (исключая атрибуты, унаследованные от классов). Может добавляться в любые классы и способен работать с любыми экземплярами
#-*- coding: utf-8 -*-
class AttrDisplay:
"""
Реализует наследуемый метод перегрузки операции вывода, отображающий
имена классов экземпляров и все атрибуты в виде пар имя=значение,
имеющиеся в экземплярах (исключая атрибуты, унаследованные от классов).
Может добавляться в любые классы и способен работать с любыми
экземплярами.
"""
def gatherAttrs(self):
@eirenik0
eirenik0 / login_required.py
Created September 21, 2014 07:33
Django LoginRequiredMixin
class LoginRequiredMixin(object):
@method_decorator(login_required)
def dispatch(self, request, *args, **kwargs):
return super(LoginRequiredMixin, self).dispatch(request, *args, **kwargs)