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 so

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 --

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 --

'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 done

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:

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) ['bcsn', ' 101', '']

Re: A note on heapq module

2007-01-26 Thread bearophileHUGS
bearophile: I don't like your solution, this class was already slow enough. Don't use unbound methods with this class :-) Sorry for raising this discussion after so much time. Another possibile solution is to use the normal methods for the normal case, and replace them only if key is present

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: Fast Imaging for Webserver

2007-01-25 Thread bearophileHUGS
Paul McGuire: before you start replacing PIL, or optimizing CherryPy, or other possible performance-improving efforts, you should profile the within-request processing, find the bottleneck, and take care of that first. Good advice. Among the tests, the OP can also try to change the

Re: How can i do this in Python?

2007-01-25 Thread bearophileHUGS
Gabriel Genellina: import operator,fileinput mapper = map(operator.itemgetter, [0,1,20,21,2,10,12,14,11,4,5,6]) for line in fileinput.input(): fields = line.split() print '\t'.join(m(fields) for m in mapper) I'm just curious, what's the advantage of using itemgetter there compared

Re: str and __setitem__

2007-01-25 Thread bearophileHUGS
Peter Otten: class mutable_str(object):... def __init__(self, value): ... self._value = value ... def __setitem__(self, index, value): ... self._value = self._value[:index] + value + self._value[index+1:] ... def __str__(self): ... return

Re: Static variables

2007-01-24 Thread bearophileHUGS
Bruno Desthuilliers: And this let you share state between functions: def make_counter(start_at=0, step=1): count = [start_at] def inc(): count[0] += step return count[0] def reset(): count[0] = [start_at] return count[0] def peek(): return count[0]

Re: Best way to document Python code...

2007-01-22 Thread bearophileHUGS
Boris Ozegovic: Does Python has API just like in Java, for example http://java.sun.com/j2se/1.5.0/docs/api/allclasses-noframe.html ctrl-f and than click on class you are searching for, and finally you get clean list of all fields and methods. Where can I find similar in Python, for example,

Symbols again

2007-01-22 Thread bearophileHUGS
Modifying another recipe, I have defined some symbols again: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/500273 I don't know if this may be useful for something real. Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list

Re: Py 2.5 on Language Shootout

2007-01-20 Thread bearophileHUGS
[EMAIL PROTECTED]: In reality the choice would be C++ because of OO and STL. I have seen that when Python+Psyco are too much slow, D language is a good sweet half point between Python and C++ :-) Fast as C++ and with a simpler syntax and semantics (Pyrex isn't bad, but D gives high-level things

Re: Match 2 words in a line of file

2007-01-19 Thread bearophileHUGS
Rickard Lindberg, yesterday I was sleepy and my solution was wrong. 2) If you have a line something like this: foobar hello then 'foo' in line will return true, even though foo is not a word (it is part of a word). Right. Now I think the best solution is to use __contains__ (in) to quickly

Re: Iterator length

2007-01-19 Thread bearophileHUGS
Steven D'Aprano: s = aaabaabb from itertools import groupby print [(h,leniter(g)) for h,g in groupby(s)] s isn't an iterator. It's a sequence, a string, and an iterable, but not an iterator. If you look better you can see that I use the leniter() on g, not on s. g is the iterator

Re: Iterator length

2007-01-19 Thread bearophileHUGS
Steven D'Aprano: since g is not an arbitrary iterator, one can easily do this: print [(h,len(list(g))) for h,g in groupby(s)] No need for a special function. If you look at my first post you can see that I have shown that solution too, but it creates a list that may be long, that may use a lot

Py 2.5 on Language Shootout

2007-01-19 Thread bearophileHUGS
The The Computer Language Shootout has just published results for Python 2.5 and Psyco 1.5.2. Comparing the old (Python 2.4) Gentoo Pentium 4 results (now not visible anymore) with the new results, I have seen that all the tests with Python 2.5 are faster than the ones with Python 2.4 (some

Re: A note on heapq module

2007-01-18 Thread bearophileHUGS
Steven Bethard: Antoon Pardon: For me, your class has the same drawback as the heappush, heappop procedurers: no way to specify a comparision function. Agreed. I'd love to see something like ``Heap(key=my_key_func)``. It can be done, but the code becomes more complex and hairy:

Re: A note on heapq module

2007-01-18 Thread bearophileHUGS
Neil Cerutti: One more idea, cribbed from the linked list thread elsewhere: it might be nice if your Heap could optionally use an underlying collections.deque instead of a list. I don't know how excellent Python's deque is, but it's possible a deque would provide a faster heap than a

Re: A note on heapq module

2007-01-18 Thread bearophileHUGS
Steven Bethard wrote: The current code fails when using unbound methods however:: I don't like your solution, this class was already slow enough. Don't use unbound methods with this class :-) Maybe there's a (better) solution to your problem: to make Heap a function (or classmethod) that return

Iterator length

2007-01-18 Thread bearophileHUGS
Often I need to tell the len of an iterator, this is a stupid example: l = (i for i in xrange(100) if i1) len isn't able to tell it: len(l) Traceback (most recent call last): File stdin, line 1, in module TypeError: object of type 'generator' has no len() This is a bad solution, it may

Re: Iterator length

2007-01-18 Thread bearophileHUGS
George Sakkis: Is this a rhetorical question ? If not, try this: It wasn't a rhetorical question. x = (i for i in xrange(100) if i1) if leniter(x): print x.next() What's your point? Maybe you mean that it consumes the given iterator? I am aware of that, it's written in the function

Re: Match 2 words in a line of file

2007-01-18 Thread bearophileHUGS
MrJean1 wrote: def lines_with_words(file, word1, word2): Print all lines in file that have both words in it. for line in file: words = line.split() if word1 in words and word2 in words: print line This sounds better, it's probably faster than the RE

Re: How can I create a linked list in Python?

2007-01-17 Thread bearophileHUGS
Marc 'BlackJack' Rintsch: Python has a list type without the s, it's a real list. Don't confuse the *ADT list* with *linked lists* which are just one implementation of the ADT list. Right, I was mostly talking about (single/double) linked lists :-) Bye, bearophile --

A note on heapq module

2007-01-16 Thread bearophileHUGS
In few minutes I have just written this quite raw class, it lacks doctring (the same of the functions of the heapq module), it may contain bugs still, I haven't tested it much. It's just a simple wrapper around some of the functions of the heapq module (nsmallest and nlargest are missing). Usually

Re: A note on heapq module

2007-01-16 Thread bearophileHUGS
I think the sort has to be simplified, otherwise it can't keep the heap invariant... def sort(self): self.h.sort() Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list

Re: A note on heapq module

2007-01-16 Thread bearophileHUGS
Scott David Daniels: I'd suggest some changes. It is nice to have Heaps with equal contents equal no matter what order the inserts have been done. Consider how you want Heap([1, 2, 3]) and Heap([3, 1, 2]) to behave. Similarly, it is nice to have str and repr produce canonical representations

Re: How can I create a linked list in Python?

2007-01-16 Thread bearophileHUGS
Gary Herron: If you really want a list (as Python defines a list - with all the methods) then you should use Python's lists. They are quite efficient and convenient: In CPython they are dynamic arrays, they aren't lists. Try adding elements at the beginning of a list compared to adding

Re: Class list of a module

2007-01-15 Thread bearophileHUGS
Gabriel Genellina: import inspect def getClassList(aModule): return [cls for cls in vars(aModule).itervalues() if inspect.isclass(cls)] This is short enough too: from inspect import isclass getclasses = lambda module: filter(isclass, vars(module).itervalues()) Bye,

Re: help with recursion on GP project

2007-01-14 Thread bearophileHUGS
First possible raw solution: from operator import add, sub, mul, div, neg def evaluate(expr): if isinstance(expr, list): fun, ops = expr[0], expr[1:] return fun(*map(evaluate, ops)) else: return expr example = [add, [add, [sub, 5, 4], [mul, 3, 2]], [neg, 5]]

Re: AlphaBeta Search

2007-01-13 Thread bearophileHUGS
Chris wrote: I know this probably seems trivial, but I can't seem to find the bug in my alphabeta search implementation. This is another alphabeta implementation (all the nicest algorithms are inside this AIMA codebase): http://aima.cs.berkeley.edu/python/games.html Later when you program

Re: Comparing a matrix (list[][]) ?

2007-01-13 Thread bearophileHUGS
Roberto Bonvallet: What output are you expecting from your example matrix? If you are expecting it to be 5 (the smallest positive element), using min is the way to do it: matrix = [[9, 8, 12, 15], ... [0, 11, 15, 18], ... [0, 0, 10, 13], ...

Re: Type casting a base class to a derived one?

2007-01-11 Thread bearophileHUGS
Frederic Rentsch: If I derive a class from another one because I need a few extra features, is there a way to promote the base class to the derived one without having to make copies of all attributes? class Derived (Base): def __init__ (self, base_object): # ( copy all

Re: what is the idiom for copy lots of params into self?

2007-01-10 Thread bearophileHUGS
Emin: This saves a lot of code and makes it easier to see what is going on, but it seems like there should be a better idiom for this task. Any suggestions? I know two ways of doing it, one way requires very light code into the __init__ and it uses a decorator that takes the parameters and

Re: recursive function

2007-01-08 Thread bearophileHUGS
First possible solution: def rloop(seqin, comb): # xcross product recipe 302478 by David Klaffenbach if seqin: for item in seqin[0]: newcomb = comb + [item] for item in rloop(seqin[1:], newcomb): yield item else: yield comb data

Re: Why less emphasis on private data?

2007-01-07 Thread bearophileHUGS
Paul Rubin: Python certainly makes you spend more of your attention worrying about possible attribute name collisions between classes and their superclasses. And Python's name mangling scheme is leaky and bug-prone if you ever re-use class names. Trouble with this is you can have two classes

Re: I want to learn

2007-01-07 Thread bearophileHUGS
[EMAIL PROTECTED]: I am looking for a python guru who has instant messenger or gtalk or whatever who can meet me online in the mornings, give me some direction for the day and then answer some questions here and there online throughout the day. Maybe a Python gury isn't necessary, maybe a

Re: Sorting on multiple values, some ascending, some descending

2007-01-03 Thread bearophileHUGS
Raymond Hettinger: The simplest way is to take advantage of sort-stability and do successive sorts. For example, to sort by a primary key ascending and a secondary key decending: L.sort(key=lambda r: r.secondary, reverse=True) L.sort(key=lambda r: r.primary) That's probably the faster

Re: static object

2007-01-03 Thread bearophileHUGS
That looks like some kind of singleton. Why don't you use a module instead of a class? Another solution is to define your data as class attributes. Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list

Re: Sorting on multiple values, some ascending, some descending

2007-01-03 Thread bearophileHUGS
dwelden wrote: L.sort(key=lambda r: r.secondary, reverse=True) L.sort(key=lambda r: r.primary) Excellent! That looks just like what I needed. Note that there is the (probably little used) operator.attrgetter() too, with that you can avoid the possibly slow lambda:

Re: code optimization (calc PI) / Full Code of PI calc in Python and C.

2007-01-03 Thread bearophileHUGS
Michael M.: * The C is very fast, Python not. * Target: Do optimization, that Python runs nearly like C. Python can't be fast as C for that kind of programs. Note that your original C program gives less digits than the Python program. Your original takes about ~15.2 s on my PC. The following

Re: Writing more efficient code

2007-01-02 Thread bearophileHUGS
Jon Harrop: I think this sort of functionality would be a welcome addition to Python. I don't know. Perhaps it can be written in Python? Pyparsing and beautifulsoup show that practically useful parsing modules can be done using Python alone too. Set module of Python 2.3, translated to C in

Re: Iterate through list two items at a time

2007-01-02 Thread bearophileHUGS
Few alternative solutions (other are possible), I usually use a variant of the first version, inside a partition function, the second variant is shorter when you don't have a handy partition() function and you don't want to import modules, and the forth one needs less memory when the data is very

Re: Writing more efficient code

2007-01-01 Thread bearophileHUGS
Jon Harrop: OCaml's pattern matcher is very sophisticated and very fast. You'll probably shrink your code by several fold whilst also having it run a few orders of magnitude faster and having it statically checked, so it will be more reliable. You seem to forget some months of time to learn

Re: Writing more efficient code

2007-01-01 Thread bearophileHUGS
Jon Harrop: I think most people could pick up the core ideas in a day and start writing working programs. Probably I am not that intelligent, I probably need some months :-) But that language has many good sides, and one day I'll probably try to learn it a bit. Mathematica is expensive but

Re: Scaling pictures

2006-12-28 Thread bearophileHUGS
Kajsa Anka: I found the Python Imaging Library but before I dive into that I would like to know if there is a better way of doing this. PIL is very fit for that. Note that it creates thumbnails already by itself, you can use that for bigger images too. Bye, bearophile --

Re: answers.py v0.0.1 - source

2006-12-28 Thread bearophileHUGS
Marc 'BlackJack' Rintsch: You give lot of comments and I agree with most of them. One idiom to solve this is: def __init__(self, answers=None): self.answers = answers or dict() I suggest to avoid such usage of or/and (expecially for newbies), that is triky and can produce bugs,

__getattr__ possible loop

2006-12-28 Thread bearophileHUGS
I have tried this, with Psyco it segfaults, and with Python 2.5 (on Win) hangs the interpreter, is it possible to improve the situation? class T(object): def __getattr__(self, x): dir(self) #import psyco #psyco.full() T().method() (Probably dir calls __getattr__). Bye, bearophile --

Re: __getattr__ possible loop

2006-12-28 Thread bearophileHUGS
Maksim Kasimov: how to improve the situation depends on what do you expect to get by calling T().method() You are right, sorry for being cryptic. I think that's a kind of bug of Python (produced maybe by an infinite loop), so an improvement can be a traceback or some automatic breaking of that

Re: loose methods : Smalltalk asPython

2006-12-27 Thread bearophileHUGS
Steven D'Aprano: You can't modify the built-in classes. I'm not sure that it is a good idea to allow built-ins to be modified. When I see an int, I like the fact that I know what the int can do, and I don't have to worry about whether it has been modified by some piece of code elsewhere. I

Re: some OT: how to solve this kind of problem in our program?

2006-12-26 Thread bearophileHUGS
For people that will read the posts in the future, there is a little bug (it doesn't change the output of this program): items = alist[:] Has to be: alist = alist[:] Sorry, bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list

Re: some OT: how to solve this kind of problem in our program?

2006-12-24 Thread bearophileHUGS
Paul McGuire: This little framework takes about 4.5 seconds, but with psyco, cuts down to about 1.3 seconds. st = time.time() result = [] for p in permutations(range(1,10)): aresult = func(p) if aresult is not None and aresult not in result: result.append(aresult)

Re: some OT: how to solve this kind of problem in our program?

2006-12-24 Thread bearophileHUGS
Using Psyco this version is much faster, you can test it on your PC compared to the other one (the whole running time, Psyco compilation too): Psyco is unable to speed up generator functions, so you have to return true lists. Giving the func to the permutation function, you can avoid lot of list

Re: Multi-line docstrings

2006-12-23 Thread bearophileHUGS
Duncan Booth: Not spuriously included: included by design, but sometimes annoying. Then it's a design decision I don't understand... Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list

Re: Decorator for Enforcing Argument Types

2006-12-21 Thread bearophileHUGS
Chris wrote: I'm not sure if this has been done before, I think this is the best implementation: http://oakwinter.com/code/typecheck/ I have never used it, but it seems well done. Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list

array, a better shell

2006-12-20 Thread bearophileHUGS
For array.array B means unsigned char, and such arrays accept to be initialized from (str) strings too, this is quite useful: from array import array a = array(B, hello) But it seems such capability isn't shared with the append: a.extend(hello) Traceback (most recent call last): File

Re: array, a better shell

2006-12-20 Thread bearophileHUGS
Steven D'Aprano: No you're not. You're describing a quite complicated shell. You're describing a hypothetical shell with features other actual shells don't have, so therefore it can't possibly be as simple as possible. You are right, it's not really simple, but: - It has just the basic

Re: array, a better shell

2006-12-20 Thread bearophileHUGS
Duncan Booth: Later you can click on them and bring them back to the bottom of the input buffer for further editing (so no confusing output appearing out of order), I think that's worse, not better. You end with a messy final document (log), so finding things into it (during the editing too)

Re: Shed Skin - Does it break any Python assumptions?

2006-12-18 Thread bearophileHUGS
Jean-Paul Calderone: So yes, it seems that what ShedSkin supports is pretty distant from what a seasoned Python developer might expect, aside from syntactic constructs. At the moment SS doesn't allow to change the type of a variable during its lifetime, but SS is a moving target, maybe in the

Re: Writing and reading variables to/from flat file

2006-12-15 Thread bearophileHUGS
Geoffrey Clements: readfile = open('prefs').readlines() for line in readfile: print line eval(line) print Basic Instead of using eval, using a plain dict may be a better solution. Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list

Re: AI library

2006-12-15 Thread bearophileHUGS
Gabriel Genellina: This is more stylish, but I prefer to use isxxx() or hasxxx() for functions that return booleans. Lisp-like languages allow the ending ? or !, I think Ruby allows the ending ? too (allowing it with Python may be positive). Mathematica usually uses an ending uppercase Q, like

Re: speed of python vs matlab.

2006-12-14 Thread bearophileHUGS
Chao, you can also try Psyco, applied on functions, and when necessary using its metaclass too. Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list

Re: automatically grading small programming assignments

2006-12-14 Thread bearophileHUGS
Brian Blais, just an idea. Create an online form to upload the tiny program(s). Such programs can be one for file. Then on your PC you can run a script that loads each of such programs, and runs a good series of tests, to test their quality... Such tests can be about all things, speed, coding

Re: merits of Lisp vs Python

2006-12-09 Thread bearophileHUGS
Andrea GriffiniIs this worth investigation or it has already been suggested/tried ? Recently some people around the net have discussed about similar ideas as a possible way to speed up Ruby interpreters a lot. Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list

Re: len() and PEP 3000

2006-12-09 Thread bearophileHUGS
Colin J. Williams: Why not replace the __len__ method with a len property for strings, lists, tuples, dictionaries etc. __len__ is not very special and the property len eliminates the redundant parentheses. You mean something like: ab.len, [1, 2, 3].len (2, 3) In the given page Guido says:

Re: merits of Lisp vs Python

2006-12-08 Thread bearophileHUGS
[EMAIL PROTECTED]: Sorry, I missed something here. Why do you need a release to have these sorts of things? Can't you just expand the language via macros to create whatever facility of this sort you need... Oh, sorry. You CAN'T expand the language Too bad. I guess waiting for Guido to

Re: merits of Lisp vs Python

2006-12-08 Thread bearophileHUGS
[EMAIL PROTECTED]: Sorry, I missed something here. Why do you need a release to have these sorts of things? Can't you just expand the language via macros to create whatever facility of this sort you need... Oh, sorry. You CAN'T expand the language Too bad. I guess waiting for Guido to

Re: Factory pattern implementation in Python

2006-12-04 Thread bearophileHUGS
Dennis Lee Bieber: Presuming the event x is a type code I'd just set up a list of functions: Then create a dictionary of them, keyed by the event x code processors = { 1 : process_1, 2 : process_2, x : process_x }

Re: Remarkable results with psyco and sieve of Eratosthenes

2006-11-30 Thread bearophileHUGS
George Sakkis: You can also save an attribute lookup for append; just add append = primes.append outside of the loop and replace primes.append(x) with append(x) That should cut down a few fractions of second. We were talking about Psyco, and I think with Psyco (just released for Py 2.5, BTW)

Re: best way to align words?

2006-11-30 Thread bearophileHUGS
Robert R.: i would like to write a piece of code to help me to align some sequence of words and suggest me the ordered common subwords of them [...] a trouble i have if when having many different strings my results tend to be nothing while i still would like to have one of the, or maybe, all

Re: best way to align words?

2006-11-30 Thread bearophileHUGS
This is my first solution try, surely there are faster, shorter, better solutions... It creates a graph with the paths of words, then sorts the graph topologically, Beside possible inefficiencies, this solution breaks if words aren't in the correct order, the topological sort can't work...

Re: Modifying every alternate element of a sequence

2006-11-28 Thread bearophileHUGS
Leo Kislov: input[1::2] = [-item for item in input[1::2]] If you don't want to do it in-place, just make a copy: wanted = input[:] wanted[1::2] = [-item for item in wanted[1::2]] Very nice solution. I have tried few versions like: from itertools import imap, islice from operator import neg 1)

Re: problem about list indexing

2006-11-26 Thread bearophileHUGS
hollowspook: how about indexing 1-7, 10 [range(1:8),10] will generate [[1, 2, 3, 4, 5, 6, 7], 10], instead of [1, 2, 3, 4, 5, 6, 7, 10] (Note that range(1:8) is a syntax error). You can join and extend lists as you like: range(1, 8) + [10] [1, 2, 3, 4, 5, 6, 7, 10] See also the list.append

Re: Graph Data Structures

2006-11-25 Thread bearophileHUGS
Szabolcs Nagy: i haven't read your code, but there are many graph implementations in python. in case you haven't found these yet: http://wiki.python.org/moin/PythonGraphApi if you only want to do some analysis i think you need this one (as it's pretty complete and simple):

Re: python gaining popularity according to a study

2006-11-23 Thread bearophileHUGS
[EMAIL PROTECTED]: Python is the 7th most commonly used language, up from 8th. The only one gaining ground besides VB in the top 10. It also shows that Ruby is gaining even more, and D is (gladly) growing too. Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list

Re: text file parsing (awk - python)

2006-11-22 Thread bearophileHUGS
Peter Otten, your solution is very nice, it uses groupby splitting on empty lines, so it doesn't need to read the whole files into memory. But Daniel Nogradi says: But the names of the fields (node, x, y) keeps changing from file to file, even their number is not fixed, sometimes it is (node,

Re: regex problem

2006-11-22 Thread bearophileHUGS
line is am trying to match is 1959400|Q2BYK3|Q2BYK3_9GAMM Hypothetical outer membra29.90.00011 1 regex i have written is re.compile (r'(\d+?)\|((P|O|Q)\w{5})\|\w{3,6}\_\w{3,5}\s+?.{25}\s{3}(\d+?\.\d)\s+?(\d\.\d+?)') I am trying to extract 0.0011 value from the above line.

Abelson and Python

2006-11-22 Thread bearophileHUGS
While studying the SICP video lectures I have to twist my mind some to completely understand the lessons. I implement the programs shown there in both Python and Scheme, and I find the Python implementations simpler to write (but it's not a fair comparison because I know very little Scheme still).

Re: Abelson and Python

2006-11-22 Thread bearophileHUGS
[EMAIL PROTECTED]: No surprise to anyone who's ever tried to use MIT Scheme. Be careful, such assertions are often flamebait. I am using DrPython (I think they were using it at MIT too lately), and it is very very good IDE, it produces executables on the fly, it has a visual debugger with some

Re: AVL Balancing

2006-11-22 Thread bearophileHUGS
scbauer wrote: This is one of the errors that im getting Traceback (most recent call last): File pyshell#49, line 1, in module t.insert(5) File /Users/stevenbauer/Desktop/AVL.py, line 68, in insert stack.append(current) NameError: global name 'stack' is not defined def

Re: Abelson and Python

2006-11-22 Thread bearophileHUGS
[EMAIL PROTECTED]: Haven't heard of that one, although I've got DrScheme. Right, sorry, I meant that one :-) I find that hierarchy extremely annoying. I don't see the need for it. I never use OOP in Python yet there's no need for me to have a stripped down version, I just don't use it. But

Re: Abelson and Python

2006-11-22 Thread bearophileHUGS
markscottwright: I love Python as much as the next guy, but I just don't see how SICP can be done in Python. The contents of the course are probably different, they work on robotics... Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list

Re: changing list items

2006-11-22 Thread bearophileHUGS
A possibile first solution: alist = ['a','b','c','e','d','f'] inf, sup = 2, 4 alist[inf:sup] = [t] * (sup - inf) alist ['a', 'b', 't', 't', 'd', 'f'] Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list

Re: Abelson and Python

2006-11-22 Thread bearophileHUGS
Paddy: Is the MIT course syndicated to Universities around America or something? (Is your name pronounced Beer-owe-file, or Bear-oh-fi-lee, I don't know. I too have heard about the MIT course changing to Python elsewhere and wanted to know why it was talked about so much? I don't know why

dict.reserve and other tricks

2006-11-16 Thread bearophileHUGS
I have started doing practice creating C extensions for CPython, so here are two ideas I have had, possibly useless. If you keep adding elements to a CPython dict/set, it periodically rebuilds itself. So maybe dict.reserve(n) and a set.reserve(n) methods may help, reserving enough (empty) memory

Re: dict.reserve and other tricks

2006-11-16 Thread bearophileHUGS
Thank you for the answers Terry Reedy and Klaas. Since you are writing extensions, you can create a built-in subclass of dict to experiment with. I presume the 2.5 default dict should be a model. That way it's doable, but I think it's of limited use too; I'd like to remove elements from

Re: simple way to un-nest (flatten?) list

2006-11-06 Thread bearophileHUGS
djc: As it is possible that the tuples will not always be the same word in variant cases result = sum(r.values(), ()) will do fine and is as simple as I suspected the answer would be. It is simple, but I suggest you to take a look at the speed of that part of your code into your program.

Re: string to list of numbers conversion

2006-11-05 Thread bearophileHUGS
[EMAIL PROTECTED] wrote: Hi, I have a string '((1,2), (3,4))' and I want to convert this into a python tuple of numbers. But I do not want to use eval() because I do not want to execute any code in that string and limit it to list of numbers. Is there any alternative way? This is a

Re: Defaultdict and speed

2006-11-04 Thread bearophileHUGS
Klaas wrote: Benchmarks? There is one (fixed in a succesive post) in the original thread I was referring to: http://groups.google.com/group/it.comp.lang.python/browse_thread/thread/aff60c644969f9b/ If you want I can give more of them (and a bit less silly, with strings too, etc). def ddict(n):

Defaultdict and speed

2006-11-03 Thread bearophileHUGS
This post sums some things I have written in another Python newsgroup. More than 40% of the times I use defaultdict like this, to count things: from collections import defaultdict as DD s = abracadabra d = DD(int) for c in s: d[c] += 1 ... d defaultdict(type 'int', {'a': 5, 'r': 2, 'b': 2,

Re: other ways to check for type 'function'?

2006-11-02 Thread bearophileHUGS
elderic: 1.: -- sort of clumsy and discouraged by the docs as far as I read import types type(f) is types.FunctionType What's the problem with this? from types import FunctionType if isinstance(f, FunctionType): ... Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list

Re: Python in sci/tech applications

2006-11-02 Thread bearophileHUGS
mattf: 3) -There's a problem with development under Windows. It's possibile to compile Python with MinGW, and to create extensions with it. So some site can host a single zip file that contains both MinGW and Python compiled with it, all ready and set. A person not much expert can then create

Re: Python in sci/tech applications

2006-11-02 Thread bearophileHUGS
Robert Kern: We distribute mingw set up to do this with our Enthought Edition Python distribution. http://code.enthought.com/enthon/ Sorry, maybe I'm blind but I don't see MinGW listed in that page... Maybe it's included but not listed... Bye, bearophile --

Re: Python in sci/tech applications

2006-11-02 Thread bearophileHUGS
Fredrik Lundh: last time I tried, it took me 20 minutes from that I typed mingw into google until I had built and tested my first non-trivial extension. your milage may vary. But probably before those 20 minutes there is a lot of time of experience of yours with CPython sources, other

Re: Style for modules with lots of constants

2006-11-01 Thread bearophileHUGS
Neil Cerutti: scriptref = glk.fileref_create_by_prompt('Transcript+TextMode', 'WriteAppend', 0) That + sign seems useless. A space looks enough to me. The functions can accept case-agnostic strings and ignore spaces inside them. Example: ('transcript textmode ', 'writeappend', 0) Parsing

Re: Style for modules with lots of constants

2006-11-01 Thread bearophileHUGS
Rob Williscroft: This is nice, but you can cut down on some of the cruft: class Constants( object ): pass Constants.RIGHT = 0 Constants.LEFT = 1 ## client code ... print Constants.LEFT Another possibility is to define such constants as strings instead of integers: _allflags = (left,

<    3   4   5   6   7   8   9   10   11   12   >