Re: Flexible Collating (feedback please)

2006-10-18 Thread bearophileHUGS
Ron Adam: Insted of: def __init__(self, flags=[]): self.flags = flags self.numrex = re.compile(r'([\d\.]*|\D*)', re.LOCALE) self.txtable = [] if HYPHEN_AS_SPACE in flags: self.txtable.append(('-', ' ')) if UNDERSCORE_AS_SPACE in flag

Re: making a valid file name...

2006-10-18 Thread bearophileHUGS
Tim Chase: > In practice, however, for such small strings as the given > whitelist, the underlying find() operation likely doesn't put a > blip on the radar. If your whitelist were some huge document > that you were searching repeatedly, it could have worse > performance. Additionally, the find()

Re: FOR statement

2006-10-21 Thread bearophileHUGS
Theerasak Photha: > I guess Python isn't tail-recursive then? Right. > Well, algorithms seem to be more naturally expressed iteratively in > Python, and to be fair, most uses of recursion you see in e.g., Scheme > textbooks are really just grandstanding in the real world. Still, some algorithms

Re: iniziare a programmare

2006-10-21 Thread bearophileHUGS
Lemon Tree: Interesting discussion, and I agree that having more info about the exceptions that can be raised is generally useful. You too can improve python docs, putting more info inside them. But this is the wrong newgroup, this isn't iclp, this is clp. Bye, bearophile -- http://mail.python.

Re: Tkinter--does anyone use it for sophisticated GUI development?

2006-10-22 Thread bearophileHUGS
Peter Decker: > Now that I've discovered Dabo, which wraps wxPython, hiding the C++ > ugliness under a very Pythonic API, I have the best of both worlds. I > get to code naturally, and the results look great. With some cleaning and improving, I think wax (http://zephyrfalcon.org/labs/wax.html ) ca

Re: Sorting by item_in_another_list

2006-10-24 Thread bearophileHUGS
Carsten Haese: > However, it's not clear > whether this specifies language behavior that all implementations must > adhere to, or whether it simply documents an implementation detail of > CPython. I think it's CPython-specific, but maybe here people expert in Jython and IronPython can tell if thei

Re: Any way of adding methods/accessors to built-in classes?

2006-10-25 Thread bearophileHUGS
Kenneth McDonald: > not being able to do things like '[1,2,3]'.length > drives me a little nuts. This is interesting, why? (In a computer language too much purity is often bad. And isn't [1,2,3].len better?) I think you can't add methods to Python builtin classes, I think you can do it with Ruby.

Re: Is there a python development site for putting up python libraries that people might be interest in working on?

2006-10-25 Thread bearophileHUGS
Kenneth McDonald: > * Construction of re's is object oriented, and does not require any > knowledge of re syntax. I have partially done something similar, so I am interested. Does rex outputs normal REs? Or does it wraps them in some way? A normal RE output has some advantages, even if you can't h

Re: displaying \n-less prompts in a pythonic way

2006-10-26 Thread bearophileHUGS
Sybren Stuvel: > def prompt(label): > '''Prompts the user, returning the typed text''' > sys.stdout.write(label) > return sys.stdin.readline() Maybe raw_input function may help too. Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list

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

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

Re: Style for modules with lots of constants

2006-11-01 Thread bearophileHUGS
Ron Adam: > The disadvantage is an invalid flag may pass silently unless you do some sort > of > validation which may slow things down a bit. That string validation is usually necessary. Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list

Re: other ways to check for ?

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

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 co

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 -- http://mail.python.org/mailma

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 comp

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(, {'a': 5, 'r': 2, 'b'

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

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

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.

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 f

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 arbi

Re: after del list , when I use it again, prompt 'not defined'.how could i delete its element, but not itself?

2006-06-02 Thread bearophileHUGS
python wrote: > after del list , when I use it again, prompt 'not defined'.how could i > delete its element,but not itself? This is a way: >>> a = range(10) >>> del a[:] >>> a [] >>> a.append(20) >>> a [20] Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list

Re: re beginner

2006-06-04 Thread bearophileHUGS
SuperHik wrote: > I was wondering is there a better way to do it using re module? > perheps even avoiding this for loop? This is a way to do the same thing without REs: data = 'Yellow hat\t2\tBlue shirt\t1\nWhite socks\t4\tGreen pants\t1\nBlue bag\t4\tNice perfume\t3\nWrist watch\t7\tMobile phone

Re: re beginner

2006-06-04 Thread bearophileHUGS
> strings = islice(data2, 0, len(data), 2) > numbers = islice(data2, 1, len(data), 2) This probably has to be: strings = islice(data2, 0, len(data2), 2) numbers = islice(data2, 1, len(data2), 2) Sorry, bearophile -- http://mail.python.org/mailman/listinfo/python-list

Re: How to add few pictures into one

2006-06-06 Thread bearophileHUGS
Lad wrote: > I want to to do that as easy as possible. But not even more easy. > I think the easest way could be add( append) an image to another > into an image file so that I can use an image browser and see all > pictures in one file. Is that possible? Well, you can do it with PIL, creating

Re: How to generate k+1 length strings from a list of k length strings?

2006-06-08 Thread bearophileHUGS
Boris Borcic: > I'd favor the following, that I find most readable > sets = map(set,list_of_strings) > res = set(''.join(sorted(s1|s2)) for s1 in sets for s2 in sets if > len(s1^s2)==2) I think there can be written more readable code. For my programs I usually prefer simpler code, that (if possib

Re: How to generate k+1 length strings from a list of k length strings?

2006-06-08 Thread bearophileHUGS
> I think there can be written more readable code. For my programs I > usually prefer simpler code, that (if possible) even a children can > understand. So I can debug, modify and improve it better & faster. Debugged: I think it can be written more readable code. In this newsgroup sometimes I have

Re: How to generate k+1 length strings from a list of k length strings?

2006-06-08 Thread bearophileHUGS
Boris Borcic: > I challenge you to write simpler code to do the equivalent. I don't do challenges. I too have written the code to solve that problem, it wasn't much different from your one (it uses a generator function xpairs, to yeild a scan of the different pairs, about half the square, it uses

Re: How to generate k+1 length strings from a list of k length strings?

2006-06-09 Thread bearophileHUGS
Boris Borcic: > > I don't do challenges. > > Pfff... and you don't do real debates either. Different nations have different values and different cultures, in mine challenges are often seen as things for children, and a waste of time for adults (probably in USA challenges are appreciated more). By

Re: removing dictionary key-pair

2006-06-09 Thread bearophileHUGS
JD>I try to remove a dictionary key-pair (remove an entry), >>> d = {1:2, 3:4} >>> d {1: 2, 3: 4} >>> del d[1] >>> d {3: 4} Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list

Re: Combining The Best Of Python, Ruby, & Java??????

2006-06-12 Thread bearophileHUGS
Scala seems terse and fast enough, few examples: http://shootout.alioth.debian.org/gp4sandbox/benchmark.php?test=all&lang=psyco&lang2=scala Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list

Re: Extracting values from text file

2006-06-16 Thread bearophileHUGS
First try, probably there are better ways to do it, and it's far from resilient, it breaks in lot of different ways (example: more than one number in one line, number with text on both sides of the line, etc.) I have divided the data munging in many lines so I can see what's happening, and you can

Re: Search substring in a string and get index of all occurances

2006-06-21 Thread bearophileHUGS
Maric Michaud: > I'd love str implement a xsplit(sub, start, end) method, so I could have > wrote : enumerate(s.xsplit(subs, 0, -1)). Some of such str.x-methods (or str.i-methods, etc) can be useful (especially for Py3.0), but keeping APIs simple and compact is very important, otherwise when you p

Re: returning index of minimum in a list of lists

2006-06-21 Thread bearophileHUGS
This way is probably slowe (two scans of the list for l1, and even more work for l2), but for small lists it's probably simple enough to be considered: For a simple list: >>> l1 = [5, 3, 2, 1, 4] >>> l1.index(min(l1)) 3 For a list of lists: >>> l2 = [[3, 3, 3, 3], [6], [10], [3, 3, 3, 1, 4], [3,

Re: Specifing arguments type for a function

2006-06-22 Thread bearophileHUGS
Paolo Pantaleo: > and I want to state that the_arg must be only of a certain type > (actually a list). Is there a way to do that? I suggest this very good library, typecheck: http://oakwinter.com/code/typecheck/ Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list

Re: map() return of flat tuple list

2006-06-22 Thread bearophileHUGS
Maybe you want something like this (but this doesn't use map): def indexes(m): return [(r,c) for r, row in enumerate(m) for c in xrange(len(row))] m1 = [[2,2,5], [2,2], [2,2,2,2]] m2 = [[], [2], [1,2,3,4]] print indexes(m1) print indexes(m2) Output: [(0, 0), (0, 1),

Re: map() return of flat tuple list

2006-06-23 Thread bearophileHUGS
Mirco: >He, this looks more like Haskell than like Python (for me, it looks awful ;-) Maybe this is more readable: ar = [[3,3,3,3], [3,3,3,1], [3,3,4,3]] print sorted( [(r,c) for r,row in enumerate(ar) for c in xrange(len(row))], key=lambda (r,c): ar[r][c] )

Re: Python and cellular automata (It works this time!)

2006-06-24 Thread bearophileHUGS
Few coding suggestions: - Don't mix spaces and tabs; - Don't write line (comments) too much long; - Don't post too much code here; - For this program maybe Pygame is more fit (to show the images in real time) instead of PIL; - Maybe Psyco can help speed up this program; - Maybe ShedSkin will suppor

Re: 2Qs

2006-06-24 Thread bearophileHUGS
SuperHik, for the second question there is builtin sum(): >>> values = 10.5, 5, -12 >>> sum(values) 3.5 Your if becomes: if x>10 and y>10 and z>10 and sum(tritup(x,y,z)): print "OK" Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list

Re: Mix-In Class Methods At Run-Time

2006-06-24 Thread bearophileHUGS
I think it's possible, most of such kind of things are possible with Python. I'm not an expert yet in such kind of things, so this can be a starting point for you (note the shadowing of m2, the class docstrings, etc). Other people can give you something better or more correct. class A: def m1(

Re: Mix-In Class Methods At Run-Time

2006-06-26 Thread bearophileHUGS
I can't give much answers, I am not that expert yet. Bruno Desthuilliers: > newstyle classes can do whatever oldstyle classes > did, *and much more* (descriptors and usable > metaclasses) - and they are somewhat faster too. In the past I have done few tests, and it seemed that new style classes a

Re: Dictionary .keys() and .values() should return a set [with Python 3000 in mind]

2006-07-02 Thread bearophileHUGS
Paddy: > Mind you, Never rely on that implied ordering. Always use items(). Using dict.items() is probably better, but the manual says: >If items(), keys(), values(), iteritems(), iterkeys(), and itervalues() are >called with no intervening modifications to the dictionary, the lists will >direc

Re: wanted: framework for creating nice step by step graphical visualisations of running Python code

2006-07-02 Thread bearophileHUGS
I remember Gato: http://gato.sourceforge.net/ It animates only algorithms on graphs, but it seems a starting point, and it works. I vaguely remember another system, but probably not very good. Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list

Re: ascii character - removing chars from string

2006-07-03 Thread bearophileHUGS
bruce: > valid_str = strip(invalid_str) > where 'strip' removes/strips out the invalid chars... This isn't short but it is fast: import string valid_chars = string.lowercase + string.uppercase + \ string.digits + """|!'\\"£$%&/()=?^*é§_:;>+,.-<\n \t""" all_chars = "".join(map(

Re: built in zip function speed

2006-07-04 Thread bearophileHUGS
[EMAIL PROTECTED]: Using Python you can do: # Data: l_a = [1.1, 1.2] l_b = [2.1, 2.2] l_c = [3.1, 3.2] l_d = [5.1, 4.2] from itertools import izip l_e = [(c-d) - (a-b)*(a-b) for a,b,c,d in izip(l_a, l_b, l_c, l_d)] print l_e With psyco + the standard module array you can probably go quite fast,

EuroPython 2006 and Py3.0

2006-07-05 Thread bearophileHUGS
>From this interesting blog entry by Lawrence Oluyede: http://www.oluyede.org/blog/2006/07/05/europython-day-2/ and the Py3.0 PEPs, I think the people working on Py3.0 are doing a good job, I am not expert enough (so I don't post this on the Py3.0 mailing list), but I agree with most of the things

Re: python function defs/declarations

2006-07-05 Thread bearophileHUGS
bruce: > is there a way for me to do this.. > > print "hello" > foo() > > def foo(): > i = 2 > print "i = "i > > ie, to use 'foo' prior to the declaration of 'foo' Generally no you can't, you have to define a name before using it. Why do you want to do that? Bye, bearophile -- http://mail.pyt

Re: EuroPython 2006 and Py3.0

2006-07-05 Thread bearophileHUGS
Sybren Stuvel: > But you can put a set in a dict... Only as values, not as keys, because sets are mutable. Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list

Re: EuroPython 2006 and Py3.0

2006-07-05 Thread bearophileHUGS
Kay Schluehr: > there is nothing really new or interesting or challenging. > Micro-optimizations and shape lifting. I see. Maybe Python is becoming a commodity used by more than 10e6 persons, so changellenges aren't much fit anymore. Guido has tried to avoid the problems of Perl6, making Py3.0 a i

CLPython

2006-07-05 Thread bearophileHUGS
Just found: http://trac.common-lisp.net/clpython/ Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list

Re: looping question 4 NEWB

2006-07-06 Thread bearophileHUGS
manstey: > is there a faster way of implementing this? Also, does the if clause > increase the speed? I doubt the if increases the speed. The following is a bit improved version: # Original data: data = 'asdfbasdf' find = (('a', 'f'), ('s', 'g'), ('x', 'y')) # The code: data2 = data for pat,rep

Re: Making a time series analysis package in python - advice or assistance sought

2006-07-07 Thread bearophileHUGS
Ray Tomes: > My package will have the following capabilities: > 1. Able to read time series data in a variety of formats. > 2. Able to create, manipulate and save time series files. > 3. Able to do vector arithmetic on time series, including > dozens of functions. > 4. Loop and macro facilities to

Re: performance of dictionary lookup vs. object attributes

2006-08-25 Thread bearophileHUGS
Andre Meyer: > Is the test meaningful and are you surprised by the results? > I am, actually, because I would have assumed that attribute access > with an object should be faster because lookup can be precompiled. The results seem okay. Python is a dynamic language, object attributes (and methods,

Re: Don't use __slots__ (was Re: performance of dictionary lookup vs. object attributes)

2006-08-25 Thread bearophileHUGS
Aahz wrote: > Taking a look at __slots__ is fine as long as you don't actually use them. I remember the recent discussion about such matters... but I don't understand its dangers fully still. I assume __slots__ may be removed in Python 3.0, but maybe "experts" need it now an then. Or maybe a "expe

Re: Python and STL efficiency

2006-08-25 Thread bearophileHUGS
Pebblestone: > (defun test4 () > (let ((a (make-array 400 :element-type 'string > :adjustable nil)) > (b nil)) > (dotimes (i 100) > (progn > (let ((j (1- (* 4 i > (setf (aref a (incf j))

Re: Python and STL efficiency

2006-08-25 Thread bearophileHUGS
Pebblestone: >I heard that python's list is implemented as adjustable array. Correct, an array geometrically adjustable on the right. >Here's my lisp implementation:< What's the memory size of a before computing b? You can compare it with Python, that may need less memory (because the array co

Re: Python and STL efficiency

2006-08-25 Thread bearophileHUGS
Pebblestone: > Sorry, I did some miscalculation what a shame. Don't worry. For me using Py 2.4.3 those memory values are 4536 before and 20184 kb after, it means a difference of 15648 kb, that equals to about 16023552 bytes, that equals to about 100 * 4 * 4. That means 4 bytes for each

Re: question about class, functions and scope

2006-08-26 Thread bearophileHUGS
nephish: > is this legal ? is it pythonic? It's legan and pythonic. Functions are here for a purpose. Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list

Re: Learning Python

2006-08-26 Thread bearophileHUGS
JAG CHAN: > As I had written earlier, I am trying to learn Python. > I chose IDLE as an editor to learn Python. > Now I find that it is an online editor. > It is not possible for me to be always on online while learning. > Kindly suggest me a suitable editor (for Windows XP) which does not require

Re: question about class, functions and scope

2006-08-26 Thread bearophileHUGS
nephish: > one more question. > the functions defined above the classes that the could be called from > within the classes, they do not need a 'self' declaration because they > are not part of a class, right? Class methods generally require the self as first parameter, functions don't need the sel

Re: Middle matching - any Python library functions (besides re)?

2006-08-27 Thread bearophileHUGS
If you want to avoid an O(n^2) algorithm, you may need to find a signature for each file. Then you use such signatures to compute hashes, and unique them with a dict (dict values may be the file names). Later you can weed out the few wrong collisions produced by the possibly approximated signature.

Re: Split with python

2006-08-29 Thread bearophileHUGS
Norman Khine: > I have a csv file which is has a field that has something like: > "text (xxx)" > "text (text) (yyy)" > "text (text) (text) (zzz)" > > I would like to split the last '(text)' out and put it in a new column, > so that I get: > "text","(xxx)" > "text (text)","(yyy)" > "text (text) (tex

Re: where or filter on list

2006-08-30 Thread bearophileHUGS
Duncan Booth: > And for Python 2.5 users only we have the exciting new option of: > >>> foo = [5, 2, -1, -7, 3, -6, 2, 12] > >>> min(foo, key=abs) > -1 Good. This is possibility for older Python: l = [(rnd()-0.5) * 20 for i in xrange(1000)] print min( (abs(el), el) for el in l )[1] Bye, bearophi

Re: python equivalent for fputc

2006-08-30 Thread bearophileHUGS
Putty wrote: > I'm porting a program a friend wrote in C over to Python and I've run > into a little hang-up. The C program writes characters out to a file. > I'm 99% sure that a conversion is going on here as well. I know for a > fact that it's taking a number and turning it into a character. >

Re: python loops

2006-08-31 Thread bearophileHUGS
AlbaClause wrote: > for i in range(length): > print i Or usually better: for ii in xrange(length): ... Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list

Re: python loops

2006-09-01 Thread bearophileHUGS
Kay Schluehr: > I hate ii ;) It's not nice looking, I agree. A more explicit name is often better. But I think ii is better than i because you can find it in the code (with the Find command of the editor or grep) more easily than i. Bye, bearophile -- http://mail.python.org/mailman/listinfo/py

Re: dictionaries - returning a key from a value

2006-09-01 Thread bearophileHUGS
Avell Diroll: keys = [key for key in sampledict if sampledict[key] == '1974'] Or better, given: sampledict = {'the Holy Grail':1975, 'Life of Brian':1979, 'Party Political Broadcast':1974,'Mr. Neutron':1974, 'Hamlet':1974, 'Light Entertainment War':1974} keys = [key

Re: dictionaries - returning a key from a value

2006-09-01 Thread bearophileHUGS
Fredrik Lundh: > better in what sense? With better I may mean faster, or needing less memory, or requiring a shorter code, or other things. It depends on many things, related to the program I am creating. Thank you for the timings, you are right, as most times. Sometimes I am wrong, but I try to

Re: How to run Python file?

2006-09-03 Thread bearophileHUGS
mistral: > I have installed ActivePython > http://www.activestate.com/Products/ActivePython/ > How I can run Python file, test.py? Running Python scripts is easy. Load the test.py from the ActivePython and run it. Otherwise you can just click on the file, otherwise you can open a shell in the dir

Re: OO on python real life tutorial?

2006-09-03 Thread bearophileHUGS
Patrick Thomson: > After all, GvR said that > "wxPython is the best and most mature cross-platform GUI toolkit, > given a number of constraints. The only reason wxPython isn't the > standard Python GUI toolkit is that Tkinter was there first." > > The Wax toolkit (http://zephyrfalcon.org/labs/wax.h

str.isspace()

2006-09-03 Thread bearophileHUGS
Are you using the str.isspace() method? I don't use it, so if most people don't uses it, then it may be removed from Py 3.0. I usually need to know if a string contains some non-spaces (not space class chars). To do it I use something like: if aline.strip(): ... If you really need str.isspace()

Re: Removing from a List in Place

2006-09-05 Thread bearophileHUGS
Tim Williams: > You could also use a list comprehension for your case > >>> alist = [1 ,2 ,3] > >>> alist = [x for x in alist if x != 2] > >>> alist > [1, 3] The list comprehension filtering is the simpler and often the best solution. For memory-conscious people this is another possible (un-python

Re: Extracting text from a string + note

2006-09-07 Thread bearophileHUGS
Tempo: > I am having a little trouble extracting text from a string. The > string that I am dealing with is pasted below, and I want to > extract the prices that are contained in the string below. This may help: >>> import re >>> reg = r"(?<= \$ ) (?: \d* \.? \d* )" >>> prices = re.compile(r

Re: Question about subclassing - version 2

2006-09-08 Thread bearophileHUGS
Frank Millman, just a short note, more expert people can give you better answers. There aren't abstract classes in Python. They are all concrete. You may have classes with undefined methods (they may raise NotImplementedError). Multiple inheritance isn't supported by Java and Ruby, but it is suppor

Re: Looking for a regexp generator based on a set of known string representative of a string set

2006-09-08 Thread bearophileHUGS
[EMAIL PROTECTED]: > I am looking for python code that takes as input a list of strings > (most similar, > but not necessarily, and rather short: say not longer than 50 chars) > and that computes and outputs the python regular expression that > matches > these string values (not necessarily strictl

Re: Map with an extra parameter

2006-09-08 Thread bearophileHUGS
This may be what you need: class foo: def __init__(self, a, b): self.a = a self.b = b vars = [1,2,3,4,5,6] objects = [foo(a, 1) for a in vars] Note that in Python the new is expressed wit the () at the end: > f = new foo() Bye, bearophile -- http://mail.python.org/mailman/list

Re: convert loop to list comprehension

2006-09-08 Thread bearophileHUGS
Two possibile solutions: seq = [2, 3, 1, 9] print sum( ([i]*n for i,n in enumerate(seq)), []) print [i for i, x in enumerate(seq) for _ in xrange(x)] The second one is probably quite faster. Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list

Re: Map with an extra parameter

2006-09-08 Thread bearophileHUGS
ml1n wrote: > In the interests of speed my thinking was that using map would move the > loop out of Python and into C, is that the case when using list > comprehension? I'd always thought it was just syntatic short hand for > a Python loop. In Python the faster things are often the most simple. Y

Re: Map with an extra parameter

2006-09-08 Thread bearophileHUGS
ml1n: > Looks like someone already did: > http://mail.python.org/pipermail/python-list/2005-January/259870.html Don't belive too much in such general timings. Time your specific code when you think you need a true answer. Timing Python code is very easy and fast, and sometimes results are surprisi

Re: Function metadata (like Java annotations) in Python

2006-09-09 Thread bearophileHUGS
oripel: Maybe this is a silly suggestion, the docstring is already overloaded, but it may be used for this too: def foo(): """ ... ... @ATTR name="Xander" @ATTR age=10 @ATTR hobby="knitting" """ ... (Or somethins similar without the @). Later you can retrive the a

Re: "filtered view" upon lists?

2006-09-12 Thread bearophileHUGS
Wildemar Wildenburger: > I sort of wanted to avoid these. Though my lists shouldn't terribly > long, so performance is not an issue so much. I simply want to avoid > having two datasets that I have to sync. Major pain, I believe. Note that if you just have to scan the "view list", then you can use

Re: table (ascii text) lin ayout recognition

2006-09-13 Thread bearophileHUGS
My version, not much tested. It probably doesn't work well for tables with few rows. It finds the most frequent word beginnings, and then splits the data according to them. data = """\ 44544 ipod apple black 102 GFGFHHF-12 unknown thing bizar brick mortar tbc 45fjk

Re: Delete items in nested dictionary based on value.

2006-09-13 Thread bearophileHUGS
My first try, not much tested: def clean(d): for key,val in d.items(): if isinstance(val, dict): val = clean(val) if not val: del d[key] return d a = {1: {2: 2, 3: {1: None, 2: 2}}, 2: 2, 3: None} print clean(a) # Out: {1: {2: 2, 3: {2: 2}}, 2: 2} b

Re: Delete items in nested dictionary based on value.

2006-09-13 Thread bearophileHUGS
Better: def clean(d): for key,val in d.items(): if isinstance(val, dict): val = clean(val) if val is None or val == {}: del d[key] return d a = {1: {2: 2, 3: {1: None, 2: 2}}, 2: 2, 3: None} print clean(a) # Out: {1: {2: 2, 3: {2: 2}}, 2: 2} b = {1:

Re: Delete items in nested dictionary based on value.

2006-09-13 Thread bearophileHUGS
Fuzzyman: > Can you delete values from a dictionary whilst iterating over its items ? Try the code, it works. I am not iterating on the dict, I am not using dict.iteritems(), that produces a lazy iterable, I am using dict.items() that produces a list of (key,value) pairs. And I am not removing ele

Re: table (ascii text) lin ayout recognition

2006-09-13 Thread bearophileHUGS
Here you can find an improved version: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/498093 -- http://mail.python.org/mailman/listinfo/python-list

Re: Tkinter.Button(... command) lambda and argument problem

2006-09-15 Thread bearophileHUGS
In that case you don't need a lambda: import Tkinter as tk class Test: def __init__(self, parent): buttons = [tk.Button(parent, text=str(x+1), command=self.highlight(x)) for x in range(5)] for button in buttons: button.pack(side=tk.LEFT) def highlight(self, x)

Re: Code Golf Challenge : 1,000 Digits Of Pi

2006-09-18 Thread bearophileHUGS
Paddy: > Is having good 'code-fu' worthwhile? It may be trivial to score but do > the results show who iss the better programmer? With Python you can't win, because Perl and Ruby allow for shorter programs. Beside the language, you win if you can invent more tricks, that you have to avoid in real

Re: why a main() function?

2006-09-18 Thread bearophileHUGS
Others have already told you the most important things. There is another secondary advantage: the code inside a function runs faster (something related is true for C programs too). Usually this isn't important, but for certain programs they can go 20%+ faster. Bye, bearophile -- http://mail.pyt

Re: Read a group of files as a list

2006-09-18 Thread bearophileHUGS
citlaly: > I'm trying to use the files from a > "folder" as a list. What I want to do is read each one as a list, but > just the name of the file, the data inside doesn't matter. >>> import os >>> os.listdir("...path...") [ file names... ] If you are using Windows I suggest you to invert the

Re: Replace single character at given position

2006-09-19 Thread bearophileHUGS
Martin Kulas: > Are there better (faster) ways to achieve my goal? > I have looked through the methods of type ``string'' > but I have not found any appropriate method or function. Python strings are immutable, so you can't modify them, so you can't find methods to change them. I agree that someti

Re: Is it possible to change a picture resolution with Python?

2006-09-20 Thread bearophileHUGS
Lad: > Is it possible to change a picture resolution with Python? > Let's say I have a picture with a resolution of 96 dpi and I would like > to increase to 256dpi or higher. "Resolution" is a too much overloaded word, from some point of view increasing the resolution of images is a very difficult

Re: Is it possible to change a picture resolution with Python?

2006-09-20 Thread bearophileHUGS
Lad: > But the above code increases size only , but not DPI resolutions( > vertical nad horizontal).I need a higher vertical and horisontal > resolutions. > Any idea how to do that? Do you need to overwrite the DPI tag contained in the header of a Jpeg/PNG image? Then you can probably find some

Re: Can I inherit member variables?

2006-09-21 Thread bearophileHUGS
MonkeeSage: If you have multiple inheritance do you need the old style init anyway? class Animal1(object): def __init__(self, weight, colour): self.weight = weight self.colour = colour class Animal2(object): def __init__(self, name): self.name = name class Bird(Animal1, Animal2)

itertools.count(-3)

2006-09-21 Thread bearophileHUGS
itertools.count docs say: Does not currently support python long integers. Note, count() does not check for overflow and will return negative numbers after exceeding sys.maxint. This behavior may change in the future. But it seems it doesn't support negative numbers too: >>> from itertools import

Re: Tkinter button not working as expected

2006-09-21 Thread bearophileHUGS
[EMAIL PROTECTED] wrote: > I've created a short test program that uses tkFileDialog.askdirectory > to help the user input a path into a tk entry widget. The problem I'm > having is that when I run the code as listed below, the getPath > function is called when the program initially runs, not when

Re: Newbie RE question

2006-09-22 Thread bearophileHUGS
T: > I meant to say: Search for any character in r'/\:*?"<>|' in a string You don't need a RE to solve such problem. There are many ways to solve it, this is one of the simpler (Python 2.4+): >>> chars = set(r'/\:*?"<>|') >>> s1 = "is this a sample string?" >>> bool( set(s1) & chars ) True >>> s

Doctests for nested functions

2006-09-22 Thread bearophileHUGS
Recently I have posted this same question on it.comp.lang.python, maybe there aren't solutions, but I'd like to know what you think. Can doctests be added to nested functions too? (This can be useful to me, I use nested function when I don't have attributes that I have to remember, but I want to s

Re: grabbing random words

2006-09-23 Thread bearophileHUGS
Jay: > How would I be able to grab random words from an internet source. I'd > like to grab a random word from a comprehensive internet dictionary. > What would be the best source and the best way to go about this? Why do you need to grab them from the net? A simpler solution seems to keep a loca

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