dict.keys() ?

2007-01-26 Thread bearophileHUGS
The PEP 3100: http://www.python.org/dev/peps/pep-3100/ says: Return iterators instead of lists where appropriate for atomic type methods (e.g. dict.keys(), dict.values(), dict.items(), etc.); iter* methods will be removed. Better: make keys(), etc. return views ala Java collections??? ... To be re

Re: Fixed length lists from .split()?

2007-01-27 Thread bearophileHUGS
Duncan Booth: > def nsplit(s, sep, n): > return (s.split(sep) + [""]*n)[:n] Another version, longer: from itertools import repeat def nsplit(text, sep, n): """ >>> nsplit("bcsn; 101; 1456", ";", 3) ['bcsn', ' 101', ' 1456'] >>> nsplit("bcsn; 101", ";", 3) ['bc

Re: Executing Javascript, then reading value

2007-01-30 Thread bearophileHUGS
Jean-Paul Calderone: > You might look into the > stand-alone Spidermonkey runtime. However, it lacks the DOM APIs, so > it may not be able to run the JavaScript you are interested in running. > There are a couple other JavaScript runtimes available, at least. This may be okay too: http://www.digi

'First class' Relationships

2007-01-31 Thread bearophileHUGS
Currently reading an article, "First Class Relationships in an Object- oriented Language", by Gavin Bierman and Alisdair Wren: http://homepages.inf.ed.ac.uk/wadler/fool/program/final/4/4_Paper.pdf Found in the "Lambda the Ultimate" blog: http://lambda-the-ultimate.org/node/2013 Maybe it can be do

Re: pil, histogram, mask

2007-02-01 Thread bearophileHUGS
Daniel Nogradi > I don't need the histogram really, only the mean color > value, but as far as I can see the 'mean' attribute only applies to an > image and a mask can not be specified. You can slice parts of the image, and then use the ImageStat.Stat(im).mean On it. Bye, bearophile -- http://m

Re: Inconsistent list/pointer problem

2007-02-01 Thread bearophileHUGS
Doug Stell: The standard module copy has deepcopy, it's slow but it may be a simple solution to your problem. A better solution is to look where data is changed and fix that. Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list

Re: A* search implementation in Python

2007-02-01 Thread bearophileHUGS
Reid Priedhorsky: > I'm looking for an open-source Python implementation of A* search for use > in a mapping application. You can try this one: http://aima.cs.berkeley.edu/python/search.html Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list

Re: Overloading the tilde operator?

2007-02-01 Thread bearophileHUGS
Peter Otten: > No, you will get a syntax error before python even look up the names: There are some tricks that allow the use of "undefined" symbols in Python too, but they are probably just toys. I have recently posted a recipe in the cookbook for that. Bye, bearophile -- http://mail.python.or

Re: compound statement from C "?:"

2007-02-02 Thread bearophileHUGS
Jussi Salmela: > In this particular case you don't need the ternary operator: > print "I saw %d car%s\n" % (n, ("", "s")[n != 1]) The last newline is probably unnecessary. This seems be a bit more readable: print "I saw", n, "car" + ("", "s")[n != 1] With Python 2.5 this looks better: print "I sa

Re: Writing "pythonish" code

2007-02-02 Thread bearophileHUGS
Mizipzor: > To me, the main.py code above looks very ugly. With time, and looking at other people code, you will learn what pythonic means, in the meantime you can remember that into your Python code if you find something that makes you write too much code, or you see something "ugly", then that's

Re: newbie/ merging lists of lists with items in common

2007-02-02 Thread bearophileHUGS
Paddy: >>> _ = [d[x0].append(x1) for x0,x1 in data] I think that you probably want: for text, num in data: d[text].append(num) ardief: > thanks to everyone for the help, and the speed of it! It's really > useful and I will spend some time working on understanding the code > you posted. I'd be s

Re: Jython

2007-02-03 Thread bearophileHUGS
[EMAIL PROTECTED]: > Files aren't lists and thus don't have the functions for iteration. > Try: > def go(): > for line in open("bobo.txt", "r").readlines(): > print line > go() CPython 2.1 has xreadlines, maybe Jython has it too. Bye, bearophile -- http://mail.python.org

Re: Parameter lists

2007-02-04 Thread bearophileHUGS
Mizipzor > I dont like the looks of that code, there are many > function parameters to be sent in and if I were to add an attribute, i > would need to add it in three places. Add it to the function > parameters, add it to the class and assign it. > Is there a smoother way to do this? You may use s

Re: Two mappings inverse to each other: f, g = biject()

2007-02-06 Thread bearophileHUGS
Jonathan Fine: > A google search for biject.py and bijection.py > produced no hits, so I suspect that this may not > have been done before. There are few (good too) implementations around, but they are called bidict or bidirectional dicts. Sometimes I use this implementation, with few changes: htt

Re: Calling J from Python

2007-02-06 Thread bearophileHUGS
Gosi: > There are a number of graphics examples, utilities and demos you can > use in J and combine it with Python. Some of those graphic examples are very nice, I have seen a big site filled with complex fractals, chaotic attractors, etc. Python Zen seems somewhat opposed to part of the J spirit,

Re: Steiner Tree

2007-02-06 Thread bearophileHUGS
Suresh: > I could find GeoSteiner (http://www.diku.dk/geosteiner/) which is > implemented as a C program. Anybody know python wrapper for this? > Anybody tried this program in a python program? Once compiled, you may just need to use it with files calling it through the console with pipes from Py

Re: Does the world need another v0.1 python compiler?

2007-02-08 Thread bearophileHUGS
sturlamolden: > IMHO, with the presence of static types in Py3K, we should have a > static compiler that can be invoked dynamically, just like Common > Lisp. > Something like > > def foo(...): > bar = static_compile(foo, optimize=2) > bar(...) > > JIT compilers are hyped, static compilers perform m

Re: unique elements from list of lists

2007-02-09 Thread bearophileHUGS
Tekkaman: If the sublists contain hashable elements you can use this: def uniter(lists): merge = set() for sub in lists: merge = merge.union(sub) for el in merge: yield el data = [['a', 'b', 'd'], ['b', 'c'], ['a', 'c', 'd']] print list(uniter(data)) But often this t

Re: pygame and python 2.5

2007-02-09 Thread bearophileHUGS
Skip: > Python used to work that way. You'd then silently get errors if the API > changed between version A and version B and you neglected to recompile the > extensions you compiled against version A. Can't the compiled module have one or more test functions that can be used during linking to se

Re: Calling J from Python

2007-02-09 Thread bearophileHUGS
ant: > and in debugging it far outweighs the time you'd spend on all > of that typing in a clean but more verbose language such as Python. Typing time counts a bit too. A language like Java is even more verbose than Python, and that probably slows down the actual programming, compared to less verb

Re: searching a list of lists as a two-dimensional array?

2007-02-11 Thread bearophileHUGS
James Stroud: > import operator > srch = [(i,j) for i in [-1,0,1] for j in [-1,0,1] if (i,j) != (0,0)] > is_adj = reduce(operator.or_, [ary[row+i][col+j] for (i,j) in srch]]) Or maybe (untested), Python V.2.5: srch = [(i,j) for i in [-1,0,1] for j in [-1,0,1] if (i,j) != (0,0)] is_adj = any(ary[r

Re: replacing substrings within strings

2007-02-14 Thread bearophileHUGS
Diez B. Roggisch: > That's the price to pay for immutable strings. Right, but CPython has array.array("c") too. Using Diez Roggisch's code: >>> from array import array >>> arrs = array("c", "010203040506") >>> arrs[:2], arrs[4:5] = arrs[4:6], arrs[:2] >>> arrs.tostring() '0302013040506' Using su

Re: rot13 in a more Pythonic style?

2007-02-14 Thread bearophileHUGS
Martin P. Hellwig > for me (personal) being Pythonic means that I should > separate the logic and variables, etc... Well, for me me Pythonic means using built-in functionalities as much as possible (like using encode("rot13") or translate), and to write less code, (avoiding overgeneralizations fro

RE engines and related matters

2007-02-15 Thread bearophileHUGS
>From Lambda the Ultimate blog, a link to an interesting article about such topics: http://swtch.com/~rsc/regexp/regexp1.html http://swtch.com/~rsc/regexp/ http://lambda-the-ultimate.org/node/2064 Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list

Re: builtin set literal

2007-02-16 Thread bearophileHUGS
Raymond Hettinger: > One of the reasons for the > rejection was that the small benefit of a literal notion was more than > offset by the attendant need for syntactical atrocities like those > listed above. {:} for empty dict and {} for empty set don't look too much atrocious to me. Note: the lan

Re: Help Required for Choosing Programming Language

2007-02-16 Thread bearophileHUGS
Bruno Desthuilliers: > Iftikhar: > > i have read about Python, Ruby and Visual C++. but i want to go > > through with GUI based programming language > > "GUI based programming languages" ? What's that ? Maybe a language like Gui4cli :-) http://users.hol.gr/~dck/g4c/ Bye, bearophile -- http://ma

Re: builtin set literal

2007-02-20 Thread bearophileHUGS
Steven Bethard: > While Python 3.0 is not afraid to break backwards > compatibility, it tries to do so only when there's a very substantial > advantage. I understand, but this means starting already to put (tiny) inconsistencies into Python 3.0... Unrelated: Ruby and Lisp use ? and ! at the end o

Re: Performance project for the SigEx Foundry

2007-02-21 Thread bearophileHUGS
Pablo: > I am looking for articles/studies/benchmarks on the subject. It's not easy to test that, you need to be equally expert on all the languages to test them. This may be a starting point for you: http://shootout.alioth.debian.org/ Bye, bearophile -- http://mail.python.org/mailman/listinfo/

Re: builtin set literal

2007-02-21 Thread bearophileHUGS
Steven Bethard: > take a look at the current state of tuples: >1, 2 >1, >() That's not a good situation. I presume the situation/syntax of tuples in Python 2.x can't be improved. But can it be improved for Py 3.0? Notes: - I think in Matlab a single element is seen as the same thing as

Re: JIT (just-in-tme accelerator) for Python - exists or no?

2007-02-22 Thread bearophileHUGS
On Feb 22, 7:04 pm, [EMAIL PROTECTED] wrote: > Or is any progress going on now? > The JIT in MATLAB or Java seems to be very effective. Have you tried Psyco? Other progress is probably in the PyPy field too. Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list

Re: What is the best queue implemetation in Python?

2007-02-22 Thread bearophileHUGS
John: > I want to write a code for Breadth First Traveral for Graph, which needs a > queue to implement. For that purpose I have used the good deque that you can find in collections in the standard library. It's very good for queues, and it's a bit faster than regular lists for stacks too. Bye, b

Re: Rational numbers

2007-02-23 Thread bearophileHUGS
Martin Manns: > + gmpy is looking pretty unmaintained (dead) to me (newest update of > cvs 10 months ago). I have used it on Py2.5, so it seems to work anyway, and it's fast enough for my purposes. And probably soon some alex-shaped life will show up elsewhere. Bye, bearophile -- http://mail.py

Re: Nested Parameter Definitions

2007-02-25 Thread bearophileHUGS
Virgil Dupras: > Without the call example, I would have > had a hard time to try to figure out what these extra brackets are > for. For this reason, I think that an explicit unpack is more > readable, and thus better. I can't agree. Bye, bearophile -- http://mail.python.org/mailman/listinfo/py

Re: Jobs: Lisp and Python programmers wanted in the LA area

2007-02-26 Thread bearophileHUGS
Tech HR: > In fact, there is a significant faction in > the technical staff (including the CTO) who would like nothing better > than to be able to use Lisp instead of Python. I think CLisp and Python have different enough application areas, so often where one is fit the other can't be much fit. Do

Re: Add images together

2007-02-26 Thread bearophileHUGS
iceman: > What i am trying to do > is to calculate a color-over-time-function for each pixel. Are you using PIL? What does it means color-over-time-function? Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list

Re: Add images together

2007-02-26 Thread bearophileHUGS
On Feb 26, 10:16 pm, "iceman" <[EMAIL PROTECTED]> wrote: > a)Yes, I am using PIL. > b)The color of each pixel over a sequence of frames I think PIL has it for 2 images, you may have to build a binary tree of merged images: http://www.pythonware.com/library/pil/handbook/image.htm#blend Bye, bearop

Re: Preallocate? -- potentially brain dead question about performance

2007-02-26 Thread bearophileHUGS
Jan Danielsson: >newlist = [ None ] * len(mylist) >for i in range(len(mylist)): > newlist.append(int(e[0])) Note that this appends after the Nones, not over them. And note that here the name 'e' is undefined. The most used idiom for that is: newlist = [int(e[0]) for e in mylist] O

Re: Preallocate? -- potentially brain dead question about performance

2007-02-27 Thread bearophileHUGS
Jan Danielsson: >...completely avoiding the design issue I raised altogether. Thanks! > Exactly what I was hoping for! :-) Another common way to do it, it may be a little slower because that n,txt is a tuple: items = set(int(n) for n,txt in mylist) Bye, bearophile -- http://mail.python.org

Re: HTML to dictionary

2007-02-27 Thread bearophileHUGS
Tina I: > I have a small, probably trivial even, problem. I have the following HTML: This is a little data munging problem. If it's a one-shot problem, then you can just load it with a browser, copy and paste it as text, and then process the lines of the text in a simple way (splitting lines accor

Re: how to convert an integer to a float?

2007-02-27 Thread bearophileHUGS
yinglcs, you can use float() or the new division: >>> 1 / 2 0 >>> 1 / float(2) 0.5 >>> from __future__ import division >>> 1 / 2 0.5 Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list

Re: Yet another unique() function...

2007-02-27 Thread bearophileHUGS
MonkeeSage: > Here's yet another take on a unique() function for sequences. It's > more terse than others I've seen and works for all the common use > cases (please report any errors on the recipe page): It's more terse, but my version is built to be faster in the more common cases of all hashable

Re: quickly read a formated file?

2007-03-01 Thread bearophileHUGS
lialie: > The formated file may be very popularly, but the module ConfigPaser > doesn't handle it. Is there a way to process it freely? First try, assuming the input file can be read whole. The code isn't much readable, it needs better variable names (name names?), comments, etc. data = """ %HEAD

Re: Tuples vs Lists: Semantic difference (was: Extract String From Enclosing Tuple)

2007-03-01 Thread bearophileHUGS
George Sakkis, I agree with the things you say. Sometimes you may have a sequence of uniform data with unknown len (so its index doesn't have semantic meaning). You may want to use it as dict key, so you probably use a tuple meant as just an immutable list. I don't know Ruby, but I think it allows

Re: implement random selection in Python

2007-11-16 Thread bearophileHUGS
This recipe of mine may help: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/498229 Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list

Re: overriding methods - two questions

2007-11-16 Thread bearophileHUGS
Donn Ingle: > Say I am in class Basis, doing a loop and I have a list of Child objects. I > want to run the foo() method for each one that *has* a foo() method. This may help (on an old Python version): >>> class Sam: pass ... >>> class Judy: ... def foo(self): pass ... >>> children = [Sam()

Re: the annoying, verbose self

2007-11-22 Thread bearophileHUGS
Alexy: > Sometimes I > avoid OO just not to deal with its verbosity. In fact, I try to use > Ruby anywhere speed is not crucial especially for @ prefix is better- > looking than self. Ruby speed will increase, don't worry, as more people will use it. Bye, bearophile -- http://mail.python.org/ma

Re: multidimensional "arrays"

2007-12-06 Thread bearophileHUGS
Horacius ReX: > do you know how to do similar but in two dimensions ? >>> nr = 3 >>> nc = 4 >>> [[None] * nc for _ in xrange(nr)] [[None, None, None, None], [None, None, None, None], [None, None, None, None]] Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list

Re: searching a value of a dict (each value is a list)

2007-12-09 Thread bearophileHUGS
Seongsu Lee: > What do you think of this? Ideas with less space complexity? You can put the second group of keys in a second dictionary, so you don't have to mangle them, and it may be a bit faster. Regarding the space complexity, I don't know how you can reduce it with Python. Probably you can c

Re: searching a value of a dict (each value is a list)

2007-12-09 Thread bearophileHUGS
Jeremy C B Nicoll: > The code someone else posted to reverse the keys is all very well, but > surely hugely wasteful on cpu, maybe storage, and elapsed time. If you are talking about my D code then I know it, the creation of the first dict has to be skipped, if possible... The code I have posted m

Re: searching a value of a dict (each value is a list)

2007-12-10 Thread bearophileHUGS
Adonis Vargas: > Also, you should never use reserved words like 'dict' this creates > confusion and can cause Python to misbehave since you are rebinding the > name. > Adonis Vargas After hearing this suggestion for the 300th time, I think it may be the moment to fix this problem in Python3, and m

Re: searching a value of a dict (each value is a list)

2007-12-10 Thread bearophileHUGS
Seongsu Lee: >I have a dictionary with million keys. Each value in the dictionary has a list >with up to thousand integers.< Let's say each integer can be represented with 32 bits (if there are less numbers then a 3-byte representation may suffice, but this makes things more complex), that is 2^2

Re: Stringified list back to list of ints

2007-12-12 Thread bearophileHUGS
Another solution, possibly safer: >>> from cStringIO import StringIO >>> import csv >>> s = "[16, 16, 2, 16, 2, 16, 8, 16]" >>> sf = StringIO(s.strip()[1:-1]) >>> list(csv.reader(sf)) [['16', ' 16', ' 2', ' 16', ' 2', ' 16', ' 8', ' 16']] Bye, bearophile -- http://mail.python.org/mailman/listinf

Re: efficient data loading with Python, is that possible possible?

2007-12-13 Thread bearophileHUGS
igor: > The fundamental difference is that in C++, I create a single object (a > line buffer) that's reused for each input line and column values are > extracted straight from that buffer without creating new string > objects. In python, new objects must be created and destroyed by the > million wh

Re: are docstrings for variables a bad idea?

2006-04-21 Thread bearophileHUGS
Docstrings for variables seems a new interesting idea to me, but I don't know how much useful it can be. Do you mean something like this? >>> rcar_speed = 25 >>> print rcar_speed 25 >>> print rcar_speed.__doc__ int(x[, base]) -> integer ... >>> rcar_speed.__ndoc__ = "Speed of the red car, km/h" ..

Re: Pythonesque interface.

2006-04-21 Thread bearophileHUGS
Michael Tobis>Yes but he obviously wants this to be delivered to the browser.< I think Jython can be used to create applets that run with the JavaVM. Can't it be used to solve the OP problem (even without PIL)? Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list

Re: Pythonesque interface.

2006-04-22 Thread bearophileHUGS
Gaz: > Right now im trying to dl Jython (SF.net server down?), if it's > language sintaxis is just like Python and allows to use numpy and PIL, > im in! (i think :) ) I don't think you can do that, but you can create and show images anyway (and maybe read the pointer position too). Sorry for the "

Re: Uniquifying a list?

2006-04-22 Thread bearophileHUGS
There is my version too: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/438599 Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list

Re: list example

2006-04-22 Thread bearophileHUGS
PAolo>any comment, suggestion? Is there something not elegant?< Here you can see many little differences, some of them reflect just my style, but some other of them are Python standard style guidelines: even = [] odd = [] for i in xrange(1, 10): if i % 2: odd.append(i)

Re: The whitespaceless frontend

2006-04-25 Thread bearophileHUGS
Stelios Xanthakis: >in my opinion nested functions are not so important and I wouldn't spend any >time to improve them. Usually you can do anything with classes< Some people like and use them often (like those ones coming from Pascal-like languages, etc), some other people (like those coming fro

Re: do while loop

2006-04-26 Thread bearophileHUGS
Rick Zantow>In any case, what would you want to do that you can't do (in some way) now?< You can do all things already, that's not the point, I presume. Some things added in the last years were already possibile in different ways. Rick Zantow>If you have a compelling use case,< I agree that suc

ANN: ShedSkin 0.0.8

2006-05-03 Thread bearophileHUGS
Just released the version 0.0.8 of ShedSkin, the Python ==> C++ compiler. Blog, the last post contains some notes about Summer of Code and some open problems: http://shed-skin.blogspot.com/ Thesis about SS, with lot of info, useful for people that want to help this project too: http://kascade.org

Re: ANN: ShedSkin 0.0.8

2006-05-03 Thread bearophileHUGS
Sorry, the correct link to the thesis: http://kascade.org/shedskin.pdf bearophile -- http://mail.python.org/mailman/listinfo/python-list

Re: list*list

2006-05-03 Thread bearophileHUGS
Ziga Seilnach: >c = map(operator.mul, a, b) Usually I like map a lot, but this time for me the l.c. version is a bit simpler to understand (even if it's longer, and maybe slower too): >>> from operator import mul >>> from itertools import izip >>> a = [1, 2, 3] >>> b = [4, 5, 6] >>> map(mul, a, b

Re: data entry tool

2006-05-10 Thread bearophileHUGS
Peter wrote>Wow - why so big for such a simple tool? 2MB sounds like a LOT of coding.< Yes, it's a lot of code, but it's code written by other people (Python, Tkinter). Using Tkinter your program will probably be quite short, even if you use some dbase. If the data to be entered is simple and text

Re: comparing values in two sets

2006-05-14 Thread bearophileHUGS
Note that you are comparing ordered sequences, like lists, tuples, strings, etc, and not sets. Something like this can be a little improvement of your code, it avoids building the zipped list, and scans the iterable unpacking it on the fly: from itertools import izip def test_sets(original_set, tr

Re: comparing values in two sets

2006-05-14 Thread bearophileHUGS
So you probably have to change the function test_sets name, because it's not much useful on real sets. Can't you use the == or != operators on those sequences? Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list

Re: Large Dictionaries

2006-05-15 Thread bearophileHUGS
Roy Smith: > I am befuddled as to why > people thought creating a dict by keyword would be a useful thing to > do, but left out (and, indeed, eliminated the chance to add the syntax > later) the obviously useful ability to hint at the size. Adding the keyword syntax doesn't require much memory to

Re: Sorting of list containing tuples

2006-05-18 Thread bearophileHUGS
>>> l = [(2,3),(3,2),(6,5)] >>> from operator import itemgetter >>> sorted(l, key=itemgetter(1), reverse=True) [(6, 5), (2, 3), (3, 2)] Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list

Re: newb: comapring two strings

2006-05-19 Thread bearophileHUGS
I think a way to solve the problem may be: 1) create a little Python script to separate the original words in many files, each one containing only words of the same length. Every filename can contain the relative word length. 2) write a little C program with two nested loops, that scans all the pai

Re: newb: comapring two strings

2006-05-19 Thread bearophileHUGS
> I have suggested C because if the words are all of the same length then > you have 3^2 = 90 000 000 000 pairs to test. Sorry, you have (n*(n-1))/2 pairs to test (~ 45 000 000 000). bearophile -- http://mail.python.org/mailman/listinfo/python-list

Re: bitstream

2006-05-19 Thread bearophileHUGS
Maybe this is what you are looking for: http://cheeseshop.python.org/pypi/BitBuffer/0.1 Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list

Re: newb: comapring two strings

2006-05-19 Thread bearophileHUGS
Paul Rubin>Still terrible. Use a better algorithm!< I agree, it's O(n^2), but if you need to run this program just 1 time, and the program is in C, and you don't want to use much time to think and code a better algorithm (or you aren't able to do it) then maybe that naive solution can be enough,

Re: Speed up this code?

2006-05-26 Thread bearophileHUGS
If you are interested in such programs, you can take a look at this one too: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/366178 It requires more memory, but it's quite fast. Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list

Re: Speed up this code?

2006-05-26 Thread bearophileHUGS
I have tried this comparison, with a version I've modified a bit, I have encoutered a problem in sieve_all, for example with n=1, I don't know why: def sieve_all(n=100): # yield all primes up to n stream = iter(xrange(2, n)) while True: p = stream.next() yield p

Re: chop() and empty() functions

2006-05-27 Thread bearophileHUGS
Jeremy L. Moles>It's just an iterative way to say, "Okay, give me some default behavior for everything, and I'll come back around later and set the explicit handlers later."< There's some correlation with the Null Object pattern: http://www.cs.oberlin.edu/~jwalker/nullObjPattern/ Bye, bearophile

Re: Fate of itertools.dropwhile() and itertools.takewhile()

2007-12-29 Thread bearophileHUGS
Almost every day I write code that uses itertools, so I find it very useful, and its functions fast. Removing useless things and keeping things tidy is often positive. But I can't tell you what to remove. Here are my usages (every sub-list is sorted by inverted frequency usage): I use often or ver

Two candies

2008-01-02 Thread bearophileHUGS
Two little things I may like added. 1) A fast and memory efficient way to create an array.array at a certain size. At the moment I can see some ways to do it: from array import array from itertools import repeat a = array("l", xrange(n)) #1 a = array("l", [0]*n)) #2 a = array("l", repeat(0, n)) #

Re: Two candies

2008-01-02 Thread bearophileHUGS
First of all, thank you Raymond for your answer, and a happy new year to you and to all the Python group :-) Raymond: >#3 is a fine choice. It is memory efficient -- the repeat() itertool takes-up >only a few bytes. It doesn't need psyco, you already have to fast C routines >talking to each ot

Re: Two candies

2008-01-02 Thread bearophileHUGS
Raymond: >though you have to be very careful about what you measure, how you measure it, >that the system state hasn't changed between measurements, and how your >interpret the results).< Right. This is part of the list of things they teach you to care of when you want to make experiments in bi

Re: Details about pythons set implementation

2008-01-05 Thread bearophileHUGS
Sion Arrowsmith: > Because ... how to be polite about this? No, I can't. std::set is > crap. The implementation is a sorted sequence What about using hash_map instead? You can use it with GCC too (but you have to use a trick if you want to use string keys). Bye, bearophile -- http://mail.python.

Re: dictionary/hash and '1' versus 1

2008-01-05 Thread bearophileHUGS
Paddy: > Not really, it seems to me to be going the exact opposite way with > languages with automatic type conversions being seen as not suited for > larger programs. In Java you can add the number 1 to a string, and have it automatically converted to string before the string join... What do you

Re: Point Object

2008-01-06 Thread bearophileHUGS
Pete: > Translate the hexadecimal form > into decimal and confirm that they match. No need to convert the IDs... Soviut: > You shouldn't have to compare the hex IDs. Just a simple comparison > operator will work: > > firstPoint = Point() > secondPoint = Point() > print(firstPoint == secondPoint

Re: "Canonical" way of deleting elements from lists

2008-01-09 Thread bearophileHUGS
Robert Latest: > Fredrik Lundh wrote: > > keywords = filter(None, keywords) # get "true" items only > > Makes seinse. BTW, where can I find all methods of the built-in types? > Section 3.6 only talks about strings and mentions the list append() method > only in an example. Am I too stupid to re

Re: alternating string replace

2008-01-09 Thread bearophileHUGS
My version, uses a re.sub, plus a function used as an object with a one bit state: from re import sub def repl(o): repl.n = not repl.n return ":" if repl.n else "," repl.n = False print sub("_", repl, "hi_cat_bye_dog_foo_bar_red") Bye, bearophile -- http://mail.python.org/mailman/listi

Re: stupid/style/list question

2008-01-09 Thread bearophileHUGS
Duncan Booth: > I tried to measure this with timeit, and it looks like the 'del' is > actually quite a bit faster (which I find suprising). Yes, it was usually faster in my benchmarks too. Something similar is true for dicts too. I think such timings are influenced a lot by the garbage collector.

Re: Collecting Rich Data Structures for students

2008-01-09 Thread bearophileHUGS
It may be better to keep the data in a simpler form: data = """\ 42 40 73 45 Albany, N.Y. 35 5 106 39 Albuquerque, N.M. 35 11 101 50 Amarillo, Tex. 34 14 77 57 Wilmington, N.C. 49 54 97 7 Winnipeg, Man., Can.""" cities = {} for line in data.splitlines(): a1, a2, a3, a4, n = line.split(" ", 4)

Re: Converting a bidimensional list in a bidimensional array

2008-01-09 Thread bearophileHUGS
Santiago Romero: > - Speed Performance: Do you think that changing from list to Array() > would improve speed? I'm going to do lots of tilemap[y][x] checks (I > mean, player jumping around the screen, checking if it's falling over > a non-zero tile, and so). First of all: if you have enough memory

Re: alternating string replace: Extended input (Long).

2008-01-09 Thread bearophileHUGS
Donald 'Paddy' McCarthy: [... lots and lots and lots of tests...] C'mon Paddy, where are the timings too? Are you becoming lazy lately? ;-) Bear bugs, bearophile -- http://mail.python.org/mailman/listinfo/python-list

Re: alternating string replace

2008-01-09 Thread bearophileHUGS
Gordon C: > This is very cool stuff but I suspect that the code is unreadable > to many readers, including me. Just for fun here is a complete program, > written in Turbo Pascal, circa 1982, that does the job. Readable > n'est pas? I think it's quite readable, especially if you indent it more cor

Re: alternating string replace

2008-01-11 Thread bearophileHUGS
Dennis Lee Bieber: > So� in Python, your str[n] := > ':' just can not be done! You would have to create a new string > containing everything in front of n, the ':', and then everything behind > n (skipping n itself, of course). This is a painfully slow operation in > Python as it allocates memory f

Re: Converting a bidimensional list in a bidimensional array

2008-01-11 Thread bearophileHUGS
Santiago Romero: > If each integer-python-object takes 16 bytes, this makes 6 * 16 = > almost 1MB of memory just for the tilemaps... > Using array of type H (16 bits per item = 2 bytes), my maps take just > 6*2 = 120KB of memory. > Do you think I should still go with lists instead of an

Re: Magic function

2008-01-12 Thread bearophileHUGS
Steven D'Aprano: > As simple as the above is, it could be made simpler. Judging from the > example given, the Bigobj constructor doesn't need a keyword argument, > it could just as easily take an arbitrary number of arguments: > bigobj = Bigobj(obj1, obj2, obj3, obj4...) I agree; "Things should be

Re: Data mapper - need to map an dictionary of values to a model

2008-01-15 Thread bearophileHUGS
Luke: >What design patterns would you use here?< What about "generator (scanner) with parameters"? :-) Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list

Re: Python too slow?

2008-01-15 Thread bearophileHUGS
Paul Boddie: > what is everyone with any degree of > concern about Python's performance doing to improve the situation? They are probably developing systems like Cython and ShedSkin, and hoping to see Psyco improved again to manage itertools better (and maybe 64 bit CPUs too). > Sure, C (or actu

Re: Python too slow?

2008-01-15 Thread bearophileHUGS
[EMAIL PROTECTED]: > A lecturer gave me the perfect answer to the question of speed. > "You have two choices when it comes to programming. Fast code, or fast > coders." I don't believe that anymore, ShedSkin compiles slowly and it has limitations still, but it shows that it's possible to create a

Re: Benchmark [was Re: common problem - elegant solution sought]

2008-01-15 Thread bearophileHUGS
Helmut Jarausch: > The clear winner is > > def del_by_key(L,key) : >for pos, (k,d) in enumerate(L): > if k == key : >del L[pos] >break If you use Psyco this is faster: def del_by_key(L,key): pos = 0 for pair in L: if pair[0] == key : del L[pos]

Re: Data mapper - need to map an dictionary of values to a model

2008-01-15 Thread bearophileHUGS
Luke: > I'm not familiar with this pattern. I will search around, but if you > have any links or you would like to elaborate, that would be > wonderful. :) It's not a pattern, it's a little thing: def line_filter(filein, params): for line in filein: if good(line, params): yield extrac

Re: Replace stop words (remove words from a string)

2008-01-17 Thread bearophileHUGS
Raymond Hettinger: > Regular expressions should do the trick. > >>> stoppattern = '|'.join(map(re.escape, stoplist)) > >>> re.sub(stoppattern, '', mystr) If the stop words are many (and similar) then that RE can be optimized with a trie-based strategy, like this one called "List": http://search.cp

Re: array and list

2008-01-18 Thread bearophileHUGS
J. Peng>why perl call it array and python call it list?< Unfortunate naming, I'd say. Calling list a dynamic array is silly, despite all the things you may say about abstract data types having the correct methods, etc. Paddy: > I guess 'under the hood' Python (& Perl?), arrays might be more like

Re: Efficient processing of large nuumeric data file

2008-01-18 Thread bearophileHUGS
Matt: > from collections import defaultdict > > def get_hist(file_name): > hist = defaultdict(int) > f = open(filename,"r") > for line in f: > vals = line.split() > val = int(vals[0]) > try: # don't look to see if you will cause an error, > # just c

<    1   2   3   4   5   6   7   8   9   10   >