All computer source code presented on this page, unless it includes attribution to another author, is provided by Ed Halley under the Artistic License. Use such code freely and without any expectation of support. I would like to know if you make anything cool with the code, or need questions answered.
# useful - generic useful standalone routines


Several utility routines that are hardly worth mentioning.


    Ed Halley ( 17 September 2005


import random


def all(seq):
    '''Returns True if all of the given sequence are non-False.'''
    for x in seq:
        if not x:
            return False
    return True

def none(seq):
    '''Returns True if none of the given sequence is non-False.'''
    for x in seq:
        if x:
            return False
    return True

def any(seq):
    '''Returns True if any of the given sequence is non-False.'''
    for x in seq:
        if x:
            return True
    return False

def wrap(text, width=72):
    '''Wrap a piece of text at whitespace, so as to fit within margins.

    The width of the space is measured in characters, suitable for
    monospaced fonts like console applications.
    return reduce(lambda line, word, width=width: "%s%s%s" %
                   " \n"[(len(line)-line.rfind("\n")-1 +
                          len(word.split("\n",1)[0]) >= width)],
                  text.split(" "))

def weighted(choices, total=0):
    '''Given a dict of key:weight pairs, chooses a key at random.

    The dict values are non-negative numerical weights.  Keys with higher
    values are chosen more often than keys with lower values.

    If the caller knows the total of all weights, it can be given to
    avoid recalculating it internally on each call.  If the given total
    is not accurate, a key may be chosen with a poorly-shaped
    if not total:
        total = sum(choices.values())
    mark = random.random()*total
    keys = choices.keys()
    for i in xrange(len(keys)):
        span = choices[keys[i]]
        if span > mark:
            return keys[i]
        mark -= span
    # should not reach here if total is accurate
    return random.choice(keys)


if __name__ == '__main__':
    raise Exception, \
        'This module is not a stand-alone script.  Import it in a program.'

Contact Ed Halley by email at
Text, code, layout and artwork are Copyright © 1996-2013 Ed Halley.
Copying in whole or in part, with author attribution, is expressly allowed.
Any references to trademarks are illustrative and are controlled by their respective owners.
Make donations with PayPal - it's fast, free and secure!