snippets / language / python

All snippets for language python (35)

  1. simple xml serializer

    simple xml serializer that convert a python object in xml file.

     1 def serialize_xml(d):
    2 # simple serializer
    3 if not isinstance(d, (dict,list,tuple)):
    4 raise TypeError("Expected a dict here")
    5 yield "\r\n"
    6 if isinstance(d, dict):
    7 for k,v in d.items():
    8 if isinstance(v, (dict,list,tuple)):
    9 v = "".join(serialize_xml(v))
    10 yield "<%(key)s>%(value)s</%(key)s>\r\n" % {
    11 'key':k,
    12 'value':v
    13 }
    14 elif isinstance(d, (tuple, list)):
    15 for v in d:
    16 if isinstance(v, (dict,list,tuple)):
    17 v = serialize_xml(v)
    18 yield "<value>%s</value>\r\n" % v
    Posted by benoitc to python xml serializer ... saved by 2 persons ... 0 comments ... 5 months, 1 week
  2. Xconf

    EEEPC Xandros

      1 Section "ServerLayout"
    2 Identifier "Xandros"
    3 Screen 0 "Screen1"
    4 InputDevice "keyboard"
    5 InputDevice "mouse"
    6 InputDevice "synaptics"
    7 EndSection
    8
    9 Section "Files"
    10 ModulePath "/usr/lib/xorg/modules"
    11 FontPath "/usr/share/fonts/X11/misc"
    12 FontPath "/usr/share/fonts/X11/Type1"
    13 FontPath "/usr/share/fonts/X11/75dpi"
    14 FontPath "/usr/X11R6/lib/X11/fonts/Type1"
    15 EndSection
    16
    17 Section "Module"
    18 Load "glx"
    19 Load "dri"
    20 Load "extmod"
    21 Load "synaptics"
    22 EndSection
    23
    24 Section "ServerFlags"
    25 Option "AllowMouseOpenFail"
    26 Option "BlankTime" "5"
    27 Option "DontVTSwitch" "true"
    28 Option "AIGLX" "false"
    29 EndSection
    30
    31 Section "InputDevice"
    32 Identifier "keyboard"
    33 Driver "kbd"
    34 Option "CoreKeyboard"
    35 Option "XkbRules" "xorg"
    36 Option "XkbModel" "pc105"
    37 Option "XkbLayout" "fr"
    38 Option "XkbVariant" "eeepc"
    39 EndSection
    40
    41 Section "InputDevice"
    42 Identifier "mouse"
    43 Driver "mouse"
    44 Option "Device" "/dev/input/mice"
    45 Option "Protocol" "IMPS/2"
    46 Option "Emulate3Buttons" "yes"
    47 Option "ZAxisMapping" "4 5"
    48 Option "CorePointer"
    49 EndSection
    50
    51 Section "InputDevice"
    52 Identifier "synaptics"
    53 Driver "synaptics"
    54 Option "Device" "/dev/psaux"
    55 Option "Protocol" "auto-dev"
    56 Option "LeftEdge" "1000"
    57 Option "RightEdge" "5400"
    58 Option "TopEdge" "1000"
    59 Option "BottomEdge" "4900"
    60 Option "PalmDetect" "0"
    61 Option "SHMConfig" "true"
    62 Option "SendCoreEvents" "yes"
    63 Option "HorizScrollDelta" "0"
    64 Option "RBCornerButton" "0"
    65 Option "RTCornerButton" "0"
    66 Option "MaxSpeed" "0.1"
    67 EndSection
    68
    69 Section "Monitor"
    70 Identifier "Monitor1"
    71 VendorName "ASUS"
    72 ModelName "eeePC P701"
    73 Modeline "800x480" 29.58 800 816 896 992 480 481 484 497 -HSync +Vsync # 60 Hz
    74 EndSection
    75
    76 Section "Device"
    77 Identifier "Device1"
    78 Driver "intel"
    79 VendorName "Intel Corporation"
    80 BoardName "Mobile 915GM/GMS/910GML Express Graphics Controller"
    81 BusID "PCI:0:2:0"
    82 EndSection
    83
    84 Section "Screen"
    85 Identifier "Screen1"
    86 Device "Device1"
    87 Monitor "Monitor1"
    88 DefaultDepth 16
    89 SubSection "Display"
    90 Depth 8
    91 Virtual 1024 768
    92 EndSubSection
    93 SubSection "Display"
    94 Depth 15
    95 Virtual 1024 768
    96 EndSubSection
    97 SubSection "Display"
    98 Depth 16
    99 Virtual 1024 768
    100 EndSubSection
    101 SubSection "Display"
    102 Depth 24
    103 Virtual 1024 768
    104 EndSubSection
    105 EndSection
    106
    107 Section "DRI"
    108 Mode 0666
    109 EndSection
    110
    111 Section "Extensions"
    112 Option "Composite" "Disable"
    113 EndSection
    114
    115 Section "Module"
    116 Load "glx"
    117 Load "dri"
    118 Load "dbe"
    119 EndSection
    120
    121 Section "DRI"
    122 Mode 0666
    123 EndSection
    Posted by shadow125 to python eee ... saved by 1 person ... 0 comments ... 5 months, 3 weeks
  3. session support in werkzeug with sqlalchemy

    session object for werkzeug with sqlalchemy. This one use SessionStore object distributed with werkzeug

      1 # -*- coding: utf-8 -*-
    2 """"
    3 example of session support on werkzeug with sqlachemy
    4 all session data are saved in database. It override
    5 SessionStore object from werkzeug.contrib.sessions
    6
    7 Setup :
    8 you have to set these settings :
    9 SESSION_COOKIE_NAME = 'SID'
    10 SESSION_COOKIE_AGE = 60 * 60 * 24 * 7 * 2
    11 SESSION_COOKIE_DOMAIN = None
    12 SESSION_COOKIE_PATH = '/'
    13 SESSION_COOKIE_SECURE = False
    14
    15 DBSession is a basic sqlalchemy session
    16 related to your wsgi application.
    17
    18 store and session object directly in the application dispatching::
    19
    20 session_store = FilesystemSessionStore()
    21
    22 def application(environ, start_response):
    23 request = Request(environ)
    24 sid = request.cookie.get('cookie_name')
    25 if sid is None:
    26 request.session = session_store.new()
    27 else:
    28 request.session = session_store.get(sid)
    29 response = get_the_response_object(request)
    30 if request.session.should_save:
    31 max_age = settings.SESSION_COOKIE_AGE
    32 expires = time.time() + settings.SESSION_COOKIE_AGE
    33 session_store.save(request.session)
    34 response.set_cookie(settings.SESSION_COOKIE_NAME,
    35 request.session.sid,
    36 expires=expires, max_age = max_age,
    37 path=settings.SESSION_COOKIE_PATH,
    38 domain=settings.SESSION_COOKIE_DOMAIN,
    39 secure=settings.SESSION_COOKIE_SECURE)
    40
    41 return response(environ, start_response)
    42 """"
    43
    44
    45
    46 from datetime import datetime, timedelta
    47 import base64
    48 import md5
    49 import random
    50 import cPickle as pickle
    51
    52 from sqlalchemy.orm import synonym
    53
    54 from werkzeug.contrib.sessions import Session,SessionStore
    55
    56 from database import DBSession
    57 import settings
    58
    59 session_table = Table('session', metadata,
    60 Column('session_key', Unicode(40), primary_key=True),
    61 Column('session_data', Binary),
    62 Column('expire_date', DateTime)
    63 )
    64
    65 class SuspiciousOperation(Exception):
    66 pass
    67
    68 class SessionModel(object):
    69 def __init__(self, session_key, session_data=None, expire_date=None):
    70 self.session_key = session_key
    71 self.session_data = session_data
    72 self.expire_date = expire_date
    73
    74 def __repr__(self):
    75 return "<%s(%s)>" % (self.__class__.__name__ , self.session_key)
    76
    77 def _encode(self, session_data):
    78 pickled = pickle.dumps(session_data)
    79 pickled_md5 = md5.new(pickled + settings.SECRET_KEY).hexdigest()
    80 self._session_data = base64.encodestring(pickled + pickled_md5)
    81
    82 def _decode(self):
    83 encoded_data = base64.decodestring(self._session_data)
    84 pickled, tamper_check = encoded_data[:-32], encoded_data[-32:]
    85 if md5.new(pickled + settings.SECRET_KEY).hexdigest() != tamper_check:
    86 raise SuspiciousOperation, "User tampered with session cookie."
    87 try:
    88 return pickle.loads(pickled)
    89 # Unpickling can cause a variety of exceptions. If something happens,
    90 # just return an empty dictionary (an empty session).
    91 except:
    92 return {}
    93
    94 session_data = property(_decode, _encode)
    95
    96 DBSession.mapper(SessionModel, session_table, properties = {
    97 'session_data':synonym('_session_data', map_column=True)
    98 })
    99
    100 class DatabaseSessionStore(SessionStore):
    101 def __init__(self, session_class=Session):
    102 SessionStore.__init__(self, session_class)
    103
    104 def save(self, session):
    105 s = DBSession.query(SessionModel).get(session.sid)
    106 if s:
    107 s.session_data = dict(session)
    108 expire_date = datetime.now() + timedelta(seconds=settings.SESSION_COOKIE_AGE)
    109 else:
    110 s=SessionModel(
    111 session_key=session.sid,
    112 session_data=dict(session),
    113 expire_date = datetime.now() + timedelta(seconds=settings.SESSION_COOKIE_AGE)
    114 )
    115 DBSession.expunge(s)
    116 DBSession.save_or_update(s)
    117 DBSession.commit()
    118
    119 def delete(self, session):
    120 try:
    121 DBSession.delete(DBSession.query(SessionModel).get(session_key=session.sid))
    122 except:
    123 pass
    124 return {}
    125
    126 def get(self, sid):
    127 s=DBSession.query(SessionModel).filter(SessionModel.session_key==sid).first()
    128 if not s or not self.is_valid_key(sid):
    129 return self.new()
    130
    131 return self.session_class(s.session_data, sid, False)
  4. Session management in werkzeug

    Example of session support on werkzeug (http://werkzeug.pocco.org) with sqlachemy. All session data are saved in database in a pickle objet. Session is a simple dict.This is based on django session system.

      1 # -*- coding: utf-8 -*-
    2 # example of session support on werkzeug with sqlachemy
    3 # all session data are saved in database in a
    4 # pickle objet. session is a simple dict.
    5 # This is based on django session system.
    6 #
    7 # To add a variable to the session :
    8 # request.session['variable'] = value
    9 #
    10 # to get a variable :
    11 # request.session['variable'] or request.session.get('variable')
    12 #
    13 # To delete a variable :
    14 # del request.session['variable']
    15 #
    16 # .......
    17 #
    18 # Setup :
    19 # you have to set these settings :
    20 # SESSION_COOKIE_NAME = 'SID'
    21 # SESSION_COOKIE_AGE = 60 * 60 * 24 * 7 * 2
    22 # SESSION_COOKIE_DOMAIN = None
    23 # SESSION_COOKIE_PATH = '/'
    24 # SESSION_COOKIE_SECURE = False
    25 #
    26 # DBSession is a basic sqlalchemy session
    27 # related to your wsgi application.
    28 # to use session you have to override BaseRequest
    29 # object like this :
    30 #
    31 # class Request(BaseRequest):
    32 # charset = 'utf-8'
    33 #
    34 # def __init__(self, app, environ):
    35 # super(Request, self).__init__(environ)
    36 # self.app = app
    37 # session_key = self.cookies.get(settings.SESSION_COOKIE_NAME)
    38 # self.session = SessionStore(session_key)
    39 #
    40 # session is saved by your application when a data
    41 # is modified. Add this somehere in your wsgi application
    42 # where you get your response object :
    43 #
    44 # try:
    45 # modified = request.session.modified
    46 # accessed = request.session.accessed
    47 # except:
    48 # pass
    49 # else:
    50 # if modified:
    51 # max_age = settings.SESSION_COOKIE_AGE
    52 # expires = time.time() + settings.SESSION_COOKIE_AGE
    53 # request.session.save()
    54 # response.set_cookie(settings.SESSION_COOKIE_NAME,
    55 # request.session.session_key,
    56 # expires=expires, max_age = max_age,
    57 # path=settings.SESSION_COOKIE_PATH,
    58 # domain=settings.SESSION_COOKIE_DOMAIN,
    59 # secure=settings.SESSION_COOKIE_SECURE)
    60 #
    61
    62 session_table = Table('session', metadata,
    63 Column('session_key', Unicode(40), primary_key=True),
    64 Column('session_data', Binary),
    65 Column('expire_date', DateTime)
    66 )
    67
    68
    69
    70
    71 import base64
    72 from datetime import datetime, timedelta
    73 import os
    74 import md5
    75 import random
    76 import sys
    77 import time
    78 import cPickle as pickle
    79
    80 from database import DBSession
    81 import settings
    82
    83 from sqlalchemy.orm import synonym
    84
    85 class SuspiciousOperation(Exception):
    86 pass
    87
    88 class Session(object):
    89 def __init__(self, session_key, session_data=None, expire_date=None):
    90 self.session_key = session_key
    91 self.session_data = session_data
    92 self.expire_date = expire_date
    93
    94 def __repr__(self):
    95 return "<%s(%s)>" % (self.__class__.__name__ , self.session_key)
    96
    97 def _encode(self, session_data):
    98 pickled = pickle.dumps(session_data)
    99 pickled_md5 = md5.new(pickled + settings.SECRET_KEY).hexdigest()
    100 self._session_data = base64.encodestring(pickled + pickled_md5)
    101
    102 def _decode(self):
    103 encoded_data = base64.decodestring(self._session_data)
    104 pickled, tamper_check = encoded_data[:-32], encoded_data[-32:]
    105 if md5.new(pickled + settings.SECRET_KEY).hexdigest() != tamper_check:
    106 raise SuspiciousOperation, "User tampered with session cookie."
    107 try:
    108 return pickle.loads(pickled)
    109 # Unpickling can cause a variety of exceptions. If something happens,
    110 # just return an empty dictionary (an empty session).
    111 except:
    112 return {}
    113
    114 session_data = property(_decode, _encode)
    115
    116 DBSession.mapper(Session, session_table, properties = {
    117 'session_data':synonym('_session_data', map_column=True)
    118 })
    119
    120
    121
    122 class SessionBase(object):
    123 def __init__(self, session_key = None):
    124 self._session_key = session_key
    125 self.accessed = False
    126 self.modified = False
    127
    128 def __contains__(self, key):
    129 return key in self._session
    130
    131 def __getitem__(self, key):
    132 return self._session[key]
    133
    134 def __setitem__(self, key, value):
    135 self._session[key]=value
    136 self.modified = True
    137
    138 def __delitem__(self, key):
    139 del self._session['key']
    140 self.modified = True
    141
    142 def items(self):
    143 return self._session.items()
    144
    145 def keys(self):
    146 return self._session.keys()
    147
    148 def get(self, key, default=None):
    149 return self._session.get(key, default)
    150
    151 def pop(self, key, *args):
    152 self.modified = self.modified or key in self._session
    153 return self._session.pop(key, *args)
    154
    155 def setdefault(self, key, value):
    156 if key in self._session:
    157 return self._session[key]
    158 else:
    159 self.modified = True
    160 self._session[key] = value
    161 return value
    162
    163 def _get_new_session_key(self):
    164 "Returns session key that isn't being used."
    165 # The random module is seeded when this Apache child is created.
    166 # Use settings.SECRET_KEY as added salt.
    167 try:
    168 pid = os.getpid()
    169 except AttributeError:
    170 # No getpid() in Jython, for example
    171 pid = 1
    172 while 1:
    173 session_key = md5.new(u"%s%s%s%s" % (random.randint(0, sys.maxint - 1),
    174 pid, time.time(), settings.SECRET_KEY)).hexdigest()
    175 if not self.exists(session_key):
    176 break
    177 return session_key
    178
    179 def _get_session_key(self):
    180 if self._session_key:
    181 return self._session_key.decode()
    182 else:
    183 self._session_key = self._get_new_session_key()
    184 return self._session_key.decode()
    185
    186 def _set_session_key(self, session_key):
    187 self._session_key = session_key
    188
    189 session_key = property(_get_session_key, _set_session_key)
    190
    191 def _get_session(self):
    192 # Lazily loads session from storage.
    193 self.accessed = True
    194 try:
    195 return self._session_cache
    196 except AttributeError:
    197 if self._session_key is None:
    198 self._session_cache = {}
    199 else:
    200 self._session_cache = self.load()
    201 return self._session_cache
    202
    203 _session = property(_get_session)
    204
    205 def exists(self, session_key):
    206 raise NotImplementedError
    207
    208 def save(self):
    209 """
    210 Saves the session data.
    211 """
    212 raise NotImplementedError
    213
    214 def delete(self, session_key):
    215 """
    216 Clears out the session data under this key.
    217 """
    218 raise NotImplementedError
    219
    220 def load(self):
    221 """
    222 Loads the session data and returns a dictionary.
    223 """
    224 raise NotImplementedError
    225
    226
    227 class SessionStore(SessionBase):
    228 def __init__(self, session_key=None):
    229 super(SessionStore, self).__init__(session_key)
    230
    231 def load(self):
    232 s=DBSession.query(Session).filter(Session.session_key==self.session_key).first()
    233 if s:
    234 return s.session_data
    235 else:
    236 self.session_key = self._get_new_session_key()
    237 self._session_cache = {}
    238 self.save()
    239 self.modified = True
    240 return {}
    241
    242 def exists(self, session_key):
    243 try:
    244 DBSession.query(Session).get(session_key=session_key)
    245 except:
    246 return False
    247 return True
    248
    249 def save(self):
    250 s = DBSession.query(Session).get(self.session_key)
    251 if s:
    252 s.session_data = self._session
    253 expire_date = datetime.now() + timedelta(seconds=settings.SESSION_COOKIE_AGE)
    254 else:
    255 s=Session(
    256 session_key=self.session_key,
    257 session_data=self._session,
    258 expire_date = datetime.now() + timedelta(seconds=settings.SESSION_COOKIE_AGE)
    259 )
    260 DBSession.expunge(s)
    261 DBSession.save_or_update(s)
    262 DBSession.commit()
    263
    264 def delete(self, session_key):
    265 try:
    266 DBSession.delete(DBSession.query(Session).get(session_key=session_key))
    267 except:
    268 pass
    269 return {}
  5. Comb sort 11

    A Python implementation of the "Comb sort 11" algorithm. See http://en.wikipedia.org/wiki/Comb_sort

     1 def combsort11(seq, cmp=None, key=None):
    2 """Sort `seq` *in-place* with the CombSort11 algorithm.
    3 Optional arguments `cmp` and `key` have same meaning as in the
    4 Python `sorted` built-in function.
    5
    6 Examples::
    7
    8 >>> seq = [8,4,5,0,2,3,1,6,7]
    9 >>> combsort11(seq)
    10 >>> seq
    11 [0, 1, 2, 3, 4, 5, 6, 7, 8]
    12
    13 >>> seq = range(9)
    14 >>> combsort11(seq, cmp=-cmp)
    15 >>> seq
    16 [8, 7, 6, 5, 4, 3, 2, 1, 0]
    17
    18 >>> seq = [(1,0), (2,3), (1,3), (1,-1)]
    19 >>> combsort11(seq, key=lambda x: 10*x[0] + x[1])
    20 >>> seq
    21 [(1, -1), (1, 0), (1, 3), (2, 3)]
    22
    23 See http://en.wikipedia.org/wiki/Comb_sort for an explanation and
    24 the original pseudocode.
    25 """
    26
    27 if cmp is None:
    28 cmp = __builtins__.cmp
    29 if key is None:
    30 key = lambda x: x
    31
    32 gap = len(seq) # initialize gap size
    33 swap_occurred = False
    34 while (gap > 1) or swap_occurred:
    35 # update the gap value for a next comb
    36 if gap > 1:
    37 gap = int(gap / 1.247330950103979)
    38 # adjust gap size for final steps of the sequence;
    39 # see http://en.wikipedia.org/wiki/Comb_sort#Combsort11
    40 if gap in (9, 10):
    41 gap = 11
    42
    43 # a single "comb" over the input list
    44 swap_occurred = False
    45 for i in xrange(len(seq) - gap):
    46 j = i + gap
    47 if cmp(key(seq[i]), key(seq[j])) > 0:
    48 # swap seq[i] and seq[i+gap]
    49 seq[i], seq[j] = seq[j], seq[i]
    50 swap_occurred = True
    Posted by rmurri to python sort combsort algorithms ... saved by 1 person ... 0 comments ... 9 months, 2 weeks
  6. Group items from iterable into chunks of specified size.

    Only tested with Python 2.5, but should work with 2.3+

     1 class chunks(object):
    2 """Lump items from iterable into chunks of specified size.
    3
    4 Instanciate the iterator passing a sequence of chunk sizes in
    5 argument 1 and an iterable to consume in argument 2::
    6
    7 >>> for c in chunks([1,1,1], xrange(3)): print c
    8 [0]
    9 [1]
    10 [2]
    11
    12 The list of chunk sizes may be any kind of sequence, for instance
    13 a tuple or even a (possibly infinite) iterable::
    14
    15 >>> list(chunks((1,2,3), range(6)))
    16 [[0], [1, 2], [3, 4, 5]]
    17
    18 The total size of the chunks may be less than the size of the
    19 iterator: remaining items in the iterator are not consumed::
    20
    21 >>> for c in chunks([1,2], range(6)): print c
    22 [0]
    23 [1, 2]
    24
    25 As a special case, if a chunk has size 0, then an empty list is
    26 returned in its place and no item from iterable is consumed::
    27
    28 >>> for c in chunks([2,0,2], range(4)): print c
    29 [0, 1]
    30 []
    31 [2, 3]
    32
    33 """
    34 def __init__(self, sizes, iterable):
    35 """Constructor, taking sequence of chunk sizes and iterable to
    36 consume."""
    37 self.current_chunk = -1
    38 self.sizes = sizes
    39 self.iterable = iter(iterable)
    40 def __iter__(self):
    41 return self
    42 def next(self):
    43 """Return next chunk."""
    44 self.current_chunk += 1
    45 if self.current_chunk >= len(self.sizes):
    46 raise StopIteration
    47 return [ self.iterable.next()
    48 for x in xrange(self.sizes[self.current_chunk]) ]
    Posted by rmurri to python itertools ... saved by 1 person ... 0 comments ... 10 months, 1 week
  7. Alter items in a sequence according to a translation table

    This is the analogue of Python `str.translate` or `unicode.translate` for general iterables (lists, tuples, etc.) Tested with Python 2.5

     1 class itranslate:
    2 """Return items from a sequence, substituting them as specified.
    3
    4 First c'tor argument `subst` is a dictionary, specifying
    5 substitutions to be applied. If an item matches a key of the
    6 `subst` dictionary, the associated dictionary value is returned
    7 instead; unless the value is `None`, in which case the item is
    8 skipped altogether.
    9
    10 *Note:* you should use an appropriate `dict`-subclass if you want
    11 to translate items which are not immutable.
    12
    13 Examples::
    14 >>> list(itranslate({0:None, 3:2}, [2,1,0,0,1,3]))
    15 [2, 1, 1, 2]
    16 """
    17 def __init__(self, subst, iterable):
    18 self.mappings = subst
    19 self.iterable = iter(iterable)
    20 def __iter__(self):
    21 return self
    22 def next(self):
    23 while True:
    24 next = self.iterable.next()
    25 if not self.mappings.has_key(next):
    26 return next
    27 translated = self.mappings[next]
    28 if translated is None:
    29 # skip this item
    30 continue
    31 return translated
    Posted by rmurri to python itertools ... saved by 2 persons ... 0 comments ... 10 months, 3 weeks
  8. Generate all partitions of an integer

    Iterative algorithms to generate all partitions of a given integer. Only tested with Python 2.5

      1 import itertools
    2
    3 class FixedLengthPartitionIterator:
    4 """Iterate over partitions of integer `N` into *exactly* `K`
    5 positive integers.
    6
    7 Each returned partition is a list of positive integers in
    8 descending order, such that their sum is `N`.
    9
    10 Arguments `min_` and `max_` bound the values in each partition.
    11
    12 Examples::
    13 >>> list(FixedLengthPartitionIterator(3,1))
    14 [(3,)]
    15 >>> list(FixedLengthPartitionIterator(3,2))
    16 [(2, 1)]
    17 >>> list(FixedLengthPartitionIterator(3,3))
    18 [(1, 1, 1)]
    19 >>> list(FixedLengthPartitionIterator(6,2))
    20 [(5, 1), (4, 2), (3, 3)]
    21 >>> list(FixedLengthPartitionIterator(8,3))
    22 [(6, 1, 1), (5, 2, 1), (4, 3, 1), (4, 2, 2), (3, 3, 2)]
    23 >>> list(FixedLengthPartitionIterator(8,4,2))
    24 [(2, 2, 2, 2)]
    25 >>> list(FixedLengthPartitionIterator(8,3,2))
    26 [(4, 2, 2), (3, 3, 2)]
    27 >>> list(FixedLengthPartitionIterator(8,3,2,3))
    28 [(3, 3, 2)]
    29 """
    30 def __init__(self, N, K, min_=1, max_=None):
    31 # `max_` really defaults to N
    32 if max_ is None:
    33 max_ = N
    34
    35 # rule out trivial cases
    36 if (K*min_ > N) or (K*max_ < N):
    37 self.done = True
    38 return
    39
    40 self._N = N #: integer to be partitioned
    41 self._K = K #: maximum number of nonzero parts
    42 self._k = 0 #: current number of nonzero parts
    43 self._min = min_ #: minimum value of each part
    44 self._max = max_ #: maximum value of each part
    45 self._p = [0] * K #: current partition
    46 self.done = False #: when `True`, enumeration is over
    47
    48 def __iter__(self):
    49 return self
    50
    51 def next(self):
    52 if self.done:
    53 raise StopIteration
    54 if self._N == self._K * self._min:
    55 self.done = True
    56 return tuple([self._min]*self._K)
    57 else:
    58 while self._k <= self._K:
    59 i = self._k - 1
    60 while i > 0:
    61 if (self._p[i]+1 <= self._p[i-1]-1) \
    62 and (self._p[i-1]-1 >= self._min) \
    63 and (self._p[i]+1 <= self._max):
    64 self._p[i-1] -= 1
    65 self._p[i] += 1
    66 return tuple(self._p)
    67 else:
    68 i -= 1
    69 # only change the first `k` parts
    70 self._k += 1
    71 head = (self._N - self._k - self._min*self._K + self._min + 1)
    72 if (head < self._min+1) or (head > self._max) \
    73 or (self._k > self._K):
    74 continue
    75 # advance to next partition:
    76 # [N-2*(k-1)-(K-k), 2, ..., 2, (k-1 times) 1, ..., 1 (K-k times)]
    77 self._p = [head] \
    78 + ([self._min + 1] * (self._k - 1)) \
    79 + ([self._min] * (self._K - self._k))
    80 return tuple(self._p)
    81 raise StopIteration
    82
    83
    84 def PartitionIterator(N, K, min_=1, max_=None):
    85 """Iterate over partitions of integer `N` into *at most* `K`
    86 positive integers.
    87
    88 Each returned partition is a list of positive integers in
    89 descending order, such that their sum is `N`.
    90
    91 Optional arguments `min_` and `max_` bound the values in each
    92 partition.
    93
    94 Examples::
    95 >>> list(PartitionIterator(2,1))
    96 [(2,)]
    97 >>> list(PartitionIterator(3,3))
    98 [(3,), (2, 1), (1, 1, 1)]
    99 >>> list(PartitionIterator(8,3,2))
    100 [(8,), (6, 2), (5, 3), (4, 4), (4, 2, 2), (3, 3, 2)]
    101 >>> list(PartitionIterator(8,3,2,3))
    102 [(3, 3, 2)]
    103 """
    104 return itertools.chain(*[FixedLengthPartitionIterator(N,k,min_,max_)
    105 for k in xrange(1,K+1)])
  9. convert '2007-11-08 16:17:17.375000' in a datetime and keep microseconds

    strptime don't take microseconds in python 2.x. Here is a quickway to add them to a datetime object.

    1 >>> from datetime import datetime
    2 >>> from time import strptime
    3 >>> date_str='2007-11-08 16:17:17.375000'
    4 >>> d = datetime(*strptime(date_str[:19],"%Y-%m-%d %H:%M:%S")[0:6])
    5 >>> d = d.replace(microsecond=eval(date_str[20:]))
    6 >>> print d
    7 2007-11-08 16:17:17.375000
    Posted by benoitc to python datetime ... saved by 1 person ... 2 comments ... 11 months
  10. Changer du texte dans des fichiers recursivement

    un script en python pour remplacer du texte recursivement dans des fichiers.

     1 import os
    2 liste = os.