Re: sort one list using the values from another list

2006-02-28 Thread bearophileHUGS
>_ is just a plain variable name in Python. It is sometimes when a variable is >needed to receive a value that won't be used.< Like in some other interactive systems (Mathematica, etc, but with a different syntax) _ has a use in the interactive shell, it contains the last unassigned result: >>>

Open source reliability study

2006-03-04 Thread bearophileHUGS
They have used a lot of time and money to find bugs in Python too: http://www.theregister.co.uk/2006/03/03/open_source_safety_report/print.html 0.32 defects per 1,000 lines of code in LAMP, it says. I hope they will show such Python bugs, so Python developers can try to remove them. From the botto

Re: Simulation Programming Skills and Python

2006-03-06 Thread bearophileHUGS
Richard Blackwood: >Is the skill of being able to translate in one's head realworld relationships >into a model represented by code an inherent/native skill of all programmers?< I don't think so. Creating a good computational model can be a complex art. >Python a good language for simulation p

IronPython on Shootout

2006-03-06 Thread bearophileHUGS
I have suggested the Shootout site to add tests for IronPython too (tests are done on Mono): http://shootout.alioth.debian.org/gp4sandbox/benchmark.php?test=all&lang=iron People that use IronPython can probably fix some of those programs. Bye, bearophile -- http://mail.python.org/mailman/listi

Re: IronPython on Shootout

2006-03-06 Thread bearophileHUGS
This is the answer that I did receive about Boo: https://alioth.debian.org/tracker/index.php?func=detail&aid=302999&group_id=30402&atid=411005 igouy-guest>We already have languages no one uses and no one writes rograms for - once there are a bunch of shootout programs written in Boo and tested on

Re: Python advocacy in scientific computation

2006-03-06 Thread bearophileHUGS
Michael Tobis: > Python plays so well with others. For many applications, NumPy is fine. > Otherwise write your own C or C++ or F77; building the Python bindings > is trivial. On Windows I have found that creating such bindings is very very difficult... I have succed only partially, with C++, and

ANN: pynetwork 2.25

2005-04-30 Thread bearophileHUGS
Pynetwork is a graph library, my first SourceForge project: http://sourceforge.net/projects/pynetwork/ It included tests, some demo, some premilinary docs, and some images. You can see some screenshoots on the SourceForge page for them. I know about 5-6 other graph libraries for Python, one even

Re: ANN: pynetwork 2.25

2005-05-01 Thread bearophileHUGS
Kay Schluehr>What is wrong with the other librarys that they can't be approved?< I presume there are so many kinds of graphs, that one data structure doesn't fit all... On the other hand, I think that trying to design a too much general data structure can have some drawbacks. I've tried a compromi

Re: pyvm -- faster python

2005-05-08 Thread bearophileHUGS
I've seen the benchmarks, they look quite interesting. This project is probably a LOT of work; maybe people can tell us about such efforts *before* doing so much work, so we can discuss it, and avoid wasting time. Maybe you can explain us why it is so fast, and/or maybe you can work with the othe

Re: Unique Elements in a List

2005-05-09 Thread bearophileHUGS
runes: > d = {} > for k in data: > try: > d[k] += 1 > except: > d[k] = 1 > > for k,v in d.items(): > if v == 1: > print k For this problem, if duplicated keys are common enough, this version is probably the faster. With this *different* problem, it seems that

Re: Merging overlapping spans/ranges

2005-05-10 Thread bearophileHUGS
This is the problem of finding the connected components inside an interval graph. You can implement the algorithms yourself, of you can use my graph data structure here: http://sourceforge.net/projects/pynetwork/ The graph methods: createIntervalgGraph And: connectedComponents can probably solve

Re: Convert String to Int and Arithmetic

2007-06-13 Thread bearophileHUGS
Kay Schluehr: > >>> int(cpuSpeed.split(":")[1].strip()) Probably this suffices: int(cpuSpeed.split(":")[1]) Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list

Re: NEWBIE: Extending a For Statement.

2007-05-21 Thread bearophileHUGS
mosscliffe: > if key in xrange (60,69) or key == 3: I keep seeing again and again code like this, mostly from people not much expert of Python, but the PEP 260 shows the fast in was removed, so it's O(n). Maybe removing the fast __contains__ was bad for necomers (or just the casual Python users, t

Re: Fastest Way To Iterate Over A Probability Simplex

2007-05-22 Thread bearophileHUGS
On May 22, 11:19 am, Efrat Regev: > I want to iterate over all > such vectors under the constraint that the granularity of > each component is at most some delta. You can think of this like your sum is an integer>=1 and the single "probabilities" are integers>=1 So given the sum, like 6, you can f

From D

2007-07-24 Thread bearophileHUGS
There are various things I like about the D language that I think Python too may enjoy. Here are few bits (mostly syntactical ones): 1) (we have discussed part of this in the past) You can put underscores inside number literals, like 1_000_000, the compiler doesn't enforce the position of such und

Re: From D

2007-07-26 Thread bearophileHUGS
Sorry for the slow feedback. Stargaming>Sounds like a good thing to be but the arbitrary positioning doesnt make any sense.< The arbitrary positioning allows you to denote 4-digit groups too in binary/hex literals, like in my example: auto x = 0b0100_0011; Stargaming>fits into the current movem

Re: Perl and Python, a practical side-by-side example.

2007-03-02 Thread bearophileHUGS
Few suggestions, some important, some less important. All my suggestions are untested. Use 4 spaces to indent. If you want to speed up this code you can move it inside a function. After that, if you want to make it even faster you can use Psyco too. Ho are the dates represented? How do you te

Re: print a ... z, A ... Z, "\n"' in Python

2007-03-03 Thread bearophileHUGS
js: > crange = lambda c1, c2: [ chr(c) for c in range(ord(c1), ord(c2)+1) ] > ''.join(chr(c) for c in crange('a', 'z') + crange('A', 'Z')) Yes, managing char ranges is a bit of pain with Python. You can also pack those chars: xcrange = lambda cc: (chr(c) for c in xrange(ord(cc[0]), ord(cc[1]) +1)

Re: Is every number in a list in a range?

2007-03-05 Thread bearophileHUGS
Steven W. Orr: > I have a list ll of intergers. I want to see if each number in ll is > within the range of 0..maxnum One possible nice solution (Python V.2.5): data = [1, 20, 22, 11, 400, 7] maxnum = 100 print all(0 <= x <= maxnum for x in data) maxnum = 1000 print all(0 <= x <= maxnum for x in

Re: Graphviz Python Binding for Python 2.5 on Windows?

2007-03-06 Thread bearophileHUGS
Alex Li: > Now, I am sure we will redo it in C# after my "prototype"; Sadly this happens often, they don't want to keep using two languages when one may suffice. On the other hand, you may even find a way to adapt your Python code to IronPython, so maybe you can avoid the translation to C#. Bye,

Re: Best place for a function?

2007-03-07 Thread bearophileHUGS
Diez B. Roggisch: > If it really has no other use as in this class, put it as an > instancemethod in there. Alternatively, you _could_ nest it like this: Using an instancemethod may be the most formally correct solution for that problem, but often nested function are the simpler solution. A downsi

property syntax

2007-03-08 Thread bearophileHUGS
Probably you have already discussed this topic, but maybe you can stand touching it again briefly. Maybe properties aren't used so often to deserve a specific syntax, but I don't like their syntax much. Here I show some alternative solutions that work with the current Python, followed by a syntax i

Re: property syntax

2007-03-08 Thread bearophileHUGS
Gabriel Genellina: > You miss this common way, that does not depend on metaclasses, > nor base classes, nor custom decorators... My purpose was to discuss a new syntax. The other stuff is mostly for reference, to show that lot of (some) people has tried to find alternative solutions to a problem t

Re: bisect on a list of lists

2007-03-09 Thread bearophileHUGS
Paulo da Silva: > What is the best way to have something like the bisect_left > method on a list of lists being the comparision based on an > specified arbitrary i_th element of each list element? You may use this recipe of mine that I've just put there for you, but it's not fully tested yet (if y

Re: Bitpacked Data

2007-03-11 Thread bearophileHUGS
Bjoern Schliessmann: > I'd use the module struct, with bit shifting operators to extract > the bits. Maybe Pyrex can be used to create a small module that can manage similar bitfields quickly and with a syntax not too much far from the Erlang bit syntax. Bye, bearophile -- http://mail.python.or

Re: dict.items() vs dict.iteritems and similar questions

2007-03-15 Thread bearophileHUGS
Laurent Pointal: > you may prefer range/items when processing of the result > value explicitly need a list (ex. calculate its length) Creating a very long list just to know the len of an iterator is barbaric, so sometimes I use this: def leniter(iterator): if hasattr(iterator, "__len__"):

Re: dict.items() vs dict.iteritems and similar questions

2007-03-15 Thread bearophileHUGS
Steve Holden: > once you know how long it is you > no longer have access to the elements. Or did I miss something? Now and then I need to know how many elements there are, and not what they are, so in those situations storing them isn't necessary. Bye, bearophile -- http://mail.python.org/mailm

Re: dict.items() vs dict.iteritems and similar questions

2007-03-15 Thread bearophileHUGS
Alex Martelli: > Right. However, "return sum(1 for _ in iterator)" may be a handier way > to express the same desctructive semantics as the last 4 lines here. With the speed tests I have done my version did come out as the faster one. Bye, bearophile -- http://mail.python.org/mailman/listinfo

Re: To count number of quadruplets with sum = 0

2007-03-17 Thread bearophileHUGS
n00m: > i have no NumPy to test it... > without Psyco Anton's code is the winner: ~48sec vs ~58sec of my code > But with Psyco my runtime is ~28sec; Anton's - ~30sec (PC: 1.6 ghz, > 512 mb) > Not so bad.. keeping in mind that 256000 billions quadruplets to > check :) I have oiled it a bit, you can

Re: To count number of quadruplets with sum = 0

2007-03-17 Thread bearophileHUGS
Mark Dufour: > FWIW, the original program can also be compiled with Shed Skin (http:// > mark.dufour.googlepages.com), an experimental (static-)Python-to-C++ > compiler, resulting in a speedup of about 8 times for a single test > with 500 tuples. If we want to play, then this is a literal translat

Re: where function

2007-03-18 Thread bearophileHUGS
vorticitywo: > Is there a function in Python analogous to the "where" function in > IDL? Python gives very elastic syntax, you can simply do: data = [0,1,2,3,4,2,8,9] print [pos for pos, el in enumerate(data) if el==2] Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list

Re: When is List Comprehension inappropriate?

2007-03-20 Thread bearophileHUGS
BJörn Lindqvist: > While they > may be faster, Psyco is great here. Also, if you have lots of 2d-loops > like "for x in something: for y in something:", then it could be more > beautiful to separate the iteration from the task: > > def iterimage(im, width, height, step = 1): > for y in range(0,

Re: why brackets & commas in func calls can't be ommited? (maybe it couldbe PEP?)

2007-03-21 Thread bearophileHUGS
I have nothing against brackets, and I think Python has used them for too much time to allow a so big change in its syntax. But I think in some situations Ruby allows to omit them, solving some of the "impossibile" problems shown in this thread. This makes Ruby a bit better than Python to create ap

Re: parsing combination strings

2007-03-21 Thread bearophileHUGS
Bruno Desthuilliers: > exp = re.compile(r'^([0-9]+)') > for s in ["12ABA", "1ACD", "123CSD"]: > print exp.match(line).group(0) This may be enough too: exp = re.compile(r'\d+') for s in ["12ABA", "1ACD", "123CSD"]: print exp.match(line).group(0) With it: exp.match("a123CSD") = None Bye,

Re: On text processing

2007-03-23 Thread bearophileHUGS
Daniel Nogradi: > Any elegant solution for this? This is my first try: ddata = {} inside_matrix = False for row in file("data.txt"): if row.strip(): fields = row.split() if len(fields) == 2: inside_matrix = False ddata[fields[0]] = [fields[1]]

Re: plot dendrogram with python

2007-03-27 Thread bearophileHUGS
Frank: > does anyone know if there is a way to plot a dendrogram with python. > Pylab or matplotlib do not provide such a function. An ASCII solution: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/139422 Some graphics: http://plone.org/products/phylogenetictree http://www.bioinformatics

Re: PyPy 1.0: JIT compilers for free and more

2007-03-28 Thread bearophileHUGS
Kay Schluehr: > RPython is heuristically defined as a subset of Python "static enough > to be translatable to C". So it is actually static analysis that is > done here, not on a local scale but on a simpler sublanguage. It is > not clear to me whether for a sufficiently annotated Py3K program the >

Re: Modal value of an array

2007-03-29 Thread bearophileHUGS
Alex Martelli: > >>> foo = ["spam", "eggs", "spam", "spam", "spam", "beans", "eggs"] > >>> max(foo, key=foo.count) It's a very nice solution, the shortest too. But I think it's better to develop your own well tested and efficient stats module (and there is one already done that can be found around

Re: Any "consumer review generators" available?

2007-03-29 Thread bearophileHUGS
> Python's standard module "ai" has a function called > "generateFakeReview". I believe it does what you want, but I haven't > used it myself. It's nice to have an ai module too in the standard library (A*, CSP, etc), Norvig may help with the Python version of his AIMA sofware ;-] Bye, bearophile

Re: clean up html document created by Word

2007-03-30 Thread bearophileHUGS
jd: > I am looking for python code (working or sample code) that can take an > html document created by Microsoft Word and clean it up (if you've > never had to look at a Word-generated html document, consider yourself > lucky ;-) Alternatively, if you know of a non-python solution, I'd > like to

Re: Sorting a multidimensional array by multiple keys

2007-03-31 Thread bearophileHUGS
Rehceb Rotkiv: > can I sort a multidimensional array in Python by multiple sort keys? A > litte code sample would be nice! If you want a good answer you have to give me/us more details, and an example too. Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list

Re: Shed Skin Python-to-C++ Compiler 0.0.21, Help needed

2007-04-02 Thread bearophileHUGS
Paul Boddie: > the author's frustration with the state of the standard library: > something which almost always gets mentioned in people's pet Python > hates, but something mostly ignored in the wider enthusiasm for > tidying up the language. There is some possibility that Python 3.1 will have wha

Re: Sorting a multidimensional array by multiple keys

2007-04-02 Thread bearophileHUGS
Steven Bethard: > there's almost never a reason to use the cmp= argument to > sort() anymore. It's almost always better to use the key= argument. I always use key now, but maybe cmp uses less memory. There can be few situations where cmp is better still. Bye, bearophile -- http://mail.python.o

Re: Shed Skin Python-to-C++ Compiler 0.0.21, Help needed

2007-04-02 Thread bearophileHUGS
Paul Boddie: > Prior to that PEP being written/published, I made this proposal: > http://wiki.python.org/moin/CodingProjectIdeas/StandardLibrary/Restru... On first sight it looks good. Python 3.0-3.1 is the best and probably only possibility for such improvement (I have said 3.1 too because I thin

Re: Need help on reading line from file into list

2007-04-04 Thread bearophileHUGS
Bruno Desthuilliers: > result = [line.strip() for line in f.readlines()] Probably better, lazily: result = [line.strip() for line in infile] Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list

Re: Indentifying the LAST occurrence of an item in a list

2007-04-04 Thread bearophileHUGS
Terry Reedy: > def rindex(lis, item): > for i in range(len(lis)-1, -1, -1): > if item == lis[i]: > return i > else: > raise ValueError("rindex(lis, item): item not in lis") This is an alternative, I don't know if it's faster: def rindex(seq, item): for pos,

Re: How can I make sure my python exit

2007-04-04 Thread bearophileHUGS
> Typically when the last piece of code executes, the program ends. You > could import sys and explicitly exit by calling sys.exit(0). > Mike raise SystemExit works too. Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list

Re: Picture resolution and PIL

2007-04-06 Thread bearophileHUGS
Johny: > Is it possible to find out a picture resolution by using PIL package By Gian Mario Tagliaretti: import PIL.Image a = PIL.Image.open("foo.jpg") a.info["dpi"] (72, 72) (It may raise an exception if that information isn't available) I don't know if that can be used to read the DPI tag insi

Re: tuples, index method, Python's design

2007-04-07 Thread bearophileHUGS
Carsten Haese: > The lack of convincing use cases is still a pertinent reason today. Note > that the original poster on this thread did not present a use case for > tuple.index, they were only asking out of curiosity. > If you have a use case for tuple.index, please show it to me, and I'll > show y

Re: tuples, index method, Python's design

2007-04-07 Thread bearophileHUGS
Carsten Haese: > Adding useless features always makes a product worse. What's your use > case for tuple.index? Ruby is a bit younger than Python, it has shown that few things may be better done in a different way. An advantage of PyPy is that it allows faster and simpler ways to perform language e

Re: tuples, index method, Python's design

2007-04-10 Thread bearophileHUGS
BJörn Lindqvist: > > One might perversely allow extension to lists and tuples to allow > >[3, 4] in [1, 2, 3, 4, 5, 6] > > to succeed, but that's forcing the use case beyond normal limits. The > > point I am trying to make is that circumstances alter cases, and that we > > can't always rely on

Re: Does python have the static function member like C++

2007-04-10 Thread bearophileHUGS
> Many thanks for you! > I've never heard of the "staticmethod" , that's great! Note that you don't need an empty __init__ : class AAA: counter = 0 @staticmethod def counter_increase(): AAA.counter += 1 print "couter now:", AAA.counter AAA.counter_increase() Bye, be

Re: Newbie help with array handling

2007-04-12 Thread bearophileHUGS
loial: > I am new to python and am converting an awk script to python It seems there are many people trying to convert awk code to Python :-) > I need to store some data in an array/table of some form > keyvalue1, value1, value2, value3 > keyvalue2, value1,value2, value3 > keyvalue3, value1,valu

Re: tuples, index method, Python's design

2007-04-12 Thread bearophileHUGS
Carsten Haese: > Nobody seems to be complaining about "+" behaving > "inconsistently" depending on whether you're adding numbers or > sequences. We can learn a bit from the D language too, it uses ~ for array/string concatenation, look for the "Array Concatenation" here: http://www.digitalmars.com

Re: Lists and Tuples and Much More

2007-04-12 Thread bearophileHUGS
Scott: Others will give you many more answers, here is just a bit. > And how would you sort the list that's in the list? I guess that goes in > conjunction with the section above, but still: >>> my_list = [6, 4, 3, 5, 2, 1] > >>> my_list.append([7, 9, 8, 10]) > >>> my_list.sort() > >>> my_list >

Re: split and regexp on textfile

2007-04-13 Thread bearophileHUGS
Flyzone: > i have a problem with the split function and regexp. > I have a file that i want to split using the date as token. My first try: data = """ error text Mon Apr 9 22:30:18 2007 text text Mon Apr 9 22:31:10 2007 text text Mon Apr 10 22:31:10 2007 text text """ import re date_find = re.

Re: Any way to refactor this?

2007-04-13 Thread bearophileHUGS
James Stroud: > Probably best is to code the parameters as > a set of tuples and iterate over them. I agree. Before: def _create_3D_xhatches(...pass more parameters here...): for x in xrange(-axis_length, axis_length + 1): if x == 0: continue visual.cylinder(pos=(x

Re: list comparison help?

2007-04-14 Thread bearophileHUGS
7stud: > prefixes = [ "the", "this", "that", "da", "d", "is", "are", "r", > "you", "u"] > sentence = "what the blazes is the da this da this the" > sentence = sentence.split() > result = [word for word in sentence if word not in prefixes] > print result If prefixes becomes long enough (let's say

Re: Python Feature Request: (?) Group all file-directory-related stdlib functions in one place

2007-04-14 Thread bearophileHUGS
> Currently file-directory-related functionality in the Python standard > library is scattered among various modules such as shutil, os, > dircache etc. So I request that the functions be gathered and > consolidated at one place. Some may need renaming to avoid conflicts > or for clarification. I

Re: Making a tree out of a 2 column list

2007-04-14 Thread bearophileHUGS
The solution I have found is quite similar to the [EMAIL PROTECTED] one (it uses a defaultdict, and it yields the result lazily), but it lacks the quite useful max_depth (it can be added): from collections import defaultdict def finder(el, stor): if el in stor: for v in stor[el]:

Re: combination function in python

2007-04-15 Thread bearophileHUGS
DanielJohnson: > Please help, I couldnt find the function through help. You can't find it because it's not there: def factorial(n): """factorial(n): return the factorial of the integer n. factorial(0) = 1 factorial(n) with n<0 is -factorial(abs(n)) """ result = 1 for i in

Re: combination function in python

2007-04-15 Thread bearophileHUGS
Steven D'Aprano: > That's a naive and slow implementation. For even quite small values > of n and k, you end up generating some seriously big long ints, > and then have to (slowly!) divide them. > A better implementation would be something like this: You are right, thank you for the improvement (t

Re: combination function in python

2007-04-15 Thread bearophileHUGS
Mark Dickinson: > def choose(n, k): > ntok = 1 > for t in xrange(min(k, n-k)): > ntok = ntok*(n-t)//(t+1) > return ntok With few tests, it seems this is faster than the version by Jussi only with quite big n,k. (Another test to be added, is the assert n>0 of my original versio

Re: Making a tree out of a 2 column list

2007-04-15 Thread bearophileHUGS
Sebastian Bassi: > I guess this should make the program enter into a endless loop. But > the data won't have such a redundancy, because it was taken from a > philogenetic tree. But errors and bugs do happen, inside data too; so often it's better to be on safe side if the safe code is fast enough.

python-list@python.org

2007-04-16 Thread bearophileHUGS
Once in while I too have something to ask. This is a little problem that comes from a Scheme Book (I have left this thread because this post contains too much Python code for a Scheme newsgroup): http://groups.google.com/group/comp.lang.scheme/browse_thread/thread/a059f78eb4457d08/ The function mu

python-list@python.org

2007-04-17 Thread bearophileHUGS
Paddy: > def multiremberandco1(el, seq, fun): > l1, l2 = [], [] > c = seq.count(e1) > l1 = [el] * c > l2 = [el] * (len(seq) - c) > return fun(l1, l2) Thank you Paddy, but unfortunately there is a bug in my first function, this is more correct: def multiremberandco1b(el, seq,

Re: simple question on dictionary usage

2007-10-27 Thread bearophileHUGS
My take too :-) dict(item for item in record.iteritems() if item[0][0] == 'E') Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list

Re: simple question on dictionary usage

2007-10-28 Thread bearophileHUGS
Marc 'BlackJack' Rintsch>``s.startswith('E')`` is a little safer than ``s[0] == 'E'`` as the former returns `False` if `s` is empty while the latter raises an `IndexError`.< Thank you. In this problem if there is an empty key in the record dict then maybe it's better to raise an IndexError, becaus

Re: Need some help...

2007-10-28 Thread bearophileHUGS
> I want to create a program that I type in a word. You can see that Python has a command to input strings from the command line. > chaos > each letter equals a number > A=1 > B=20 > and so on. > So Chaos would be > C=13 H=4 A=1 O=7 S=5 > I want to then have those numbers > 13+4+1+7+5 added

Re: 3 number and dot..

2007-10-31 Thread bearophileHUGS
Hrvoje Niksic: > I'm surprised that no one has proposed a regex solution, such as: I presume many Python programmers aren't much used in using REs. > >>> import re > >>> re.sub(r'\d{1,3}(?=(?:\d{3})+$)', r'\g<0>.', str(1234567)) > '1.234.567' It works with negative numbers too. It's a very nice

Re: Iterable Flattener with Depth.

2007-11-01 Thread bearophileHUGS
Pradeep Jindal: > Any comments? Something with similar functionality (plus another 20 utility functions/classes or so) has probably to go into the std lib... :-) Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list

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 u

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 att

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 wor

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

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

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

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 eleme

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

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

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 cont

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 i&1) len isn't able to tell it: >>> len(l) Traceback (most recent call last): File "", line 1, in TypeError: object of type 'generator' has no len() This is a bad solution, it may need t

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 i&1) > >>> 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 functi

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 t

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 quic

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 th

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 l

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 results

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

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

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 antiali

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 compa

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

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 (

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