Re: strip module bug

2008-10-13 Thread bearophileHUGS
Poppy: > var = "detail.xml" > print var.strip(".xml") ### expect to see 'detail', but get 'detai' > var = "overview.xml" > print var.strip(".xml") ### expect and get 'overview' Python V.2.5 is not flawless, but you can't find bugs so easily. I've found only two bugs in about three years of conti

Re: Append a new value to dict

2008-10-13 Thread bearophileHUGS
jdd: > foo = {'bar': 'baz'} > foo.update({'quux': 'blah'}) That creates a new dict, to throw it away. Don't do that. Use the standard and more readable syntax: > foo = {...} > foo['quux'] = 'blah' Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list

docpicture

2008-10-13 Thread bearophileHUGS
In Python code that processes some geometrical data I want to explain what each variable like w1, w2, h2, h3, etc, means in the geometrical objects. In such situation I don't use longer and more clear variable names because in geometry I'm used to use short vertex/line/length names, finding them mo

Re: docpicture

2008-10-14 Thread bearophileHUGS
André: > Ok, the following is my first attempt at implementing this idea. I suggest you to change the program you use to encode your images, because it's 1000 bytes, while with my program the same 256 colors image needs just 278 bytes: iVBORw0KGgoNSUhEUgAAABYeCAMfOR5kBGdBTUEAAL GP

Re: docpicture

2008-10-14 Thread bearophileHUGS
Steven D'Aprano: > Unless bearophile is willing to share his code, There's no code: all I do is written in my post, and so far I have done it "manually" :-) Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list

Re: docpicture

2008-10-14 Thread bearophileHUGS
André: > A more complete example is now available at > http://code.activestate.com/recipes/576538/ Nice. >The idea for this recipe was mentioned on the Python mailing list as something >desirable and apparently done by someone< That someone has a nickname you can use, I am known in the cookboo

Re: xor: how come so slow?

2008-10-15 Thread bearophileHUGS
Few suggestions for your code: - Use xrange instead of range. - Loop over lists where you can instead of their indexes. - array.array("B", somestring) may help you because it gives a byte "view" of a string. - Using psyco helps a lot for such kind of code. - I think numpy arrays can contain text/ch

Re: How to transfer data structure or class from Python to C/C++?

2008-10-15 Thread bearophileHUGS
Hongtian: > Could you please guide me to do that? or tell me some document to have > a research? You can start googling for: - SWIG - Boost.Python - SIP - ctypes (built-in module) - And more. Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list

Re: default value in __init__

2008-10-16 Thread bearophileHUGS
Chris Rebert: > Although primitive and likely somewhat flawed, you may find the > statistics in the "Compatibility Issues" section > ofhttp://mail.python.org/pipermail/python-3000/2007-February/005704.html > to be of interest. I am quite glad to see that I am not the only one that cares for such

Re: xor incongruences

2008-10-16 Thread bearophileHUGS
Michele: > in Java this block has an hash which is different from the Python one. Note that integer numbers in Python are multiprecision by default, this may cause differences. You can put some prints in various stages of the data flow (or breakpoints for your debuggers, etc) to spot where the va

Re: Dictionary of Dicts question

2008-10-17 Thread bearophileHUGS
MRAB: > for line in open(path): > fields = line.split("\t") > data[tuple(fields[ : 2])] = fields[2 : ] Keeping the key as a string may have some memory/performance advantages (not tested): for line in open(path): fields = line.split("\t") data[fields[0] + fields[1]] = map(float, i

Re: algorizm to merge nodes

2008-10-17 Thread bearophileHUGS
JD, you probably need the algorithm for connected components of an undirected graph. For example you can do that with my graph lib: http://sourceforge.net/projects/pynetwork/ from graph import Graph g = Graph() data = [['a', 'b'], ['c', 'd'], ['e', 'f'], ['a', 'g'], ['e', 'k'], ['c', 'u'], ['b',

Re: algorizm to merge nodes

2008-10-17 Thread bearophileHUGS
JD: > Thanks, > This one really works. Note that you can save some RAM (almost half) creating a directed graph, because later the connectedComponents() manages the arcs as undirected anyway: >>> from graph import Graph >>> g = Graph() >>> data = [['a', 'b'], ['c', 'd'], ['e', 'f'], ['a', 'g'], ['

heapreplace, methodcaller

2008-10-18 Thread bearophileHUGS
Hello, I'm experimenting more with Python 2.6 and its numerous changes. To improve name coherence I think this method of the heapq module: heapq.heapreplace(heap, item) can grow an alias in Python 2.6.1/2.7 and 3.0/3.1: heapq.heappoppush(heap, item) So later the heapreplace() name can be depreca

Re: Interoperating with C

2008-10-18 Thread bearophileHUGS
Michele: > I would like to call C functions in a Python program, First of all take a look at the standard module ctypes. Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list

Re: indentation

2008-10-19 Thread bearophileHUGS
Derek Martin: > I know of several people who favor the idea of "indent with tab, align > with space." [...] I favor this myself actually, [...] Thanks Guido, in Python3 this is finally a Syntax Error (I have asked for this probably about three years ago). Unfortunately the new Python-syntax-based

Re: Porting VB apps to Python for Window / Linux use

2008-10-19 Thread bearophileHUGS
Stef Mientki: > it's just Object Pascal , which is inferior to Python. They are quite different languages, you can't compare them in a simple way. Delphi is statically typed, and compiles very quickly producing "small" exes; "algorithmic" code can run a hundred times faster than Python code. There

Re: regexp in Python (from Perl)

2008-10-19 Thread bearophileHUGS
MRAB: > The regular expression changes the last sequence of digits to > "9" ("192.168.1.100" => "192.168.1.9") but the other code replaces the > last digit ("192.168.1.100" => "192.168.1.109"). Uhmm, this is a possible alternative: >>> s = " 192.168.1.100 " >>> ".".join(s.strip().split(".")[:3])

Re: Append a new value to dict

2008-10-22 Thread bearophileHUGS
Frank Niemeyer: > There's simply no > way to increment a non-existent value - not without performing some > obscure implict behind-the-scenes stuff. Like importing and using a defaultdict(int). > > So you > > either have to use a workaround: > > >  >>> try: > > ...   counter['B'] += 1 > > ... ex

Re: Ordering python sets

2008-10-22 Thread bearophileHUGS
Mr.SpOOn: > Is there another convenient structure or shall I use lists and define > the operations I need? As Python becomes accepted for more and more "serious" projects some more data structures can eventually be added to the collections module: - SortedSet, SortedDict: can be based on red-blac

Re: Append a new value to dict

2008-10-23 Thread bearophileHUGS
Marc 'BlackJack' Rintsch: > counter['B'] = counter.get('B', 0) + 1 If you benchmark it, you will find that using the get() method it's quite slower. Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list

Re: "Find" in list of objects

2008-10-23 Thread bearophileHUGS
Andreas Müller: > is there a construct like > list.find (10, key='ID') You can create yourself a little convenience function, or you can use something like the following. First some testing code: class C: def __init__(self, id): self.id = id def __repr__(self): return "<%s

Re: "Find" in list of objects

2008-10-23 Thread bearophileHUGS
Andreas Müller: > is there a construct like > list.find (10, key='ID') Given the current Python a syntax like this is more probable: somelist.find(10, key=attrgetter('ID')) Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list

Re: Slow comparison between two lists

2008-10-23 Thread bearophileHUGS
Hrvoje Niksic: > internal = set(list_internal) ... To do that the original poster may have to define a __hash__ and __eq__ methods in his/her class. Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list

Re: Slow comparison between two lists

2008-10-23 Thread bearophileHUGS
Hrvoje Niksic: > You're right.  The OP states he implements __eq__, so he also needs a > matching __hash__, such as: > >     def __hash__(self, other): >         return (hash(self.xcoord) ^ hash(self.ycoord) ^ >                 hash(self.streetname) ^ hash(self.streetno)) The hash function by Otte

Re: Append a new value to dict

2008-10-23 Thread bearophileHUGS
slais-www: > Slower than > ... Okay, I seen there's a little confusion, I try to say it more clearly. Generally this is the faster version (faster than the version with get), especially if you use Psyco: version 1) if 'B' in counter: counter['B'] += 1 else: counter['B'] = 1

set/dict comp in Py2.6

2008-10-25 Thread bearophileHUGS
I'd like to know why Python 2.6 doesn't have the syntax to create sets/ dicts of Python 3.0, like: {x*x for x in xrange(10)} {x:x*x for x in xrange(10)} Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list

Re: PIL: Getting a two color difference between images

2008-10-25 Thread bearophileHUGS
Kevin D. Smith: > What I want is a two color output image: black where the image wasn't > different, and white where it was different.< There are several ways to do that. If speed isn't essential, then you can create a third blank image of the right size, and then use the method that iterates on

collections.chain

2008-10-25 Thread bearophileHUGS
Several languages like Java, C# etc have a List type in the std lib. Python has a built-in list(), it's implemented as array dynamic on the right. Not too much time ago Hettinger has added a collections.deque (its C code is really nice), that compared to list() allows a faster append on the right

Re: set/dict comp in Py2.6

2008-10-25 Thread bearophileHUGS
Sorry for the answering delay, Google Groups is slow today. Steven D'Aprano: >Personally, I don't see the advantage of set and dict comprehensions. I think >the value of them is very marginal, not worth the additional syntax.< If it's worth in 3.0 then it's worth in 2.6 too. If it isn't worth i

Re: Ordering python sets

2008-10-27 Thread bearophileHUGS
Glenn Linderman: > how does one create a key that corresponds to ascending integer followed by > descending character string? (Others may have already answered you because Google groups is very slow.) >>> seq = [(10, "abb"), (5, "zul"), (5, "hal"), (2, "of")] >>> sorted(seq, key=lambda (n,s): (

Re: Limit between 0 and 100

2008-10-27 Thread bearophileHUGS
(Sorry for the answering delay, Google groups is very slow.) James: >P.S. I don't understand a lot of what I have there, I got most of it from the >beginning tutorials and help sections. I have never programmed before, but >this is for a school assignment.< You must understand what you do at s

Re: big objects and avoiding deepcopy?

2008-10-27 Thread bearophileHUGS
Robert Kern: > This is similar to implementing "Undo" functionality in applications.< In a quite-high-level language (like Python, but not necessarily in Python itself) it may become eventually advantageous to add some (even limited) built-in form of undo. Both to give a simpler way to implement a

Re: Ordering python sets

2008-10-27 Thread bearophileHUGS
Lie Ryan: >Oh no, the two dict implementation would work _exactly_ the same from the >outside, they are transparently interchangeable. Only the performance >characteristic differs because of the different implementation.< I don't agree with the general idea. If the operations done by your data

Re: Database specialized in storing directed graphs?

2008-10-28 Thread bearophileHUGS
Sorry Carl Banks for the answering delay, there are problems in Google Groups. > This is not to study graph theory; I'm using the graph to represent a > problem domain. The graphs could be arbitrarily large, and could > easily have millions of nodes, and most nodes have a substantial > amount of

Re: Improving interpreter startup speed

2008-10-29 Thread bearophileHUGS
Terry Reedy: > The current developers, most of whom use Python daily, [...] Thank you for bringing some light in this thread so filled with worse than useless comments. Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list

Re: Is psyco available for python 2.6?

2008-10-30 Thread bearophileHUGS
sert: > I used the windows installer for the latest version of psyco, > which is labeled as compatible with 2.5, but it gives the > following error: > ImportError: DLL load failed: The specified module could not be > found. (check that the compiled extension 'C:\Python26\lib\site- > packages\psyco\

Re: Testing dictionary results with doctest

2008-10-31 Thread bearophileHUGS
Joe Strout: > What's the standard solution for this? I don't know of any standard solution, I generally sort the items in some ways, or add the result, that has to be equal: >>> r = foo() >>> r == {'object': 'rain', 'location': 'Spain', 'subloc': 'train'} True > Does doctest have some special wa

Re: brackets content regular expression

2008-10-31 Thread bearophileHUGS
netimen: > Thank's but if i have several top-level groups and want them match one > by one: > text = "a < b < Ó > d > here starts a new group:  < e < f  > g >" What other requirements do you have? If you list them all at once people will write you the code faster. bye, Bearophile -- http://mail.p

Re: Ordering python sets

2008-11-01 Thread bearophileHUGS
Lie Ryan: >Although you said you disagree with the general idea, you actually take the >idea two steps further, I take that as an implicit agreement to several parts >of the idea.< Think about a bridge: building half bridge may be bad/useless, while building it whole may lead to something useful

Re: Fast list traversal

2008-11-02 Thread bearophileHUGS
dineshv: > What is the fastest way to traverse these long_list's sequentially > from the beginning to the end?  Maybe there is another data structure > that can be used instead of a list. Psyco can help a lot in that kind of code. >The elements of long_list are immutable (ie. don't change).< A

Re: Fast list traversal

2008-11-02 Thread bearophileHUGS
Steven D'Aprano: > The only solutions to that are to reduce the amount of > computation in each loop, reduce the number of items, or get a faster > computer. Changing language too is an option :-) Languages like Java, D, C, C++ may help :-) Bye, bearophile -- http://mail.python.org/mailman/listin

Re: Structures

2008-11-03 Thread bearophileHUGS
Paulo J. Matos: > Since Python focus > on having one way to do it and structures are something like classes > with only public methods, if I want structures that's what I should use. > Is that right? Yes, it is. On the other hand in Python 2.6 there's something that helps you build one of such cla

Re: length of a tuple or a list containing only one element

2008-11-03 Thread bearophileHUGS
Steve Holden: > While this kind of beginner > mistake is common it isn't one that's frequently repeated once the > learner understands the syntax. You may be right, but I don't have to like it. When you teach programming to people that have never done it before, and you use Python, they spot simil

Re: length of a tuple or a list containing only one element

2008-11-03 Thread bearophileHUGS
TP: > This is actually the length of a bracketed string, not a tuple. > Tuple's are defined by the existence of a comma...try: > >>> len(('foo',)) > 1 Time ago I have suggested to change the tuple literal, to avoid the warts of the singleton and empty tuple, that may lead to bugs. But using ASCII

Re: Replacing cmp with key for sorting

2008-11-03 Thread bearophileHUGS
On Nov 3, 6:49 pm, George Sakkis <[EMAIL PROTECTED]> wrote: > I want to sort sequences of strings lexicographically but those with > longer prefix should come earlier, e.g. for s = ['a', 'bc', 'bd', > 'bcb', 'ba', 'ab'], the sorted sequence is ['ab', 'a', 'ba', 'bcb', > 'bc', 'bd']. Currently I do

Re: length of a tuple or a list containing only one element

2008-11-03 Thread bearophileHUGS
Arnaud Delobelle: >And introduces some new inconsistencies for newcomers, e.g. > s = {1, 2, 3} # A set with 3 elements > s = {1} # A set with one element > s = {} # Surely, this should be an empty set!! Are you able to list other inconsistencies? Python3 introduces one or two warts, but removes

Re: Replacing cmp with key for sorting

2008-11-03 Thread bearophileHUGS
Alan G Isaac: > Probably not what you had in mind ... > ... > >>> maxlen = max(len(si) for si in s) >      >>> def k(si): return si+'z'*(maxlen-len(si)) This looks a little better: assert isinstance(s, str) sorted(s, key=lambda p: p.ljust(maxlen, "\255")) If the string is an unicode that ma

Re: Replacing cmp with key for sorting

2008-11-03 Thread bearophileHUGS
Arnaud Delobelle: > Here's another idea, probably more practical: > >>> sorted(s, key=lambda x: tuple(256-ord(l) for l in x), reverse=True) Nice. A variant that probably works with unicode strings too: print sorted(s, key=lambda x: [-ord(l) for l in x], reverse=True) Bye, bearophile -- http://ma

Re: Replacing cmp with key for sorting

2008-11-03 Thread bearophileHUGS
Arnaud Delobelle: > It's funny how the obvious escapes me so often. In this case it's a well known cognitive effect: the mind of humans clings to first good/working solution, not allowing its final tuning. For that you may need to think about something else for a short time, and then look at your

Re: Replacing cmp with key for sorting

2008-11-03 Thread bearophileHUGS
George Sakkis: > but I guess there's not much more room for improvement. That's nonsense, Python is a high level language, so there's nearly always room for improvement (even in programs written in assembly you can generally find faster solutions). If speed is what you look for, and your strings a

Re: split() and string.whitespace

2008-11-04 Thread bearophileHUGS
MRAB: > It's interesting, if you think about it, that here we have someone who > wants to split on a set of characters but 'split' splits on a string, > and others sometimes want to strip off a string but 'strip' strips on > a set of characters (passed as a string). That can be seen as a little in

Re: Parse each line by character location

2008-11-04 Thread bearophileHUGS
George Sakkis: > Here's a general solution for fixed size records: > >>> def slicer(*sizes): > > ...     slices = len(sizes) * [None] > ...     start = 0 > ...     for i,size in enumerate(sizes): > ...         stop = start+size > ...         slices[i] = slice(start,stop) > ...         start = stop

Re: Building loop with some exceptions?

2008-11-04 Thread bearophileHUGS
Gilles Ganault: > Thanks a lot but... I don't know what the above means :-/ set(iterable) just builds a set, then you use the really usual set semantics. Anyway, maybe you may find this more easy to understand: refused_indexes = set([4, 34, 40, 44, 48, 54, 57, 67, 76, 83, 89]) for i in xrange(1,

Re: Is there a better/simpler way to filter blank lines?

2008-11-04 Thread bearophileHUGS
tmallen: > I'm parsing some text files, and I want to strip blank lines in the > process. Is there a simpler way to do this than what I have here? > lines = filter(lambda line: len(line.strip()) > 0, lines) xlines = (line for line in open(filename) if line.strip()) Bye, bearophile -- http://mail.

Re: Structures

2008-11-04 Thread bearophileHUGS
Michele Simionato: > No, slots have nothing to do with speed, they are a memory optimization. In many languages, often in Python too, the less memory you use/ allocate the faster you go. In fact slots allow a speed increase too (in new style classes): from timeit import default_timer as clock c

Re: Is there a better/simpler way to filter blank lines?

2008-11-04 Thread bearophileHUGS
tmallen > I must be missing something: > > >>> xlines = (line for line in open("new.data") if line.strip()) > >>> xlines > > >>> xlines.sort() > Traceback (most recent call last): > File "", line 1, in > AttributeError: 'generator' object has no attribute 'sort' > > What do you think? Congratu

Re: split() and string.whitespace

2008-11-04 Thread bearophileHUGS
MRAB: > I also had the thought that the backtick (`), which is not used in > Python 3, could be used to form character set literals (`aeiou` => > set("aeiou")), although that might only be worth while if character > sets were introduced as an specialised form of set. Python developers have removed

Re: False and 0 in the same dictionary

2008-11-05 Thread bearophileHUGS
Ben Finney: > Is there a later PEP that I've missed which > finally makes ‘bool’ a type independent from ‘int’? In a tidy language like an ObjectPascal or Java bools and integers are different types. In Python if bools become distinct from integers you have to rewrite things like: sum(el == val f

Re: False and 0 in the same dictionary

2008-11-05 Thread bearophileHUGS
Prateek: > How do I make a dictionary which has distinct key-value pairs for 0, > False, 1 and True. Why do you have to do that? What's the problem you have to solve? Maybe (probably) there are better or more clean alternative solutions. Bye, bearophile -- http://mail.python.org/mailman/listinfo/

Re: Is psyco available for python 2.6?

2008-11-09 Thread bearophileHUGS
Fuzzyman: > I've built a Windows installer if anyone is interested: Thank you to both. Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list

Re: Why is indexing into an numpy array that slow?

2008-11-10 Thread bearophileHUGS
Rüdiger Werner: > So i am looking for any explaination why the numpy version is that slow > (i expected it to be at least as fast as the pure python version). For speed use Psyco with array.array. Psyco is available for Python 2.6 too now. Bye, bearophile -- http://mail.python.org/mailman/listin

Re: Bug in PIL 1.1.6

2008-11-11 Thread bearophileHUGS
Markus Mayer: > Any idea where I should send this (and/or more) information to? You can send your note and and image to effbot. You can also put an image online somewhere and give here the link (a small image, to avoid saturating your server, etc) so people can test it. Bye, bearophile -- http://

Re: How to make arrays from Lists

2008-11-11 Thread bearophileHUGS
gc_ott: > How do I change the value of any element to produce (say) > [[99,0,0],[0,0,0],[0,0,0]] ? > > gordc To create a 2D list, that is a list of lists: x = [[0] * ncols for i in nrows] (Don't do what you were doing, because you end with many references to the same list, and that will give you t

Re: Python IF THEN chain equivalence

2008-11-13 Thread bearophileHUGS
jzakiya: > I asked a very narrow question about a very specific language > mechanism, and I know exactly what and why I'm doing what I'm doing. You are of course free to use Python as you want. And probably some of the answers weren't fully polite. But it's interesting to see why they have given s

Re: How to use a contiguous memory location of n bytes in python

2008-11-13 Thread bearophileHUGS
chachi: > I want to know how to instantiate a data structure which has n bytes > (given by me) and is internally stored in a contiguous fashion. array.array("B", ...) may be fit for you. You can also use a numpy array of bytes. Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-lis

Re: Avoiding local variable declarations?

2008-11-13 Thread bearophileHUGS
Paul McGuire: > coinflip = lambda : int(random.random()*2) I warmly suggest you to use this instead: randrange(2) Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list

Re: Avoiding local variable declarations?

2008-11-14 Thread bearophileHUGS
Paul McGuire: > Really?  Looking at randrange, it sure seems to do a lot of work in > pursuit of handling all possible cases for specifying range > boundaries, step values, etc. Well, randrange is the simpler thing to read and understand here, and maybe the one less likely to get wrong too. But I

Re: Clustering the keys of a dict according to its values

2008-11-14 Thread bearophileHUGS
Florian Brucker: > We may assume that all values in the > original dict/list can be used as dict keys. Are you sure? Is this for school? Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list

Re: Clustering the keys of a dict according to its values

2008-11-14 Thread bearophileHUGS
Not much tested: from collections import defaultdict def cluster(pairs): """ >>> d = {'a':1, 'b':2, 'c':1, 'd':1, 'e':2, 'f':3} >>> cluster(d) == {1:['a', 'c', 'd'], 2:['b', 'e'], 3:['f']} True >>> p = [1, 2, 1, 1, 2, 3] >>> cluster(p) == {1: [0, 2, 3], 2: [1, 4], 3: [5]}

Re: Clustering the keys of a dict according to its values

2008-11-14 Thread bearophileHUGS
Alternative version: def cluster(data): d = defaultdict(list) pairs = enumerate(data) if isinstance(data, list) else data.iteritems() for k, v in pairs: d[v].append(k) return d Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list

Re: Good practice when writing modules...

2008-11-15 Thread bearophileHUGS
r0g: > a) Import all the other modules these functions depend on into the > modules global namespace by putting them at the top of the module or > should I... > b) Include them in each function individually. This is a interesting topic, that requires some care. Generally I suggest you put them at

Re: Comparing value in two dictionaries?

2008-11-15 Thread bearophileHUGS
Gilles Ganault: > I fill two dictionaries with the same number of keys, and then need to > compare the value for each key, eg. Probably using the DBMS capabilities you can find a better solution. Are the keys equal? If you want to do it using dicts, you can iterate on one dict, with iteritems, an

Re: Regular expression and exception

2008-11-15 Thread bearophileHUGS
Mr.SpOOn: > try: >     m = re.match('[1-9]$', my_string) > except: >     print 'something...' > ... > try: >    m.group() > except: >    print 'error...' Generally don't write a nude except, use qualified exceptions, that is put there one of more exceptions that you want to catch (be careful with

Re: Clustering the keys of a dict according to its values

2008-11-15 Thread bearophileHUGS
Bruno Desthuilliers: > What is data is another type of sequence or iterable ?-)< The original problem statement was: Florian Brucker: >Given a dictionary, I want to create a clustered version of it, collecting >keys that have the same value: [...] Another requirement is that it should >also wor

Re: Need help in understanding a python code

2008-11-15 Thread bearophileHUGS
silverburgh: > max([(sum(a[j:i]), (j,i)) Other people have already answered you so I'll add only a small note: today the max() function has a key optional attribute, so that code can also be written as: max(((j, i) for ...), key=lambda (j, i): sum(a[j : i])) I think you have copied that part fro

Re: Good practice when writing modules...

2008-11-16 Thread bearophileHUGS
John Machin: > > import foo # used by baz() > > import bar # used by spam() > > Why bother with the ()? I code in other language too beside Python, in those languages there are other things (like templates in D language) beside functions, so my comment helps me remember that baz() is a function in

Re: Does python is suitable for enterprise cluster management?

2008-11-16 Thread bearophileHUGS
Asaf Hayman: > We are currently pondering which programming language will best suite > us. The two major contenders are Python and Java. I think there is also Erlang for such kind of things. Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list

Re: Sorting lists

2008-11-17 Thread bearophileHUGS
Chris Rebert: > You use the `key` argument to .sort(): > L2.sort(key=lambda item: item[1]) I like the lambda because it's a very readable solution that doesn't require the std lib and it doesn't force the programmer (and the person that reads the code) to learn yet another thing/function. But I c

Dynamic features used

2008-11-21 Thread bearophileHUGS
I often use Python to write small programs, in the range of 50-500 lines of code. For example to process some bioinformatics data, perform some data munging, to apply a randomized optimization algorithm to solve a certain messy problem, and many different things. For that I often use several genera

Re: Dynamic features used

2008-11-21 Thread bearophileHUGS
Almar Klein: > but I fail to see the point you're trying > to make or the question you're asking... :) It's not easy to define what my point was :-) I try again, but the following questions don't cover all the points: - What are the dynamic features of Python that you use in your code? (excluding

Re: Efficient searching through objects

2009-02-26 Thread bearophileHUGS
sert: > I have implemented this by creating a list with all the people's > names and another list with their objects (their data). > > It works but after profiling the code it turns out that half the > time spent in the program is spent in the list.index() function > looking up names. Isn't there a

Re: Using xreadlines

2009-02-26 Thread bearophileHUGS
Brett Hedges: > My question is how do I go to a previous line in the file? xreadlines has a > file.next() statement that gives the next line, and I need a statement that > gives me the previous line.< In modern versions of Python you usually don't need xreadlines, because files are iterable. If

Re: Proposed implementation for an Ordered Dictionary

2009-02-27 Thread bearophileHUGS
Raymond Hettinger: >Paul Rubin: >>another (messy) approach would be to write a C >>extension that uses a doubly linked list some day. > > That seems like an ideal implementation to me. This was my Python implementation, where the delete too is O(1), but it's slow: http://code.activestate.com/recip

Re: Multiple conditional expression

2009-02-27 Thread bearophileHUGS
Chris Rebert: > That seems to just be an overly complicated way of writing: > > spaces = bool(form.has_key('spaces') and form.getvalue('spaces') == 1) Better: spaces = bool(('spaces' in form) and form.getvalue('spaces') == 1) Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list

Re: removing duplication from a huge list.

2009-02-27 Thread bearophileHUGS
odeits: > How big of a list are we talking about? If the list is so big that the > entire list cannot fit in memory at the same time this approach wont > work e.g. removing duplicate lines from a very large file. If the data are lines of a file, and keeping the original order isn't important, then

Re: Proposed implementation for an Ordered Dictionary

2009-02-27 Thread bearophileHUGS
Paul Rubin: >I don't see how to delete a randomly chosen node if you use that trick, since >the hash lookup doesn't give you two consecutive nodes in the linked list to >xor together.< Thank you, I think you are right, I am sorry. So on 32-bit CPUs you need to add 8 bytes to each value. On 64-b

Re: Proposed implementation for an Ordered Dictionary

2009-02-27 Thread bearophileHUGS
Steve Holden: > A sort of premature pessimization, then. Maybe not, the save in memory may lead to higher speed anyway. So you need to test it to know the overall balance. And in data structures with general purpose you want all the speed you can get. Bye, bearophile -- http://mail.python.org/mai

Re: Using xreadlines

2009-02-27 Thread bearophileHUGS
Brett Hedges: > How would I keep track of the absolute position of the lines? You may have to do all things manually (tell, seek and looking for newlines manually, iterating chars), that's why I have said it's not handy. The other solutions are simpler. Bye, bearophile -- http://mail.python.org/m

Re: removing duplication from a huge list.

2009-03-03 Thread bearophileHUGS
odeits: > Although this is true, that is more of an answer to the question "How > do i remove duplicates from a huge list in Unix?". Don't you like cygwin? Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list

Indentations and future evolution of languages

2009-03-05 Thread bearophileHUGS
This is an interesting post, it shows me that fitness plateau where design of Python syntax lives is really small, you can't design something just similar: http://unlimitednovelty.com/2009/03/indentation-sensitivity-post-mortem.html Living on a small fitness plateau isn't good, even if it's very

Re: RELEASED Python 3.1 alpha 1

2009-03-07 Thread bearophileHUGS
Are the computed gotos used in the future pre-compiled Windows binary (of V.3.1) too? Is such optimization going to be backported to the 2.x series too, like Python 2.7? Bye and thank you for your work, bearophile -- http://mail.python.org/mailman/listinfo/python-list

Re: RELEASED Python 3.1 alpha 1

2009-03-07 Thread bearophileHUGS
Benjamin Peterson: >It provides a good incentive for people to upgrade. :)< Sometimes at work you are forced you to use Python 2.x, so incentives aren't much relevant. Christian Heimes: > No, the MS Visual C compiler doesn't supported labels as values [1]. The > feature is only supported by som

Re: Candidate for a new itertool

2009-03-07 Thread bearophileHUGS
Raymond Hettinger, maybe it can be useful to add an optional argument flag to tell such split_on to keep the separators or not? This is the xsplit I usually use: def xsplit(seq, key=bool, keepkeys=True): """xsplit(seq, key=bool, keepkeys=True): given an iterable seq and a predicate key, s

Re: Is python worth learning as a second language?

2009-03-09 Thread bearophileHUGS
ZikO, if you know C++, then knowing one scripting language is useful, it can be Ruby, Python (or even Lua, etc). Note that learning a language isn't a binary thing, so I suggest you to use a week to learn Python and use it try to solve some of your practical problems. After a week you will be able

Re: Candidate for a new itertool

2009-03-09 Thread bearophileHUGS
Raymond Hettinger: >In your experiences with xsplit(), do most use cases involve removing the >separators?< Unfortunately I am not able to tell you how often I remove them. But regarding strings, I usually want to remove separators: >>> "aXcdXfg".split("X") ['a', 'cd', 'fg'] So sometimes I wan

Re: Why is lambda allowed as a key in a dict?

2009-03-09 Thread bearophileHUGS
See here Daniel Fetchinson: http://groups.google.com/group/comp.lang.python/browse_thread/thread/a973de8f3562675c But be quite careful in using that stuff, it has some traps. Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list

Re: Special keyword argument lambda syntax

2009-03-13 Thread bearophileHUGS
MRAB: >  >>> sorted(range(9), def key(n): n % 3) I am fine with the current lambda syntax, but another possibility: sorted(range(9), n => n % 3) Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list

Re: Style question - defining immutable class data members

2009-03-14 Thread bearophileHUGS
Maxim Khitrov: > When the types are immutable, there is no difference. But you may want different instances to have different immutable data. Generally if the data (immutable or not) is the same for all the instances, use class attributes, otherwise use instance attributes. Bye, bearophile -- ht

Re: Integer arithmetic in hardware descriptions

2009-03-15 Thread bearophileHUGS
John Nagle: >I gave up on this when C came in; the C crowd was so casual about integer >overflow that nobody cared about this level of correctness. Today, of course, >"buffer overflows" are a way of life.< Experience shows that integer overflows are a very common bug. One of the huge advantages

<    4   5   6   7   8   9   10   11   12   >