Re: swapping numeric items in a list

2006-08-22 Thread bearophileHUGS
Jiang Nutao: To convert list aa = [0x12, 0x34, 0x56, 0x78] into [0x34, 0x12, 0x78, 0x56] How to do it fast? My real list is huge. Note that: a = range(6) a [0, 1, 2, 3, 4, 5] a[::2] [0, 2, 4] a[1::2] [1, 3, 5] So you can do: a[::2], a[1::2] = a[1::2], a[::2] a [1, 0, 3, 2,

Re: Regular Expression question

2006-08-21 Thread bearophileHUGS
I am not expert of REs yet, this my first possible solution: import re txt = tag1 name=john/ br/ tag2 value=adj__tall__/ tag1 name=joe/ tag1 name=jack/ tag2 value=adj__short__/ tfinder = r# The opening the tag to find \s* # Possible space or newline

Re: convert a long string in binary

2006-08-20 Thread bearophileHUGS
bussiere maillist: i've got a very long string and i wanted to convert it in binary Not much tested: _nibbles = {0:, 1:0001, 2:0010, 3:0011, 4:0100, 5:0101, 6:0110, 7:0111, 8:1000, 9:1001, A:1010, B:1011, C:1100, D:1101, E:1110, F:} def

Re: sum and strings

2006-08-18 Thread bearophileHUGS
Paul Rubin: Sybren Stuvel: Because of there should only be one way to do it, and that way should be obvious. There are already the str.join and unicode.join methods, Those are obvious??? They aren't fully obvious (because they are methods of the separator string), but after reading some

Re: a bug in list.remove?

2006-08-18 Thread bearophileHUGS
Astan Chee: (This is a small trap of Python, that it shares with some other languages, and it shows that it may exist a language with a higher level than Python.) Generally in Python you can't modify a sequence that you are iterating on. There are some ways to avoid the problem. You can create a

Re: New to python

2006-08-17 Thread bearophileHUGS
Tim Gallagher: I am new to python and I have a few questions. I am an old Perl hacker been using Perl for many years. I wanted to give python a try, I am happy with it so far. In some places and jobs Perl is the only scripting language used still, but It seems there are other people like you

Re: idea on how to get/set nested python dictionary values

2006-08-15 Thread bearophileHUGS
[EMAIL PROTECTED] wrote: py def SetNewDataParam2(Data, NewData): ... if type(Data[Data.keys()[0]]) == type(dict()): ... SetNewDataParam2(Data[Data.keys()[0]], NewData) ... else: ... Data[Data.keys()[0]] = NewData ... ... return Data py Data = {'a':{'b':{'c':1}}}

Re: idea on how to get/set nested python dictionary values

2006-08-15 Thread bearophileHUGS
Like for the list.sort() method, to remind you that this function operate by side effect, maybe it's better if it doesn't return the modified nested dict: def setNested(nest, path, val): nest2 = nest for key in path[:-1]: nest2 = nest2[key] nest2[path[-1]] = val Bye,

Re: yet another noob question

2006-08-14 Thread bearophileHUGS
Stargaming: Also note that reduce will be removed in Python 3000. Then let's use it until it lasts! :-) bearophile -- http://mail.python.org/mailman/listinfo/python-list

Re: yet another noob question

2006-08-14 Thread bearophileHUGS
Gerard Flanagan: mod5 = ['1','2','3','4','5'] X = [ ''.join([a,b,c,d,e]) for a in mod5 for b in mod5 for c in mod5 for d in mod5 for e in mod5 ] A modified version of your one is the faster so far: v = 12345 r = [a+b+c+d+e for a in v for b in v for c in v

Re: yet another noob question

2006-08-14 Thread bearophileHUGS
Jason Nordwick: Stargaming wrote: Also note that reduce will be removed in Python 3000. What will replace it? Nothing, I presume. You will have to write a function to find another way to solve problems. Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list

Re: Memory problem

2006-08-14 Thread bearophileHUGS
Yi Xing wrote: I need to read a large amount of data into a list. So I am trying to see if I'll have any memory problem. When I do x=range(2700*2700*3) I got the following message: Traceback (most recent call last): File stdin, line 1, in ? MemoryError Any way to get around this

Re: yet another noob question

2006-08-13 Thread bearophileHUGS
Simon Forman: I originally meant this as a joke and was going to say not to use it. But on my old, slow computer it only takes about a second or two. Another possibility, still using a filter: nodig = set(06789) r = [i for i in xrange(1, 5+1) if not (set(`i`) nodig)] Bye, bearophile

Re: Python checking for None/Null values

2006-08-11 Thread bearophileHUGS
Fuzzydave: I am trying to check all of the historyRep items to check if they are empty/null/None (whatever the term is in python) An item can't be empty in Python,and null doesn't exist, it can be the object None. But probly that's not your case. I did print historyRep[8] out and it falls

Re: Easy image rendering?

2006-08-10 Thread bearophileHUGS
[EMAIL PROTECTED]: my eventual goal is to be able to put the pictures on the screen with a full-screen interface. Not in a visible window, with just the picture and then a black backdrop for it. Pygame (plus PIL if you need) can do that, Pygame manages full screens too. Bye, bearophile --

Re: technique to enter text using a mobile phone keypad (T9 dictionary-based disambiguation)

2006-08-10 Thread bearophileHUGS
Yu-Xi Lim: Thank you for your comments, and sorry for my last cryptic answer. I think Bearophile isn't refering to compression of the dictionary, but the predictive algorithms used by modern data compressors. However, I think he's over-complicating the issue. It is *not* a data compression

Re: Two Classes In Two Files

2006-08-09 Thread bearophileHUGS
[EMAIL PROTECTED]: Is there a way to avoid having to use the from xxx import yyy syntax from files in the same directory? You can just use: import xxx and then: class Two(xxx.One): ... If you don't want to use the import line, you have to put the two classes into the same module. Bye,

Re: technique to enter text using a mobile phone keypad (T9 dictionary-based disambiguation)

2006-08-09 Thread bearophileHUGS
Justin Azoff: It takes a second or two to read the list of words in, Nice solution. If you want to speed up the initialization phase you may use something like this (it requires a bit more memory, because lines contains all the words). Note that the words and numbers have the same sorting

Re: technique to enter text using a mobile phone keypad (T9 dictionary-based disambiguation)

2006-08-09 Thread bearophileHUGS
Note that this is essentially a data-compression problem, so the most accurate solution is probably to use an instrumeted PAQ compressor in a certain smart way, but you have to work a lot to implement this solution, and maybe this problem doesn't deserve all this work. Bye, bearophile --

Re: technique to enter text using a mobile phone keypad (T9 dictionary-based disambiguation)

2006-08-09 Thread bearophileHUGS
I've tested that sorting just the strings instead of the tuples (and removing the stripping) reduces the running time enough: def __init__(self): numbers = '222333444555666888' conv = string.maketrans(string.lowercase, numbers) lines =

Re: technique to enter text using a mobile phone keypad (T9 dictionary-based disambiguation)

2006-08-09 Thread bearophileHUGS
John Machin: 2. All responses so far seem to have missed a major point in the research paper quoted by the OP: each word has a *frequency* associated with it. When there are multiple choices (e.g. 43 - [he, if, id, ...]), the user is presented with the choices in descending frequency order.

Re: String.digits help!!!

2006-08-08 Thread bearophileHUGS
Simon Forman: It's unlikely to be deprecated since it doesn't make much sense to make it an attribute of the str type. Why? Thank you, bearophile -- http://mail.python.org/mailman/listinfo/python-list

Re: String.digits help!!!

2006-08-08 Thread bearophileHUGS
Simon Forman: accessing it from a module (perhaps math.. math.infinity, math.epsilon, etc., just like math.pi and math.e.) It too looks acceptable. I look forward to hearing your thoughts an the subject. Thank you, but I am not expert enough on such topics to give you good comments, so I

Re: is it possible to dividing up a class in multiple files?

2006-08-07 Thread bearophileHUGS
Martin Höfling: is it possible to put the methods of a class in different files? I just want to order them and try to keep the files small. Well, you can create one or more modules filled with nude methods, and you can define a class inside another module, and then add the methods to this last

Re: do people really complain about significant whitespace?

2006-08-07 Thread bearophileHUGS
Jason wrote: He points out that if some code gets accidentally dedented, it is difficult for another programmer to determine which lines were supposed to be in the indented block. I pointed out that if someone accidentally moves a curly brace, the same problem can occur. I like significant

Re: singleton decorator

2006-08-07 Thread bearophileHUGS
Andre Meyer: What is the preferred pythonic way of implementing singleton elegantly? Maybe to just use a module. Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list

Re: do people really complain about significant whitespace?

2006-08-07 Thread bearophileHUGS
Jason wrote: But newsgroup managers are certainly an issue. For comment thingies online, the preformat tag is your friend, too. Time ago I used to add a | or something similar at the beginning of lines, to avoid the leading whitespace stripping done by Google Groups. Other (silly) solutions are

Re: More int and float attributes

2006-08-06 Thread bearophileHUGS
Self: D is a very nice language, that I hope to see more used. It is copying lot of things from Python. Tim Roberts: I don't see that. It looks rather like an incremental improvement to C and C++ rather than a language influenced by Python. Thank you for your comments. Mine was probably just

Re: string.translate with unicode

2006-08-06 Thread bearophileHUGS
[EMAIL PROTECTED]: It's not a bug, but such incompatibility problem will probably be solved with Python 3.0, when most strings will managed as unicode. The documentation says: it returns a copy of the s where all characters have been mapped through the given translation table which must be a

More int and float attributes

2006-08-05 Thread bearophileHUGS
sys.maxint gives the largest positive integer supported by Python's regular integer type. But maybe such attribute, with few others (they can be called min and max) can be given to int type itself. D is a very nice language, that I hope to see more used. It is copying lot of things from Python. D

Re: More int and float attributes

2006-08-05 Thread bearophileHUGS
Paddy: Or do you mean the ability to choose between hardware supported float s? e.g. float and double precision? No, I mean just having the ability to ask the float (his attribute) what are the max and min values it can represent, etc. stop = float.max ... I don't know any simple way to know

Re: Railroad track syntax diagrams

2006-08-03 Thread bearophileHUGS
Paul McGuire: generation of the railroad diagrams (in something more legible/appealing than ASCII-art!). That ASCII-art looks easy enough to read. It may be bad when the graph becomes very big. Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list

Re: Best way to read, and analyze a log file?

2006-08-01 Thread bearophileHUGS
[EMAIL PROTECTED]: 1- Read the data and put all variables in a list 2- Read the data and put all the variables in dictionary? the logs is in this format xx The separation is by byte size like xxx three bytes for code x , bytes for hour, etc.. I have two main

Re: Static Variables in Python?

2006-07-31 Thread bearophileHUGS
tac-tics: If you declare bits in set_bit() as global bits = ..., it will create it as a global variable without you having to declare it outside of the function. Just be careful about name conflicts. Are you sure? def fun(): global x = 10 fun() print x Bye, bearophile --

Re: Math package

2006-07-29 Thread bearophileHUGS
[EMAIL PROTECTED]: I want to write a program which would have a 2 dimensional array of 1 billion by 1 billion. This is for computational purposes and evaluating a mathematical concept similar to Erdos number. Maybe you are talking about the edges of a graph with 1e9 nodes. This structure is

Re: list of lists of lists ....

2006-07-28 Thread bearophileHUGS
You can use this, fast, gives a tuple: from Tkinter import _flatten as flatten --- The xflatten/flatten version I sometimes use, maybe I can put something similar in the cookbook, but it can be improved a lot (and isrecursive is too much fragile): from pprint import

Re: Process files in order

2006-07-27 Thread bearophileHUGS
A possibility: import os _, _, file_names = os.walk().next() print sorted(file_names, key=lambda fn: os.stat(fn)[8]) Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list

Re: list problem

2006-07-26 Thread bearophileHUGS
placid: This may be a solution: l1 = ['acXXX1', 'XXX2', 'wXXX3', 'kXXX5'] l2 = [ 'bXXX1', 'xXXX2', 'efXXX3', 'yXXX6', 'zZZZ9'] import re findnum = re.compile(r[0-9]+$) s1 = set(int(findnum.search(el).group()) for el in l1) s2 = set(int(findnum.search(el).group()) for el in l2) nmax =

Re: Newbie Q: Class Privacy (or lack of)

2006-07-26 Thread bearophileHUGS
Steve Jobless: I'm hearing that they are features, but don't use them. You can use them if you know why you are doing it. You can also take a look at PyChecker and PyLint, they may help you. Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list

Re: How to find difference in years between two dates?

2006-07-26 Thread bearophileHUGS
Roy Smith: 2) I find the and 1 or 0 part very confusing. I can't remember all the minor rules about operator precedence, but I'm sure this works out to some clever hack involving boolean short-circuit evaluation to get around the lack of a ternary operator in python. If I need to pull out

Re: Using iterators to write in the structure being iterated through?

2006-07-26 Thread bearophileHUGS
Pierre Thibault, some people here surely know enough Python (and C++) to solve your problem, but often the problem is understanding the problem. I have understood your problem just partially, so the following are just ideas. First of all I suggest you to use a normal Python list to keep the data,

Re: binding more than one attribute in a facntion

2006-07-26 Thread bearophileHUGS
[EMAIL PROTECTED]: def f(a, b, c): return a + b + c I can do: fplus10 = f(10) and then call f with 2 params and it works. If you call that f or that fplus10 with two parameters you obtain an error in both cases. You have an error with the f(10) line too. With Python 2.5 you can probably use

Re: removing duplicates, or, converting Set() to string

2006-07-26 Thread bearophileHUGS
The write accepts strings only, so you may do: out.write( repr(list(clean)) ) Notes: - If you need the strings in a nice order, you may sort them before saving them: out.write( repr(sorted(clean)) ) - If you need them in the original order you need a stable method, you can extract the relevant

Re: dicts vs classes

2006-07-25 Thread bearophileHUGS
Simon Hibbs: It seems to me that unless you need some of the functionality supplied with dictionaries (len(a), has_key, etc) then simple objects are a syntacticaly cleaner and more natural way to express yourself. I'd say the opposite. Classes contain a dict of their attributes, etc. So if

Re: Don't use __slots__! (was Re: dicts vs classes)

2006-07-25 Thread bearophileHUGS
Aahz, citing Guido: __slots__ is a terrible hack with nasty, hard-to-fathom side effects that should only be used by programmers at grandmaster and wizard levels. Unfortunately it has gained an enormous undeserved I think I have used __slots__ just one time. Can you tell me some of of such bad

Re: Functions, Operators, and Overloading?

2006-07-24 Thread bearophileHUGS
Michael Yanowitz: Maybe I am missing something, but from what I've seen, it is not possible to overload functions in Python. Maybe here you can find some ideas: http://www.artima.com/forums/flat.jsp?forum=106thread=101605

Re: Note on PEP 299

2006-07-21 Thread bearophileHUGS
Faulkner: http://home.comcast.net/~faulkner612/programming/python/mainer.py It's a bit of magic, I'll test it more, but it seems to work binding the main() with Psyco too. I have changed it a little (removed argv passed to the main and the import of type, etc). I don't know if/when I'll use it,

Note on PEP 299

2006-07-20 Thread bearophileHUGS
I don't like much the syntax of: if __name__ == '__main__': Some time ago I have read this PEP: http://www.python.org/dev/peps/pep-0299/ And why it was refused: http://mail.python.org/pipermail/python-dev/2006-March/062955.html I think the name of the standard main function may be just main(),

Re: Retrieve ext. variables in python program

2006-07-19 Thread bearophileHUGS
alfa1234: Does anyone know and equalent way to confirm a Variable from the same property file using PYTHON code ??? Using globals(), locals(), and dir() you can find if your name exists already. Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list

Re: No need to close file?

2006-07-18 Thread bearophileHUGS
T wrote: Do I need to close the file in this case? Why or why not? for line in file('foo', 'r'): print line Close the file in Jython, but often it's not necessary in CPython. Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list

Re: range() is not the best way to check range?

2006-07-18 Thread bearophileHUGS
Dan Bishop: xrange already has __contains__. The problem is, it's implemented by a highly-inefficient sequential search. Why not modify it to merely check the bounds and (value - start) % step == 0? I think this is a nice idea. Bye, bearophile --

Re: Coding style

2006-07-18 Thread bearophileHUGS
Volker Grabsch wrote: IMHO, that flaw of Python should be documented in a PEP as it violates Python's priciple of beeing explicit. It also harms duck typing. I think this may be good food for Python 3.0, the are removing undefined comparisons too (), etc. bye, bearophile --

Re: newbie graphing recommendations ?

2006-07-16 Thread bearophileHUGS
Bryan: do you think that pygame would be a good alternative to matplotlib to create some graphs such simple bar and line graphs? For graphs MatPlotLib is usually better, and its antialiasing library (Anti-Grain Geometry) is wonderful. Pygame gives a bit more freedom but you have to do all for

Re: newbie graphing recommendations ?

2006-07-15 Thread bearophileHUGS
Adam wrote: Where should a py newbie start to do some 2D graphs on screen ? PythonGraphApi, Gato, looks interesting pygraphlib, matplotlib, is there a best native Python place to start ? The only good and simple way I have found so far to do some free graphics with Python in a Window is

Re: reading specific lines of a file

2006-07-15 Thread bearophileHUGS
Pierre Quentel: If the line number of the first line is 0 : source=open('afile.txt') for i,line in enumerate(source): if i == line_num: break print line I don't know if something like this can be called an improvement: from itertools import islice afile = file('data.txt')

Re: Chunking sequential values in a list

2006-07-14 Thread bearophileHUGS
Peter Otten: which is almost identical to the last example in http://docs.python.org/lib/itertools-example.html I see, thank you. I haven't had enoug time and brain to fix it (and the OP question seemed like homework, so leaving some other things to do is positive). I think still that too much

Re: EuroPython 2006 and Py3.0

2006-07-14 Thread bearophileHUGS
Steve Holden: The real problems with the Py3k list seem to be associated with a number of people who, despite having had little apparent connection to the language until now, have joined the list and started making inappropriate suggestions, which then have to be (patiently) rejected. This

Re: Too many imports to use a business class library?

2006-07-13 Thread bearophileHUGS
Sanjay wrote: I am new to python. Sorry if this is too novice question, Don't worry and welcome. While coding a business class library, I think it is preferable to have one class per source file, rather than combining all classes into one file, considering multiple developers developing the

Re: Chunking sequential values in a list

2006-07-13 Thread bearophileHUGS
It looks like homework. Sometimes the simpler code is better: def splitter(seq): if not seq: return [] result = [] current = [seq[0]] for pos, el in enumerate(seq[1:]): if el - current[-1] 1: result.append(current[:]) current = []

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

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

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

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

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( chr,

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 directly

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

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

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 x10 and y10 and z10 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

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

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

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, 0, 3,

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: 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=alllang=psycolang2=scala Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list

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). Bye,

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

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

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

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: 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: chop() and empty() functions

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

Re: Speed up this code?

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

Re: Speed up this code?

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

Re: newb: comapring two strings

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

Re: newb: comapring two strings

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

Re: bitstream

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

Re: newb: comapring two strings

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

Re: Sorting of list containing tuples

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

Re: Large Dictionaries

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

Re: comparing values in two sets

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

Re: comparing values in two sets

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

<    5   6   7   8   9   10   11   12   >