Re: A different kind of interface

2009-01-22 Thread bearophileHUGS
Eduardo O. Padoan: > You are almost *describing* reinteract: - Thank you for the link and the software, I have not tried it yet, but from the screencast it looks quite nice. - I am glad that there are people that don't think that Emacs is (despite being good) the alpha and omega of editing. There'

Re: A different kind of interface

2009-01-22 Thread bearophileHUGS
Marc 'BlackJack' Rintsch: > +IBQ- seems to be the way your newsreader displays the dashes that where > in Ben's posting.  I see "em dash" characters there: I see, thank you. I never finish to see all the weird things of the Web (through google groups). Bye, bearophile -- http://mail.python.org/ma

Re: Counter Class -- Bag/Multiset

2009-01-23 Thread bearophileHUGS
Raymond Hettinger: > The collections module in Python 2.7 and Python 3.1 has gotten a new > Counter class that works like bags and multisets in other languages. Very nice. Python std lib is growing more data structures, increasing the power of a default Python installation. I can remove more and m

Re: Counter Class -- Bag/Multiset

2009-01-23 Thread bearophileHUGS
bearophile: > Are keys restricted to be long and int values only? Or are they > general (referenced) objects + a control of their integral nature? Here I meant values, sorry. Also: what's the rationale of allowing negative values too? Bye, bearophile -- http://mail.python.org/mailman/listinfo/pyt

Ordered dict by default

2009-02-05 Thread bearophileHUGS
Choosing the right data structure is usually a matter of compromises, and sometimes the best you can do is to change some data structures and look for the faster running time. To do this it helps to have a language that allows you to swap data structures in the more transparent way possible. It's

where clause

2009-02-05 Thread bearophileHUGS
This comes after a small discussion in another Python newsgroup. Haskell supports a where clause, that's syntactic sugar that allows you to define things like this: p = a / b where a = 20 / len(c) b = foo(d) That means: a = 20 / len(c) b = foo(d) p = a / b I don't know how much good t

Re: Ordered dict by default

2009-02-05 Thread bearophileHUGS
Bryan Olson: > A few bits fuzzy. Is the following True or False if dict is insert-ordered? >     dict(a=6, b=7) == dict(b=7, a=6) In my odict implementation I have disallowed that syntax because if you want to define a mydict(**kwds) function that allows a syntax like: mydict(a=6, b=7) it takes

Re: where clause

2009-02-05 Thread bearophileHUGS
Albert Hopkins: > One could imagine this getting "out of hand" e.g. Yes, any syntax can be abused (your example isn't abusive enough). > a = 20 / len(c) > where > c = p / b > try: > b = foo(d) > where > d = bar() >

Re: Trouble sorting a list of objects by attributes

2009-02-06 Thread bearophileHUGS
Robocop: >then within each department block of the list, have it organized by projects.< I don't know what does it means. > timesheets.sort(key=operator.attrgetter('string')) Try something like: timesheets.sort(key=attrgetter("department", "engagement", "date", "stare_hour")) > My brain might

Re: Ordered dict by default

2009-02-06 Thread bearophileHUGS
Cameron Simpson: >increases the unrealised assumptions about mappings in general which a newbie >may acquire, causing them pain/complaint later with other mappings< This is wrong in several different ways. > I would much rather keep dictionaries as performant as possible, as a > bare mapping,

Re: Ordered dict by default

2009-02-06 Thread bearophileHUGS
bearophile: > In Python 3 strings are all unicode, integral numbers are all > multiprecision, chars in Python 2.x+ are strings, lists are arrays > that can grow dynamically, and so on because the Purpose of Python > isn't to be as fast as possible, but to be first of all flexible, > safe, easy, not

Re: Python Module: nift

2009-02-08 Thread bearophileHUGS
More suggestions for a real-world Python programmer: - There's code duplication, the original poster may express reet as a composition of the other functions. - A Python string/list/array can be inverted with [::-1] - I suggest to convert the examples of the main doscstring into doctests. - The mai

Re: Python Module: nift

2009-02-08 Thread bearophileHUGS
Paul McGuire: > LEET_LETTERS = dict( zip("eEaAiItTsSoObB", "33441177550088") ) > def leet(s): >     return ''.join( LEET_LETTERS.get(c,c) for c in s ) This may be better: from string import maketrans def leet(txt): leet_chars = maketrans("eEaAiItTsSoObB", "33441177550088") return txt.tra

Re: Python Module: nift

2009-02-08 Thread bearophileHUGS
Gabriel Genellina: > bearophile: > > - Generally I suggest to learn to code in the small, using as little > > code as possible. > > I completely agree with all the above suggestions, except this last one.   > Ok, I think I know what you mean, but a beginner might understand this   > completely wron

Re: Python Module: nift

2009-02-09 Thread bearophileHUGS
Steven D'Aprano: > There's less code, fewer bugs and lines. Less applies to continuous > quantities, like weight and "amount of code", and fewer applies to > countable quantities. Thank you, I'll try to improve my use of the language. > Within reason, naturally. There's a reason why we write: >

Re: Python binaries with VC++ 8.0?

2009-02-10 Thread bearophileHUGS
Paul Rubin: > Gideon Smeding of the University of > Utrecht has written a masters' thesis titled "An executable > operational semantics for Python". A significant part of Computer Science is a waste of time and money. Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list

Re: Functional schmunctional...

2009-02-10 Thread bearophileHUGS
Here a small benchmark: def ip2inet01(a): # can't be used with 6 li = a.split('.') assert len(li) == 4 a = int(li[0])*16777216 b = int(li[1])*65536 c = int(li[2])*256 d = int(li[3]) return a+b+c+d from itertools import count def ip2inet02(a): blocks = a.split('.')

Re: Unexpected string behaviour: txt = 'this' ' works'

2009-02-11 Thread bearophileHUGS
christopher.saun...@durham.ac.uk (c d saunter): >I assume it is a feature of the compiler.< Yes it's a bug-prone antifeature that's probably a relic from C that doesn't have a concatenation operator among strings as Python does (+). So in Python it saves you to use + at the cost of possible bugs.

Re: Unexpected string behaviour: txt = 'this' ' works'

2009-02-11 Thread bearophileHUGS
Jason: > It's such a minor optimization, that you probably wouldn't see any > effect on your program. >>> from dis import dis >>> def f(): ... return 'This is ' + 'an example.' ... >>> dis(f) 2 0 LOAD_CONST 3 ('This is an example.') 3 RETURN_VALUE Bye, bea

Re: An executable operational semantics for Python

2009-02-12 Thread bearophileHUGS
gideon: > I've recently finished my Master's thesis on the semantics of Python. > In my thesis I define the semantics of Python by rewriting an abstract > machine. The sources that are used to produce my thesis can also be > compiled into a working interpreter. Hence I call it an 'executable' > sem

Re: Another optimization request :-)

2009-02-12 Thread bearophileHUGS
On Feb 12, 2:48 am, jeffg wrote: > If anyone wants to take this on... I would really really like to have > the spring_layout modified to support multi-threading if at all > possible. You can start creating a compiled Python extension using ShedSkin, it may be enough. Bye, bearophile -- http://ma

Re: flexible find and replace ?

2009-02-16 Thread bearophileHUGS
OdarR: > how would you do a clever find and replace, where the value replacing > the tag is changing on each occurence ? > "...TAGTAGTAG..TAG." > is replaced by this : > "...REPL01REPL02REPL03..REPL04..." You may

Re: Speedup Bitmap Parser

2009-02-16 Thread bearophileHUGS
Jayson Santos: > Hello people, I'm writing a Bitmap parser for study purposes, This code: x = 0 y = 0 for line in bmp.bitmap_lines.lines: for color in xrange(len(line.colors)): canvas.create_line(x, y, x+1, y, fill="#%02x%02x%02x" % (line.colors

Re: Speedup Bitmap Parser

2009-02-16 Thread bearophileHUGS
Jayson Santos: > Here is the new code using your changeshttp://pastebin.com/m6dfe619d > And here is the profilerhttp://pastebin.com/m74d282b8 I have suggested you to profile the program mostly for pedagogical purposes, it's often a good thing to do if you want to speed up a program. But now it's y

Re: Speedup Bitmap Parser

2009-02-16 Thread bearophileHUGS
Jayson Santos: > Do I need use some patters or others progamming conventions ? That's a strong question... Knowing OOP well is important, and it's often a good way to program, etc. But... You may try to rewrite your code with functions only and no classes (well, you may need to use classes for the

Re: pythonic array subsetting

2009-02-17 Thread bearophileHUGS
Nick Matzke: > I have to do this hundreds of times, so speed would be useful. Try to create a 2D array with NumPy, and then slice it. Note that slicing syntax has a "stride" too. Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list

Re: Speedup Bitmap Parser

2009-02-17 Thread bearophileHUGS
Jayson Santos: > After changing my code to use only functions instead classes > my code is too much faster. > Here cProfile statistcs: > Using old code : 633608 function calls in 1.361 CPU seconds > Using new code: 475487 function calls in 0.800 CPU seconds If you show a pastebin of the new versio

Re: Reading from text

2009-02-17 Thread bearophileHUGS
oamram: > i have a directory with about 50 text file and i need to > iterate through them and get > line 7 to 11 from each file and write those lines into another > file(one file that will contain all lines). Files can be iterated line-by-line, so this idiom: for line in file: ... will give you

Re: Speedup Bitmap Parser

2009-02-17 Thread bearophileHUGS
Jayson Santos: > And here is the final code:http://pastebin.com/f3e20d669 Note that if you use Psyco this lookup trick isn't useful, but if the Psyco isn't available it can improve performance a little: append = BitmapList['lines'].append I suggest to replace this code: red, green, blue

Re: how to detect if a dictionary has been modified ?

2008-11-23 Thread bearophileHUGS
Stef Mientki: > I would like to detect if a dictionary has been changed. > So I would like to have a modified-flag. A solution is of course to create a SDict class, that works like a normal dict, and also watches for changes and has an extra boolean attribute. Bye, bearophile -- http://mail.pytho

Re: how to detect if a dictionary has been modified ?

2008-11-23 Thread bearophileHUGS
Paul Rubin: > As a couple of people have said, you could make a dict subclass that > notices when you do updates.  I think the real answer is a > "functional" dictionary, which means one that is never updated. Python V. 2.4, 2.5, 2.6. 3.0 have gained more and more lazy-style features, this is chan

Re: No complex rationals in Python 3.0

2008-11-24 Thread bearophileHUGS
Rock: >so I guess this could be an important issue.< What they can be useful for? Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list

Re: Enumerating k-segmentations of a sequence

2008-11-25 Thread bearophileHUGS
My version: from itertools import combinations as xcombinations from itertools import izip, islice def xpairwise(iterable): # docs and doctests removed return izip(iterable, islice(iterable, 1, None)) def segmentations(seq, k): for comb in xcombinations(range(1, len(seq)), k-1):

Re: Is the behavior expected?

2008-11-26 Thread bearophileHUGS
Alphones: > it is a little deferent from other script language. See also here: http://en.wikipedia.org/wiki/Dynamic_scope#Dynamic_scoping Python doesn't have such automatic closures, probably for performance reasons and/or maybe to keep its C implementation simpler (maybe other people here can gi

Re: hello from colombia

2008-11-26 Thread bearophileHUGS
fel: > they are starting a new project (insurance stuff) using Java, and I > just hate that eventually I'l be debugging someone-else's java code > how can I convince them that Python is better, and get them to re- > think their strategy? The choice of the language for a program isn't easy. Maintai

Re: how to construct a list of only one tuple

2008-11-27 Thread bearophileHUGS
TP: > >>> a=("1","2") > >>> b=[("3","4"),("5","6")] > >>> list(a)+b > ['1', '2', ('3', '4'), ('5', '6')] >>> a = ("1", "2") >>> b = [("3", "4"), ("5", "6")] >>> [a] + b [('1', '2'), ('3', '4'), ('5', '6')] Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list

Re: Exhaustive Unit Testing

2008-11-27 Thread bearophileHUGS
Emanuele D'Arrigo: >I can fragment the code of the original method into one public method and a >few private support methods.< Python also support nested functions, that you can put into your method. The problem is that often unit test functions aren't able to test nested functions. A question

Re: Exhaustive Unit Testing

2008-11-28 Thread bearophileHUGS
Terry Reedy: >The problem is that inner functions do not exist until the outer function is >called and the inner def is executed. And they cease to exist when the outer >function returns unless returned or associated with a global name or >collection.< OK. >A 'function' only needs to be nes

Re: optimization

2008-12-01 Thread bearophileHUGS
Robert Kern: >I only expect functions to be defined inside of functions if they are going to >use lexical scoping for some reason.< There are other reasons to nest functions. One of them is to represent logical nesting of some functionality. So you will find some exceptions to your self-created r

Re: Mathematica 7 compares to other languages

2008-12-01 Thread bearophileHUGS
Mathematica has some powerful symbolic processing capabilities, for example the integrals, etc. It also contains many powerful algorithms, often written in few lines of code. And its graphic capabilities are good. It also shows some surprising ways to integrate and manipulate data, for example here

Re: Mathematica 7 compares to other languages

2008-12-01 Thread bearophileHUGS
Jon Harrop: Is so wide cross-posting positive? > 4. Static type checking.< This is a Python newsgroup, you will find less lovers of static typing here :-) >Overall, Mathematica is a whopping 700,000 times slower!< Your Mathematica code is cute, but surely Mathematica isn't designed for that k

Re: RELEASED Python 3.0 final

2008-12-04 Thread bearophileHUGS
Gerhard Häring: > As you have probably guessed: nothing changed here. > Also see:http://www.python.org/dev/peps/pep-0666/ What? Do you mean it's possible to mix tabs and spaces still? Why? Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list

Re: generating a liste of characters

2008-12-05 Thread bearophileHUGS
Mark Tolonen: > Writing a helper function reduces code repetition and improves readability: >     def crange(startch,endch): >         '''Return a list of characters from startch to endch, inclusive.''' >         return [chr(c) for c in xrange(ord(startch),ord(endch)+1)] In Python ranges are open

Small problem with Psyco

2008-12-05 Thread bearophileHUGS
I post it here because I am using a Psyco version that was compiled by people here. I am using Python 2.6.1, on Win, with Psyco (1, 6, 0, 'final', 0). This minimized code: from psyco.classes import psyobj class Bar(psyobj): def __init__(self, baz): pass b = Bar(0) Produces: C:\...\te

Re: RELEASED Python 3.0 final

2008-12-05 Thread bearophileHUGS
Andreas Waldenburger: > Whenever has it been a pythonic ideal to "not allow" stuff? You get > warnings. Everything else is up to you. It's a strong source for bugs, especially for newbies, that I have hoped to see removed from Python3 (my first request of this was years ago). I was nearly sure to

Re: RELEASED Python 3.0 final

2008-12-05 Thread bearophileHUGS
Andreas Waldenburger: > My point is: If you mix tabs and spaces in a way that breaks code, > you'll find out pretty easily, because your program will not work. - Most newbies don't know that. - Sometimes it may produce wrong results. - And even if you are an expert when you go changing a little a

Re: slow Python 3.0 write performance?

2008-12-05 Thread bearophileHUGS
Christian Heimes: > I've fixed the read() slowness yesterday. You'll get the fix in the next > release of Python 3.0 in a couple of weeks. Thank you. Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list

Re: RELEASED Python 3.0 final

2008-12-05 Thread bearophileHUGS
Steven D'Aprano: >I think you're talking about mixed spaces/tabs in the one module.< Right. >My gut feeling is that you have to have a fairly unusual set of circumstances >before it causes actual bugs.< I don't mix tab and spaces in my code, and my editor is able to convert them, so after the

Re: Guido's new method definition idea

2008-12-06 Thread bearophileHUGS
Antoine De Groote: > Allowing "$" as a substitute for "self" wouldn't require this new syntax. > class C: > def method($, arg): > $.value = arg I think this (that is just sugar) may be a little better: class C: def method($, arg): $value = arg Or even this, combined with

Re: Guido's new method definition idea

2008-12-06 Thread bearophileHUGS
Steven D'Aprano: > If a line of code uses too many instance attributes to fit comfortably on > a line, spread it over two lines. There is no newline shortage, they are > a renewable resource. Splitting lines is generally possible, but sometimes it's not I want, for example to keep a formula whole.

Re: Guido's new method definition idea

2008-12-06 Thread bearophileHUGS
Erik Max Francis: > your precise proposal has > been brought up countless times on comp.lang.python And something tells me that it will keep coming up many more times in the following years too. Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list

Re: Is 3.0 worth breaking backward compatibility?

2008-12-07 Thread bearophileHUGS
walterbyrd: > I can not think of anything that is being changed that was really a "show > stopper" anyway.< I agree, but Python and its culture has a characteristic that not many other languages share: it tries to be a tidy language, to have one obvious way to do most things, it values readabilit

Re: Python for kids?

2008-12-07 Thread bearophileHUGS
On Dec 7, 9:13 pm, "Russ P." <[EMAIL PROTECTED]> wrote: > I have a 12-year-old son who spends too much time playing Xbox live > and watching silly YouTube videos. I would like to try to get him > interested in programming. Lot of people learn to program even before age of 12. But I think it's bett

Re: Python for kids?

2008-12-07 Thread bearophileHUGS
Luis M. González: >After he tried hard many approaches to solving the problem with his limited >knowledge,< You may even be surprised to see he/her/hir find a solution without your help :-) Or maybe you will see a different solution, this happens often in math and computer science, even basic on

Re: Public imports

2008-12-08 Thread bearophileHUGS
Márcio Faustino: > Does Python support public imports instead of the default private? > Something like D's "public import" (see 2.0/module.html>) or even Perl's "export_to_level". D type system has several big holes, and I am trying to push Walter to fix some of th

Re: Public imports

2008-12-08 Thread bearophileHUGS
> D type system has several big holes, I meant "D module system", of course. Sorry. Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list

Re: dictionary idiom needed

2008-12-11 Thread bearophileHUGS
Brandon: > I need an dictionary idiom whereby I can find all instances of > a given 'word' with any 'tagB', and then subdivide into all instances > of a given 'tagB'.  In both cases I would want the value as a count of > all instances found. If I have understood you well enough, I think you can do

Re: dictionary idiom needed

2008-12-11 Thread bearophileHUGS
bearophile: > you can do with a dict > that has the tuple ('word', 'tagB') as key, and as value has a > collections.defaultdict(int) that maps 'tagB' to its count. Where's 'tagA'? Probably I haven't understood your problem well enough. I need a better example of your data and what you need... Sor

Re: (Very Newbie) Problems defining a variable

2008-12-12 Thread bearophileHUGS
feba: >         if bank <= 0: >                 print("You're in the red!") >                 quit() >         elif bank >= 1 and bank <= : >                 rate = 0.0060 >         elif bank >= 1 and bank <= 24999: >                 rate = 0.0085 >         elif bank >= 25000 and bank <= 49

Re: Python is slow

2008-12-12 Thread bearophileHUGS
sturlamolden: > On a recent benchmark Java 6 -server beats C compiled by GCC 4.2.3 And > most of that magic comes from an implementation of a dynamically typed > language (Smalltalk). [...] > http://shootout.alioth.debian.org/u32q/benchmark.php?test=all〈=all That is indeed a nice result, JavaVM ha

Re: (Very Newbie) Problems defining a variable

2008-12-12 Thread bearophileHUGS
Kirk Strauser: > def get_rate(balance): >for threshold, rate in ((10, .0173), >(5, .0149), >(25000, .0124), >(1, .0085), >(0, .006)): >if balance > threshold: >

Re: Removing None objects from a sequence

2008-12-13 Thread bearophileHUGS
Steven D'Aprano: > The algorithm is unclear: try explaining > what you are doing in English, and see how difficult it is. That algorithm is a standard one, and quite clear. Any programmer worth his/her/hir salt has to be able to understand that. I agree that the idiom with the list comp (algorith

Shorter tracebacks

2008-12-13 Thread bearophileHUGS
When I write recursive code in Python I sometimes go past the maximum allowed stack depth, so I receive a really long traceback. The show of such traceback on my screen is very slow (despite a CPU able to perform billions of operations each second). So I think I'd like something to shorten them. I

Re: tricky nested list unpacking problem

2008-12-15 Thread bearophileHUGS
Arnaud Delobelle: > Here is a not thought out solution: >... I was waiting to answer because so far I have found a bad-looking solution only. Seeing there's only your solution, I show mine too. It seems similar to your one. def xflatten(seq): if isinstance(seq, list): stack = [iter(se

Re: Removing None objects from a sequence

2008-12-15 Thread bearophileHUGS
Scott David Daniels: > If you want to keep the original's method, but do it in a more Pythonic > way, I would suggest: > >      def deNone4(alist): >          j = 0 >          for val in alist: >              if val is not None: >                  alist[j] = val >                  j += 1 >        

Re: Generator slower than iterator?

2008-12-16 Thread bearophileHUGS
MRAB: > from collections import defaultdict > match_counter = defaultdict(int) > for line in fileinput.input(sys.argv[1:]): > ip = line.split()[0] > match_counter[ip] += 1 This can be a little faster still: match_counter = defaultdict(int) for line in fileinput.input(sys.argv[1:]):

Re: Does Python3 offer a FrozenDict?

2008-12-16 Thread bearophileHUGS
Johannes Bauer: > is there anything like a frozen dict in Python3, so I could do a > foo = { FrozenDict({"a" : "b"}): 3 } You can adapt this code to Python3 (and post a new recipe? It may be positive to create a new section of the Cookbook for Py3 only): http://code.activestate.com/recipes/414283/

Re: Does Python3 offer a FrozenDict?

2008-12-16 Thread bearophileHUGS
Paul Moore: > Moral - don't assume that all code needs to be rewritten for Python > 3.0 :-) In practice this time your moral is of little use: having a place that allows you to choose Py3 OR Py2 code is much better and tidier, helps you save time, helps you avoid wasting some time, etc. Bye, bear

Re: List comprehension in if clause of another list comprehension

2008-12-19 Thread bearophileHUGS
Peter Otten: > The problem is that list comprehensions do not introduce a new namespace. I think Python3 fixes this bug. Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list

Re: New Python 3.0 string formatting - really necessary?

2008-12-19 Thread bearophileHUGS
r: > I always thought of Python as an intuitive way to write C code.< C is a very low level language, not far from assembly, and often it's not intuitive at all. C string formatting is short and a flexible enough, but it's out of place in a language as high level as Python3. The new syntax allows

Re: Jarow-Winkler algorithm: Measuring similarity between strings

2008-12-20 Thread bearophileHUGS
John Machin: > This paper by Heikki Hyyrö is well worth > reading, and refers to a whole lot of previous work, including > Ukkonen's: > http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.6.2242 This is the site of the author: http://www.cs.uta.fi/~helmu/pubs/pubs.html There you can find updat

Re: New Python 3.0 string formatting - really necessary?

2008-12-20 Thread bearophileHUGS
walterbyrd: > As I understand it, that may have been true at one time. But, Ruby 1.9 > very significantly sped up the language. While Python has been made > slower, Ruby has been made much faster. I have already answered regarding Python3 in this thread. Regarding Ruby you are right, in computer s

Re: New Python 3.0 string formatting - really necessary?

2008-12-21 Thread bearophileHUGS
MRAB: > Interesting. The re module uses a form of bytecode. Not sure about the > relative cost of the dispatch code, though. I was talking about the main CPython VM, but the same ideas may be adapted for the RE engine too. Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list

Re: 64-bit / 128-bit data element type for array?

2008-12-22 Thread bearophileHUGS
akineko: > I need to handle binary files that contain 64-bit (or 128-bit in the > furture) unsigned int data. > Python's array seems not supporting unsigned int type beyond 32-bit > ('L'). I agree that it can be useful for the built-in array module to grow signed/unsigned 64 bit numbers. Numpy su

Re: iterating initalizations

2008-12-22 Thread bearophileHUGS
Chris Rebert: > It likely goes without saying, but you ought to read the fine tutorial as > well. I also suggest to fix the messed up indentations. Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list

2to3 used in the Shootout

2008-12-23 Thread bearophileHUGS
They have translated the Python benchmarks of the Shootout site from Py2 to Py3 using 2to3: http://shootout.alioth.debian.org/u32/benchmark.php?test=all&lang=python3 It shows some "performance bugs" of Python3 itself (especially regarding the binary-trees benchmark, that was unexpected by me), an

Re: Strategy for determing difference between 2 very large dictionaries

2008-12-24 Thread bearophileHUGS
Peter Otten: > >>> a = dict(a=1, b=2, c=3) > >>> b = dict(b=2, c=30, d=4) > >>> dict(set(a.iteritems()) ^ set(b.iteritems())) For larger sets this may be better, may avoid the creation of the second set: dict(set(a.iteritems()).symmetric_difference(b.iteritems())) Bye, bearophile -- http://mail.

Re: Exec inside a class method to call other class methods?

2008-12-25 Thread bearophileHUGS
Matthew Dubins: > def parse(self, data, data_type) >     exec "self.__parse_%s(data)" % data_type > For some reason, *it didn't work*. You can try defining this class attribute: data_types = set("nocall DOB gender Prematurity email languages phone cname pname address duedate".split()) And then a

Re: Syntax error for print

2008-12-25 Thread bearophileHUGS
On Dec 25, 7:53 pm, jsm4...@gmail.com wrote: > IDLE 3.0>>> print "hello" > > SyntaxError: invalid syntax (, line 1)>>> 3+3 > 6 > >>> var = 4 > >>> var = var*4 > >>> print var > > SyntaxError: invalid syntax (, line 1) > > > > Any idea on why I am getting this error. > I have just started learning p

Re: ruby -> python translator exists?

2008-12-26 Thread bearophileHUGS
rogerdpack: > Hi all.  My name is Roger. Hello Roger, my name is bearophile. > Anybody know of a Ruby -> Python translator at all?  I'm looking for a > way to have my Ruby code take advantage of the coolio speed of Psyco. I have never heard of such translator, so far. > Also question. Does p

Re: MemoryError when list append... plz help

2008-12-31 Thread bearophileHUGS
[BON]: > above sim is floating type. > s.append is totally coducted 60,494,500 times. > but this code raise MemoryError. > > My computer has 4G RAM. > i think it's enough. but it doesn't... Try creating it in a more clean way, here an array of doubles: >>> from array import array >>> a = array("d

Re: How to initialize an array with a large number of members ?

2008-12-31 Thread bearophileHUGS
MRAB: >  >>> # With a list >  >>> tally = array('H', [0] * 75) >  >>> >  >>> # With a generator >  >>> tally = array('H', (0 for i in range(75))) Time ago we have had a long discussion about this, the right way is: tally = array(someformat, [0]) * 75 (If you need to initialize it to something th

Re: similar words index?

2009-01-02 Thread bearophileHUGS
Jochen Schulz: > I implemented one approach in mspace.py: > http://well-adjusted.de/mspace.py/ > But beware that it is pure Python and not optimized for speed. You gain > quite a lot by having Psyco installed, though. Something similar, I haven't compared performance, Psyco helps a lot here too: h

Re: Is there a better algorithm?

2009-01-02 Thread bearophileHUGS
Fuzzyman: > for i in l: >    u = None >    if len(i) == 2: >       k, v = i >    else: >        k, u, v = i That's the best solution I have seen in this thread so far (but I suggest to improve indents and use better variable names). In programming it's generally better to follow the KISS principl

Re: Reverse order of bit in repeating seqence of byte string

2009-01-02 Thread bearophileHUGS
imageguy: > I receive the byte string with the following sequence 'bgrbgrbgrbgr' > and I would like to convert this to 'rbgrbgrbgrbg' > FWIW, the string is created using ctypes.create_string_buffer function MRAB: >  >>> a.tostring() > '210543876' That's not the required 'rbgrbgrbgrbg', but you ar

Re: Regular Expressions...

2009-01-07 Thread bearophileHUGS
Ken D'Ambrosio: > But the Python stuff simply isn't clicking for me. For people coming from Perl that want to perform some string processing with Python I suggest to learn first array/string slices and string methods. And to try to use the regular expressions as little as possible. Bye, bearophil

Re: Implementing file reading in C/Python

2009-01-09 Thread bearophileHUGS
Johannes Bauer, I was about to start writing a faster version. I think with some care and Psyco you can go about as 5 times slower than C or something like that. To do that you need to use almost the same code for the C version, with a list of 256 ints for the frequencies, not using max() but a ma

Re: how to get the thighest bit position in big integers?

2008-10-06 Thread bearophileHUGS
Mark Dickinson: > See alsohttp://bugs.python.org/issue3439 > where there's a proposal to expose the _PyLong_NumBits method. This > would give an O(1) solution. Sounds useful, I've used the gmpy.numdigits(x [,base]) few times. Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list

Re: Dict Comprehension ?

2008-10-06 Thread bearophileHUGS
Ernst-Ludwig Brust: > Given 2 Number-Lists say l0 and l1, > count the various positiv differences between the 2 lists >... > i wonder, if there is a way, to avoid the list dif Instead of creating the list (array) dif, you can create a lazy iterator. Then you can fed it to a set. Bye, bearophile -

Re: Array of dict or lists or ....?

2008-10-06 Thread bearophileHUGS
Tim Chase: >__repr__ = __str__ I don't know if that's a good practice. > try: >data.setdefault( > state, {}).setdefault( > county, {}).setdefault( > cls, Attendence(max_students)).accrue(enrolled) > except TooManyAttendants: I suggest to decompr

Re: Tuple parameter unpacking in 3.x

2008-10-07 Thread bearophileHUGS
Brett C.: > There are two things to realize about the tuple unpacking that acted > as motivation. One is supporting them in the compiler is a pain. > ... > Second, tuple unpacking in parameters breaks introspection horribly. Are there ways to re-implement from scratch similar native pattern- match

Re: Inefficient summing

2008-10-08 Thread bearophileHUGS
beginner: > I can of course use an old-fashioned loop. This is more readable, but > also more verbose. > What is the best way, I wonder? In such situation the old loop seems the best solution. Short code is good only when it doesn't make the code too much slow/difficult to understand. Keeping the

Re: split a list based on a predicate

2008-10-08 Thread bearophileHUGS
Rajanikanth Jammalamadaka: > Is there a functional way to do this? > I have an array [0,1,2,3,0,1,2,2,3] and I want the first chunk of > non-decreasing values from this array (eg: In this case I want > [0,1,2,3]) In Python sometimes the best way to write the code isn't functional, this is readable

Re: Inefficient summing

2008-10-09 Thread bearophileHUGS
FB: > def add_r( sums, r ): return sums[0]+r['F1'], sums[1]+r['F2'] > sum_f1, sum_f2 = reduce( add_r, rec, (0,0) ) > result = sum_f1/sum_f2 Until this feature vanishes I think it's better to use it (untested): add_r = lambda (a, b), r: (a + r['F1'], b + r['F2']) Bye, bearophile -- http://mail.py

Re: python 3: sorting with a comparison function

2008-10-09 Thread bearophileHUGS
Thomas Heller: > the 'cmp' argument seems to be gone. Can that be? Yes, that's a wonderful thing, because from the code I see around 99.9% of people see the cmp and just use it, totally ignoring the presence of the 'key' argument, that allows better and shorter solutions of the sorting problem. S

Re: default value in __init__

2008-10-10 Thread bearophileHUGS
Bruno Desthuilliers: > You mean : "to people that don't bother reading the FineManual *nor* > searching the newsgroup / ML archives ?" Are there ways to change how Python3 manages arguments and functions, to remove this antifeature of Python, avoiding this common mistake done by every newbie? I do

Re: default value in __init__

2008-10-10 Thread bearophileHUGS
Duncan Booth: > You can't just copy the default values on every call: you would still get > people confused by the semantics whether you did a shallow or deep copy or > as now no copy. I think I agree. > I don't think simply re-executing the default argument > expression on each call works eithe

Re: default value in __init__

2008-10-10 Thread bearophileHUGS
Chris Rebert: > The general idea been discussed ad-nauseum on the list several times > before, including just 2 months ago. See e.g.: Okay, it can't be fixed then. Bye and thank you, bearophile -- http://mail.python.org/mailman/listinfo/python-list

Re: python 3: sorting with a comparison function

2008-10-10 Thread bearophileHUGS
Kay Schluehr: > Sometimes it helps when people just make clear how they use technical > terms instead of invoking vague associations. And generally Python docs can enjoy growing few thousands examples... Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list

Re: regular expression question (re module)

2008-10-11 Thread bearophileHUGS
Faheem Mitha: > I need to match a string of the form > ... Please, show the code you have written so far, with your input-output examples included (as doctests, for example), and we can try to find ways to help you remove the bugs you have. Bye, bearophile -- http://mail.python.org/mailman/listin

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