Re: Question about idioms for clearing a list

2006-02-07 Thread Raymond Hettinger
[Ed Singleton] > Is it obvious to a newbie what the difference between mappings and > "not-mappings", and is it obvious exactly what is and isn't a mapping? FWIW, there is a glossary in the tutorial: http://docs.python.org/tut/node18.html -- http://mail.python.org/mailman/listinfo/python-lis

Re: Question about idioms for clearing a list

2006-02-10 Thread Raymond Hettinger
[Alex Martelli] > I was thinking of something different again, from a use case I did have: > > def buncher(sourceit, sentinel, container, adder, clearer): > for item in sourceit: > if item == sentinel: > yield container > clearer() > else > ad

Re: Question about idioms for clearing a list

2006-02-10 Thread Raymond Hettinger
> > If you're asking why list's don't have a clear() method, the answer is > > that they already had two ways to do it (slice assignment and slice > > deletion) and Guido must have valued API compactness over collection > > polymorphism. The latter is also evidenced by set.add() vs > > list.append

Re: ordered sets operations on lists..

2006-02-10 Thread Raymond Hettinger
[Amit Khemka] > > Hello, Is there a *direct* way of doing set operations on lists which > > preserve the order of the input lists ? > > For Ex. l1 = [1, 5, 3, 2, 4, 7] > > l2 = [3, 5, 10] > > > > and (l1 intersect l2) returns [5, 3] (and (l2 intersect l1) [bonono] > what d

Re: itertools examples

2006-02-11 Thread Raymond Hettinger
[Felipe Almeida Lessa] > IMHO, on http://www.python.org/doc/current/lib/itertools-example.html , > shouldn't the part > > >>> for k, g in groupby(enumerate(data), lambda (i,x):i-x): > ... print map(operator.itemgetter(1), g) > > be > > >>> for k, g in groupby(enumerate(data), lambda (i, x): i-x

Re: Unexpected behaviour of getattr(obj, __dict__)

2006-02-14 Thread Raymond Hettinger
Steven D'Aprano wrote: > I came across this unexpected behaviour of getattr for new style classes. > Example: > > >>> class Parrot(object): > ... thing = [1,2,3] > ... > >>> getattr(Parrot, "thing") is Parrot.thing > True > >>> getattr(Parrot, "__dict__") is Parrot.__dict__ > False > > I would

Re: Soduku

2006-02-15 Thread Raymond Hettinger
[Jack Diederich] > Is my math off or does 27ms mean 0.027 seconds? On my laptop (1.3GHz) > an empty python program takes 10ms to run (0.010 secs). I ask out of > vanity, my own solver takes .15 seconds to run (20 seconds for a 16x16 grid). Comparisons for individual puzzles are likely to be meani

Re: Does python have an internal list/dictionary of functions?

2006-02-17 Thread Raymond Hettinger
[Carl J. Van Arsdall] > basically we have: > > >>>def functA(): > ... pass > > >>> functA > > > And what I'd like to do is: > > >>>__internalFuncDict__['functA'] > globals()['functA'] -- http://mail.python.org/mailman/listinfo/python-list

Re: Add a month

2006-02-17 Thread Raymond Hettinger
[EMAIL PROTECTED] > Hi, this is probably a really simple question but... > How do you add a month to a datetime date in python? It would be nice > if you could do something like: > > d = datetime.date(2006,2,17) > dm = datetime.timedelta(months=1) > d_new = d + dm > > but timedelta doesn't have a

Re: getting the line just before or after a pattern searched

2006-02-17 Thread Raymond Hettinger
[EMAIL PROTECTED] wrote: > hi > > i have a file something like this > > abcdefgh > ijklmnopq > 12345678 > rstuvwxyz > . > . > . > 12345678 > . > > whenever i search the file and reach 12345678, how do i get the line > just above and below ( or more than 1 line above/below) the patte

Re: Multiplication optimization

2006-02-18 Thread Raymond Hettinger
[Paul McGuire] > Does Python's run-time do any optimization of multiplication > operations, like it does for boolean short-cutting? Usually, it is safest (and typically true) to assume that Python performs no optimizations. To go beyond making assumptions, it is easy to run a few timings: >>> fr

Re: list assignment

2006-02-22 Thread Raymond Hettinger
> [spam, ham] = ['yum', 'YUM'] > > I don't see how this is any different than a tuple unpacking assignment: > > >>> a, b = 1, 2 It's not different. They are ways of writing the same thing. Raymond Hettinger -- http://mail.python.org/mailman/listinfo/python-list

Re: Psychic bug

2006-02-23 Thread Raymond Hettinger
> a mutate function for a genetic algorithm which is giving me > odd results. I suspect I'm missing somthing really simple, so I'd be > grateful for any suggestions. Basically, when I comment out the line > which is commented out below, it works fine (although of course it > doesn't change the gen

Re: Can optparse do dependencies?

2006-02-25 Thread Raymond Hettinger
[Bob] > I'd like to setup command line switches that are dependent on other > switches, similar to what rpm does listed below. From the grammar below > we see that the "query-options" are dependent on the query switch, > {-q|--query}. Can "optparse" do this or do I have to code my own > "thing"? Th

Re: Optimize flag question

2006-02-25 Thread Raymond Hettinger
[Olivier Langlois] > > So my question is: what are the 'optimizations' that the Python > > interpreter is doing when you specify the optimize flag and is there > > anything I should be cautious about when using it? Currently, -O provides no optimizations other than eliminating assertions. Raymon

Re: PEP 354: Enumerations in Python

2006-03-01 Thread Raymond Hettinger
[Ben Finney] > It is possible to simply define a sequence of values of some other > basic type, such as ``int`` or ``str``, to represent discrete > arbitrary values. However, an enumeration ensures that such values > are distinct from any others, and that operations without meaning > ("Wednesday t

Re: evaluated function defaults: stored where?

2005-05-25 Thread Raymond Hettinger
[Alan Isaac] > Default parameter values are evaluated once when the function definition is > executed. Where are they stored? >>> def f(a, b=10, c=20): . pass >>> f.func_defaults (10, 20) > Where is this documented? http://docs.python.org/ref/types.html#

Re: Checking for a full house

2005-05-25 Thread Raymond Hettinger
ere's a one-liner: .def isfullHouse(hand): .return sorted(hand.count(card) for card in set(hand)) == [2,3] Raymond Hettinger -- http://mail.python.org/mailman/listinfo/python-list

Re: Checking for a full house

2005-05-25 Thread Raymond Hettinger
'four of a kind', (5): 'flush (five of a kind)' } def eval_hand(hand): counts = tuple(sorted(hand.count(card) for card in set(hand))) return hands.get(counts, 'misdeal') Raymond Hettinger -- http://mail.python.org/mailman/listinfo/python-list

Re: Checking for a full house

2005-05-26 Thread Raymond Hettinger
[Paul Rubin] > 1. "Flush" means 5 cards of the same suit (i.e. all hearts), not 5 of >a kind. More importantly, the (5) should be (5,). Also the poker terminology should be expressed in terms of dice rolls (the OP's use case). > 2. That code doesn't detect flushes or straights. It also doe

Re: evaluated function defaults: stored where?

2005-05-26 Thread Raymond Hettinger
> > Is it unsurprising if I look at it right? [John Machin's QOTW] > Yes; in general this is true across many domains for a very large number > of referents of "it" :-) There's a Quote of the Week in there somewhere. -- http://mail.python.org/mailman/listinfo/python-list

Re: Checking for a full house

2005-05-26 Thread Raymond Hettinger
[Benedict] >> It would be interesting to see how complicated it would get to write >> code to detect the correct hands in poker with wildcards included. There is an interesting SF project with code written in C: http://pokersource.sourceforge.net/ In contrast, Python makes short work of these

Re: finding indices in a sequence of parentheses

2005-05-29 Thread Raymond Hettinger
the indices: >> (2, 2), (4, 7), (6, 7), (8, 9) and (8, 10) opener_stack = [] for i, elem in enumerate(lst): for c in elem: if c == '(': opener_stack.append(i) elif c == ')': print opener_stack.pop(), i To see something like this in production code, look at Tools/scripts/texcheck.py Raymond Hettinger -- http://mail.python.org/mailman/listinfo/python-list

Re: change vars in place w/loop or list comprehension

2005-05-31 Thread Raymond Hettinger
> >>> a = 'one' > >>> b = 'two' > >>> c = 'three' > >>> [a, b, c] = [s.upper() for s in [a, b, c]] > >>> a > 'ONE' > > Both of these accomplish what I'm after; I prefer the second for its > brevity. But either approach requires that I spell out my list of > vars-to-alter [a, b, c] twice. This stri

Re: decimal and trunkating

2005-06-02 Thread Raymond Hettinger
nd to that precision level or use the quantize method to round to a fixed number of places after the decimal point: >>> Context(prec=5, rounding=ROUND_DOWN).create_decimal('199.999') Decimal("199.99") >>> Decimal('199.999').quantize(Deci

Re: how to get name of function from within function?

2005-06-04 Thread Raymond Hettinger
[Christopher J. Bottaro] >> def myFunc(): >> print __myname__ >> >>> myFunc() >> 'myFunc' Perhaps the __name__ attribute is what you want: >>> def myFunc(): print myFunc.__name__ >>> myFunc() myFunc -- http://mail.python.org/mailman/listinfo/python-list

Re: random module question

2005-06-06 Thread Raymond Hettinger
es with at least 53 bit floating point precision). Of course, none of the above applies to random.SystemRandom which accesses system generated entropy sources. Raymond Hettinger -- http://mail.python.org/mailman/listinfo/python-list

Re: split up a list by condition?

2005-06-06 Thread Raymond Hettinger
>> while writing my solution for "The python way?", I came across this fragment: >> vees = [c for c in wlist[::-1] if c in vocals] >> cons = [c for c in wlist[::-1] if c not in vocals] >> >> So I think: Have I overlooked a function which splits up a sequence >> into two, based on a condition Tryi

Re: the python way?

2005-06-07 Thread Raymond Hettinger
import random from itertools import ifilter, ifilterfalse def reinterpolate(word): word = list(word) random.shuffle(word) isvowel = dict.fromkeys('aeiouy').has_key vowels = ifilterfalse(isvowel, word) consonants = ifilter(isvowel, word) result = [] for v, c in map(No

Re: random module question

2005-06-07 Thread Raymond Hettinger
>> Is Mersenne Twister currently available at all in Jython, for example? Googling for "java mersenne twister" provides multiple hits including: http://www.axlradius.com/freestuff/Free.htm#MT Raymond -- http://mail.python.org/mailman/listinfo/python-list

Re: the python way?

2005-06-07 Thread Raymond Hettinger
Doh! The ifilter() and ifilterfalse() calls should be swapped in the previous post. -- http://mail.python.org/mailman/listinfo/python-list

Re: a library of stock mock objects?

2005-06-09 Thread Raymond Hettinger
ously I'm biased. > > What do you think? I think it is like trying to market custom-cut, application specific duck tape. The generic tear-it-and-tape-it solution is far easier and more versatile than having a "library" of pre-cut tape. Raymond Hettinger -- http://mail.python.org/mailman/listinfo/python-list

Re: case/switch statement?

2005-06-12 Thread Raymond Hettinger
ases and an open PEP, http://www.python.org/peps/pep-0275.html . It needs advocacy, TLC, a clear proposal, an implementer, and a little luck. Raymond Hettinger -- http://mail.python.org/mailman/listinfo/python-list

Re: Dynamic Lists, or...?

2005-06-13 Thread Raymond Hettinger
# Professional driver on a closed course. # Don't try this at home. data = """ rose, 1, 500 lilac, 1, 300 lilly, 1, 400 rose, 0, 100 """ data = data.replace(', 1, ', ' += ') data = data.replace(', 0, ', ' -= ') class DefaultDict(dict): def __getitem__(self, key): return self.get(key,

Re: new string function suggestion

2005-06-13 Thread Raymond Hettinger
[Andrew Dalke] <200 lines of thorough analysis> > To summarize: > - I don't think it's needed that often > - I don't think your implementation's behavior (using an >exception) is what people would expect > - I don't think it does what you expect Wow, that was a remarkably thoughtful,

Re: Set of Dictionary

2005-06-18 Thread Raymond Hettinger
FrozenDict(b=2, c=3, a=1) >>> s = set([d1, d2, d3]) >>> s set([{'e': 5, 'd': 4, 'f': 6}, {'a': 1, 'c': 3, 'b': 2}]) >>> d2 in s True Raymond Hettinger -- http://mail.python.org/mailman/listinfo/python-list

Re: Thread-safety of dict

2007-06-01 Thread Raymond Hettinger
On May 31, 9:12 pm, "Adam Olsen" <[EMAIL PROTECTED]> wrote: > It seems to be a commonly held belief that basic dict operations (get, > set, del) are atomic. They are atomic so long as the key does not have a custom __hash__, __eq__, or __cmp__ method which can trigger arbitrary Python code. With

Re: iterblocks cookbook example

2007-06-02 Thread Raymond Hettinger
On Jun 2, 10:19 am, Steve Howell <[EMAIL PROTECTED]> wrote: > George Sakkis produced the following cookbook recipe, > which addresses a common problem that comes up on this > mailing list: ISTM, this is a common mailing list problem because it is fun to solve, not because people actually need it o

Re: inverting a dictionary of lists

2007-06-14 Thread Raymond Hettinger
On Jun 14, 8:20 pm, [EMAIL PROTECTED] wrote: > I have a very large dictionary of lists: > d = {a:[1,2], b:[2,3], c:[3]} > and i want to reverse the associativity of the integers thusly: > inverse(d) makes {1:[a], 2:[a,b], 3:[b,c]} Try using setdefault: >>> d = {'a':[1,2], 'b':[2,3], 'c':[3]

Re: Getting some element from sets.Set

2007-06-29 Thread Raymond Hettinger
> $ python -m timeit -s "s = set('abcdef')" "x = iter(s).next()" > 100 loops, best of 3: 0.399 usec per loop > > $ python -m timeit -s "s = set('abcdef')" "x = s.pop(); s.add(x)" > 100 loops, best of 3: 0.339 usec per loop > > So it looks like it's more efficient to use

Re: lambda generator - curious behavior in 2.5

2007-04-21 Thread Raymond Hettinger
y be: if (result 1= NULL && f->f_stacktop == NULL) Please open a bug report on SF and assign to me. Raymond Hettinger -- http://mail.python.org/mailman/listinfo/python-list

Re: Support for new items in set type

2007-04-26 Thread Raymond Hettinger
e set of things you've deleted since them FWIW, I've posted a trial implementation in the Python cookbook: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/511496 Raymond Hettinger -- http://mail.python.org/mailman/listinfo/python-list

Re: While we're talking about annoyances

2007-04-29 Thread Raymond Hettinger
[Steven D'Aprano] > I recently needed to write a function to generate a rank table from a > list. That is, a list of ranks, where the rank of an item is the position > it would be in if the list were sorted: > > alist = list('defabc') > ranks = [3, 4, 5, 0, 1, 2] . . . > def rank(sequence): > t

Re: fastest way to find the intersection of n lists of sets

2007-04-30 Thread Raymond Hettinger
the hash values of their elements. Accordingly, binary set operations can run without any calls to element.__hash__(). Raymond Hettinger -- http://mail.python.org/mailman/listinfo/python-list

Re: fastest way to find the intersection of n lists of sets

2007-04-30 Thread Raymond Hettinger
ad code that built new intermediate sets between step: common = s1 | s2 | s3 | s4 | s5 | s6 | s7 | s8 | s9 Instead, it is faster to build-up a single result set: common = set() for s in s1, s2, s3, s4, s5, s6, s7, s8, s9: common |= s Raymond Hettinger -- http://mail.python.org/mailman/listinfo/python-list

Re: Getting some element from sets.Set

2007-05-03 Thread Raymond Hettinger
more approach: x = s.pop() s.add(x) Raymond Hettinger -- http://mail.python.org/mailman/listinfo/python-list

Re: change of random state when pyc created??

2007-05-09 Thread Raymond Hettinger
er, you've made non-guaranteed assumptions about the arbitrary ordering of an unordered collection -- a definite no-no). Raymond Hettinger -- http://mail.python.org/mailman/listinfo/python-list

Re: docs patch: dicts and sets

2007-05-11 Thread Raymond Hettinger
On May 11, 5:59 pm, "Alan Isaac" <[EMAIL PROTECTED]> wrote: > This is an attempt to synthesize Bill and Carsten's proposals. > (I'm changing the subject line to better match the topic.) > > http://docs.python.org/lib/typesmapping.html:for footnote (3) > > Keys and values are listed in an ar

Re: Generators in C code

2007-05-14 Thread Raymond Hettinger
like generators in many respects except that you are responsible for tracking state and jumping to an appropriate resume point. Being C, it won't be as convenient as Python generators, but should be able to translate any generator into equivalent C. Raymond Hettinger -- http://mail.python.org/mailman/listinfo/python-list

Re: RFC - n-puzzle.py

2007-05-19 Thread Raymond Hettinger
On May 18, 4:15 pm, Phoe6 <[EMAIL PROTECTED]> wrote: > Hi All, > I would like to request a code and design review of one of my program. > n-puzzle.pyhttp://sarovar.org/snippet/detail.php?type=snippet&id=83 > Its a N-puzzle problem solver ( Wikipedia page > andhttp://norvig.com/ltd/test/n-puzzle.li

Re: Many-to-many pattern possiable?

2007-05-19 Thread Raymond Hettinger
On May 19, 9:33 am, Jia Lu <[EMAIL PROTECTED]> wrote: > I see dict type can do 1-to-1 pattern, But is there any method to do > 1-to-many, many-to-1 and many-to-many pattern ? >>> mm = {'a': ['A', 'B', 'C'], 'c': ['C', 'D', 'E'], 'b': ['A', 'D']} >>> # Now, invert the relation >>> mmr = {} >>> fo

Re: docs patch: dicts and sets

2007-05-20 Thread Raymond Hettinger
On May 13, 4:52 pm, [EMAIL PROTECTED] wrote: > Dismissing this as not a "real problem" is both wrong > and offensive to people taking the time to actually > propose improvements. I should have elaborated on what I meant by saying that there is not a real problem. Another way to put it is that the

Re: 0 == False but [] != False?

2007-05-23 Thread Raymond Hettinger
> >>> [] == False > False > > Could anybody point out why this is the case? Writing, "if x" is short for writing "if bool(x)". Evaluating bool(x) checks for a x.__nonzero__() and if that method isn't defined, it checks for x.__len__() to see if x is a non-empty container. In your case, writing "i

Re: itertools.groupby

2007-05-27 Thread Raymond Hettinger
On May 27, 2:59 pm, Steve Howell <[EMAIL PROTECTED]> wrote: > These docs need work. Please do not defend them; > please suggest improvements. FWIW, I wrote those docs. Suggested improvements are welcome; however, I think they already meet a somewhat high standard of quality: - there is an accur

Re: itertools.groupby

2007-05-27 Thread Raymond Hettinger
On May 27, 8:28 pm, Paul Rubin wrote: > I use the module all the time now and it is great. Thanks for the accolades and the great example. FWIW, I checked in a minor update to the docs: +++ python/trunk/Doc/lib/libitertools.tex Mon May 28 07:23:22 2007 @@ -138,6 +13

Re: itertools.groupby

2007-05-28 Thread Raymond Hettinger
On May 28, 8:34 am, 7stud <[EMAIL PROTECTED]> wrote: > >- there are two more examples on the next page. those two > > examples also give sample inputs and outputs. > > I didn't see those. Ah, there's the rub. The two sections of examples and recipes are there for a reason. This isn't a beginne

Re: itertools.groupby

2007-05-28 Thread Raymond Hettinger
> > That's not for everyone, so it isn't a loss if > > someone sticks > > with writing plain, clear everyday Python instead of > > an itertool. > > I know most of the module is fairly advanced, and that > average users can mostly avoid it, but this is a very > common-antipattern that groupby() solv

Re: itertools.groupby

2007-05-28 Thread Raymond Hettinger
On May 28, 8:36 pm, "Carsten Haese" <[EMAIL PROTECTED]> wrote: > And while > we're at it, it probably should be keyfunc(value), not key(value). No dice. The itertools.groupby() function is typically used in conjunction with sorted(). It would be a mistake to call it keyfunc in one place and not

Re: itertools.groupby

2007-05-29 Thread Raymond Hettinger
On May 28, 8:02 pm, Gordon Airporte <[EMAIL PROTECTED]> wrote: > "Each" seems to imply uniqueness here. Doh! This sort of micro-massaging the docs misses the big picture. If "each" meant unique across the entire input stream, then how the heck could the function work without reading in the entire

Re: zip() function troubles

2007-07-27 Thread Raymond Hettinger
the next method on the input iterators as returns the tuple result). So, if you're seeing behavior changes at 10 millions items, the cause almost certainly lies elsewhere. One possible candidate could be memory consumed by immortal integer objects. Raymond Hettinger -- http://mail.python.org/mailman/listinfo/python-list

Re: is there anybody using __del__ correctly??

2007-08-10 Thread Raymond Hettinger
you search comp.lang.python > for __del__ you will find hundreds of people who were > bitten by __del__, so I usually give advices such as > "you should never __del__ in your code" Good advice. Explicit finalization is almost always preferable. Raymond Hettinger -- http://mail.python.org/mailman/listinfo/python-list

Re: Does shuffle() produce uniform result ?

2007-09-04 Thread Raymond Hettinger
for i in range(10): shuffle(sequence) Raymond Hettinger -- http://mail.python.org/mailman/listinfo/python-list

Re: pop method question

2007-03-03 Thread Raymond Hettinger
nd then in the context of set operations). There was also a notion that threaded programming would benefit by having lookup-then-delete as an atomic transaction. It is unknown to me whether that purported benefit has ever been realized. Raymond Hettinger -- http://mail.python.org/mailman/listinfo/python-list

Re: Python stock market analysis tools?

2007-03-04 Thread Raymond Hettinger
On Mar 4, 7:52 pm, "Mudcat" <[EMAIL PROTECTED]> wrote: > I have done a bit of searching and can't seem to find a stock market > tool written in Python that is active. Anybody know of any? I'm trying > not to re-create the wheel here. What kind of tool do you want? Getting quotes is the easy part:

Descriptor/Decorator challenge

2007-03-04 Thread Raymond Hettinger
I had an idea but no time to think it through. Perhaps the under-under name mangling trick can be replaced (in Py3.0) with a suitably designed decorator. Your challenge is to write the decorator. Any trick in the book (metaclasses, descriptors, etc) is fair game. Raymond how we currentl

Re: list-like behaviour of etree.Element

2007-03-04 Thread Raymond Hettinger
On Mar 4, 12:48 pm, "Daniel Nogradi" <[EMAIL PROTECTED]> wrote: > The etree.Element (or ElementTree.Element) supports a number of > list-like methods: append, insert, remove. Any special reason why it > doesn't support pop and extend (and maybe count)? Those methods would not be hard to add. Perh

Re: calendar (date) iterator?

2007-03-06 Thread Raymond Hettinger
[Marcus] > I'm looking for useful starting points, suggestions, and sample code, > to implement a calendar iterator. Simply, the iterator is seeded with > an initial calendar date, e.g., "03-12-2006", and then subsequent > calls to next return subsequent dates. The seed could be a standard > cale

Re: Descriptor/Decorator challenge

2007-03-06 Thread Raymond Hettinger
[George Sakkis] > What would the semantics be if m is decorated as local only in A or > only in B ? The goal is to as closely as possible emulate the sematics of under- under name mangling. Raymond -- http://mail.python.org/mailman/listinfo/python-list

Re: number generator

2007-03-10 Thread Raymond Hettinger
On Mar 9, 7:32 am, Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote: > In <[EMAIL PROTECTED]>, cesco wrote: > > Given two positive integers, N and M with N < M, I have to generate N > > positive integers such that sum(N)=M. No more constraints. > > Break it into subproblems. Generate a random nu

Re: number generator

2007-03-14 Thread Raymond Hettinger
> To make the solutions equi-probable, a simple approach is to > recursively enumerate all possibilities and then choose one of them > with random.choice(). Since people are posting their solutions now (originally only hints were provided for the homework problem), here's mine: def genpool(n, m):

Re: number generator

2007-03-14 Thread Raymond Hettinger
[Alex Martelli] > map([random.randrange(5) for i in xrange(45)].count, xrange(5)) > > i.e., this gives 5 integers (each between 0 and 45 included) summing to > 45 -- add 1 to each of them to get the desired result. This is a really nice approach. Besides being fast, it is not too hard to see th

Re: performance question

2007-03-14 Thread Raymond Hettinger
[Eric Texier] > I need speed here. What will be the fastest method or does it matter? Follow Alex's advice and use the timeit module, but do not generalize from too small examples; otherwise, the relative timings will be thrown-off by issues like the time to lookup "write" and "a" and "str" (all of

Re: challenge ?

2007-03-22 Thread Raymond Hettinger
On Mar 22, 9:41 am, "alain" <[EMAIL PROTECTED]> wrote: > I have a problem I wonder if it has been solved before. > I have a dictionnary and I want the values in the dictionnary to be > annotated with the rank that would be obtained by sorting the values > > def annotate_with_rank(my_dict): >

Re: Review/commit patch?

2007-04-05 Thread Raymond Hettinger
[Kevin Walzer] > How long does it take for a patch at the Python SF tracker to be > reviewed and/or committed? I am unfamiliar with how the process works. > > (I originally submitted a bug report, then figured out how to patch the > item in question, and subsequently submitted a patch.) Which bug

Re: Review/commit patch?

2007-04-05 Thread Raymond Hettinger
> > [Kevin Walzer] > >> How long does it take for a patch at the Python SF tracker to be > >> reviewed and/or committed? I am unfamiliar with how the process works. > > >> (I originally submitted a bug report, then figured out how to patch the > >> item in question, and subsequently submitted a pat

Re: Sets in Python

2007-09-18 Thread Raymond Hettinger
On Sep 18, 5:39 pm, sapsi <[EMAIL PROTECTED]> wrote: > I recently tried using the set function in Python and was surprised to > find that > > a=[ 1, 2,3, [1,2] ] > > doesn't work with 'set', throwing TyperError (unhashable exception). I > found out that this is because lists can't be hashed. > So,t

Re: Can a base class know if a method has been overridden?

2007-09-24 Thread Raymond Hettinger
On Sep 24, 8:23 am, Ratko <[EMAIL PROTECTED]> wrote: > Hi all, > > I was wondering if something like this is possible. Can a base class > somehow know if a certain method has been overridden by the subclass? > I appreciate any ideas. > Thanks, > > Ratko It's not hard. Both bound and unbound meth

Re: sorteddict PEP proposal [started off as orderedict]

2007-09-26 Thread Raymond Hettinger
[Mark Summerfield] > Below is a PEP proposal for a sorteddict. It arises out of a > discussion on this list that began a few weeks ago with the subject of > "An ordered dictionary for the Python library?" It is worth remembering that the long sought after datatype was a dict that could loop over k

Re: sorteddict PEP proposal [started off as orderedict]

2007-09-26 Thread Raymond Hettinger
[James Stroud ] > Maybe its the PEP killers who act prematurely because I friggin' love > genexps and the little generators they generate. No, it's the PEP author who controls when they ask for pronouncement. The natural instinct is to ask for pronouncement as soon as you have an implementation an

Re: Combine two dictionary...

2007-10-01 Thread Raymond Hettinger
On Oct 1, 10:24 am, Abandoned <[EMAIL PROTECTED]> wrote: > Hi.. > dict1={1: 4, 3: 5}... and 2 millions element > dict2={3: 3, 8: 6}... and 3 millions element > > I want to combine dict1 and dict2 and i don't want to use FOR because > i need to performance. The dict.update approach is the fastest

Re: enumerate overflow

2007-10-03 Thread Raymond Hettinger
[Paul Rubin] > I hope in 3.0 there's a real fix, i.e. the count should promote to > long. In Py2.6, I will mostly likely put in an automatic promotion to long for both enumerate() and count(). It took a while to figure-out how to do this without killing the performance for normal cases (ones used

Re: enumerate overflow

2007-10-03 Thread Raymond Hettinger
On Oct 3, 12:52 pm, koara <[EMAIL PROTECTED]> wrote: > Thanks everybody for the reply and suggestions, I'm glad to see the > issues's already been discovered/discussed/almostresolved. The new code is checked-in. In Py2.6, enumerate() will no longer raise an OverflowError and it will automatically

Re: groupby() seems slow

2007-10-16 Thread Raymond Hettinger
On Oct 15, 8:02 pm, 7stud <[EMAIL PROTECTED]> wrote: > t = timeit.Timer("test3()", "from __main__ import test3, key, data") > print t.timeit() > t = timeit.Timer("test1()", "from __main__ import test1, data") > print t.timeit() > > --output:--- > 42.791079998 > 19.0128788948 > > I thought groupby()

Re: Last iteration?

2007-10-16 Thread Raymond Hettinger
[Diez B. Roggisch] > > out:) But I wanted a general purpose based solution to be available that > > doesn't count on len() working on an arbitrary iterable. [Peter Otten] > You show signs of a severe case of morbus itertools. > I, too, am affected and have not yet fully recovered... Maybe you guy

Re: Last iteration?

2007-10-17 Thread Raymond Hettinger
> def lastdetecter(iterable): > "fast iterator algebra" > lookahead, t = tee(iterable) > lookahead.next() > t = iter(t) > return chain(izip(repeat(False), imap(itemgetter(1), > izip(lookahead, t))), izip(repeat(True),t)) More straight-forward version: d

Re: Last iteration?

2007-10-17 Thread Raymond Hettinger
[Paul Hankin] > def lastdetector(iterable): > t, u = tee(iterable) > return izip(chain(imap(lambda x: False, islice(u, 1, None)), > [True]), t) Sweet! Nice, clean piece of iterator algebra. We need a C-speed verion of the lambda function, something like a K combinator that consum

Re: Organizing Sequential Data (TimeStamps) Overthinking?

2007-10-19 Thread Raymond Hettinger
On Oct 19, 11:26 am, xkenneth <[EMAIL PROTECTED]> wrote: > All, > >Just a quick question. I want to be able to have a data structure > that organizes data (timestamps I'm working with) sequentially, so > that i can easily retrieve the first x amount of timeStamps without > iterating over a list

Re: Organizing Sequential Data (TimeStamps) Overthinking?

2007-10-19 Thread Raymond Hettinger
On Oct 19, 11:26 am, xkenneth <[EMAIL PROTECTED]> wrote: > All, > >Just a quick question. I want to be able to have a data structure > that organizes data (timestamps I'm working with) sequentially, so > that i can easily retrieve the first x amount of timeStamps without > iterating over a list

Re: Organizing Sequential Data (TimeStamps) Overthinking?

2007-10-19 Thread Raymond Hettinger
On Oct 19, 11:26 am, xkenneth <[EMAIL PROTECTED]> wrote: > All, > >Just a quick question. I want to be able to have a data structure > that organizes data (timestamps I'm working with) sequentially, so > that i can easily retrieve the first x amount of timeStamps without > iterating over a list

Re: Set operations on object attributes question

2007-10-23 Thread Raymond Hettinger
[Duane] > LoTuples1 = [(1,1,0),(1,2,1),(1,3,3)] > Set1=set(LoTuples1) > LoTuples2 = [(2,1,3),(2,2,4),(2,3,2)] > Set2=set(LoTuples2) > > What I would like to be able to do is: > > Set3 = Set1union(Set2) > Set3.intersection(Set2, ) > > to return: > set([(2,1,3), (1,3,3)]) > > How can one do this oper

Re: Set operations on object attributes question

2007-10-23 Thread Raymond Hettinger
> Since what I _really_ wanted from this was the intersection of the > objects (based on attribute 2), I was looking for a set-based > solution, > kinda like a decorate - - undecorate pattern. Perhaps > the problem does not fall into that category. The "kinda" part is where the idea falls down.

Re: Set operations on object attributes question

2007-10-23 Thread Raymond Hettinger
[Duane] > Since what I _really_ wanted from this was the intersection of the > objects (based on attribute 2), I was looking for a set-based > solution, > kinda like a decorate - - undecorate pattern. Perhaps > the problem does not fall into that category. Decorating and undecorating do not apply

Re: An efficient, pythonic way to calculate result sets

2007-10-25 Thread Raymond Hettinger
On Oct 25, 8:31 am, [EMAIL PROTECTED] wrote: > I've got a little issue, both programming and performance-wise. I have > a set, containing objects that refer to other sets. For example, in a > simple notation: (, ) (or in a more object-like > display: set(obj1.choices=set(a, b, c) ). There may be ob

Re: An efficient, pythonic way to calculate result sets

2007-10-25 Thread Raymond Hettinger
> Easy exercise of transforming recursion to iteration left to the > reader. Ack! That part was already done. Raymond -- http://mail.python.org/mailman/listinfo/python-list

Re: Proposal: Decimal literals in Python.

2007-10-27 Thread Raymond Hettinger
On Oct 26, 1:54 am, Lennart Benschop <[EMAIL PROTECTED]> wrote: > My proposal: > - Any decimal constant suffixed with the letter "D" or "d" will be > interpreted as a literal of the Decimal type. This also goes for > decimal constants with exponential notation. There's nothing new here that ha

Re: "and" and "or" on every item in a list

2007-10-29 Thread Raymond Hettinger
On Oct 29, 3:57 pm, GHZ <[EMAIL PROTECTED]> wrote: > Is this the best way to test every item in a list? > > def alltrue(f,l): > return reduce(bool.__and__,map(f,l)) > > def onetrue(f,l): > return reduce(bool.__or__,map(f,l)) > > > > >>> alltrue(lambda x:x>1,[1,2,3]) > False > > >>> alltrue(

Re: marshal vs pickle

2007-10-31 Thread Raymond Hettinger
On Oct 31, 6:45 am, Aaron Watters <[EMAIL PROTECTED]> wrote: > I like to use > marshal a lot because it's the absolutely fastest > way to store and load data to/from Python. Furthermore > because marshal is "stupid" the programmer has complete > control. A lot of the overhead you get with the > p

Re: marshal vs pickle

2007-10-31 Thread Raymond Hettinger
On Oct 31, 12:27 pm, Aaron Watters <[EMAIL PROTECTED]> wrote: > Anyway since it's easy and makes sense I think > the next version of nucular will have a > switchable option between marshal and cPickle > for persistant storage. Makes more sense to use cPickle and be done with it. FWIW, I've update

Re: marshal vs pickle

2007-11-01 Thread Raymond Hettinger
On Nov 1, 4:45 am, Aaron Watters <[EMAIL PROTECTED]> wrote: > Marshal is more secure than pickle "More" or "less" make little sense in a security context which typically is an all or nothing affair. Neither module is designed for security. From the docs for marshal: ''' Warning: The marshal mod

Re: Evolving doctests for changing output format

2007-01-10 Thread Raymond Hettinger
[EMAIL PROTECTED] > What I'd like is if I could get doctest to take my tests, and > substitute the obtained output for the provided output. There's currently no support for auto-updating doctests. I think it would make for a good feature request. In the meantime, it may not be difficult to roll

<    1   2   3   4   5   6   7   8   >