Re: Bit substring search

2008-06-24 Thread bearophileHUGS
Kris Kennaway: > Unfortunately I didnt find anything else useful here yet :( I see, I'm sorry, I have found hachoir quite nice in the past. Maybe there's no really efficient way to do it with Python, but you can create a compiled extension, so you can see if it's fast enough for your purposes. To

Re: Python 3000 vs Perl 6

2008-06-24 Thread bearophileHUGS
Michele Simionato: Also consider the famous Clinger's maxim > “Programming languages should be designed not by piling feature > on top of feature, but by removing the weaknesses and restrictions > that make additional features appear necessary.” I'm relaxed, don't worry :-) I know that maxim, but

Re: Making code more efficient and effective

2008-06-26 Thread bearophileHUGS
Cédric Lucantis: > PAT = re.compile('^[ ]*(public|protected|private)[ ]+([a-zA-Z0-9_]+) > [ ]+([a-zA-Z0-9_]+)[ ]+\((.*)\).*$') > ... > It might be hard to read but will avoid a lot of obscure parsing code. You can use the VERBOSE mode, to add comments and split that RE into some lines. I think th

Re: list previous or following list elements

2008-06-26 Thread bearophileHUGS
Terry Reedy: > I believe > wordlist = open('words.txt','r').read().split('\n') > should give you the list in Python. This looks better (but it keeps the newlines too. Untested. Python 2.x): words = open("words.txt").readlines() for i, word in enumerate(words): if word.startswith("b"):

Re: re.search much slower then grep on some regular expressions

2008-07-05 Thread bearophileHUGS
Paddy: > You could argue that if the costly RE features are not used then maybe > simpler, faster algorithms should be automatically swapped in but Many Python implementations contains a TCL interpreter. TCL REs may be better than Python ones, so it can be interesting to benchmark the same RE

Re: Moving to functional programming

2008-07-11 Thread bearophileHUGS
James Fassett: > # the first Pythonic attempt using comprehensions > result_list = [x[0] for x in tuple_list] > > # the final functional way > [result_list, _] = zip(*tuple_list) > > I really like how Python allows me to do what I feel is the most > natural solution (for a seasoned procedural progr

Perfect hashing for Py

2008-07-11 Thread bearophileHUGS
Following links from this thread: http://groups.google.com/group/comp.lang.python/browse_thread/thread/179e1a45485ab36a# I have found this perfect hash (minimal too) implementation: http://burtleburtle.net/bob/hash/perfect.html I have already translated part of it to D, and it seems to work well

Re: palindrome function

2008-07-11 Thread bearophileHUGS
Denis Kasak: > spam = ['a', 'n', 'n', 'a'] > eggs = spam[:] > if spam.reverse() == eggs: > print "Palindrome" An alternative version: >>> txt = "anna" >>> txt == txt[::-1] True >>> txt = "annabella" >>> txt == txt[::-1] False Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-

Re: heapq question

2008-07-12 Thread bearophileHUGS
Giampaolo Rodola': > Even if I avoid to re-heapify() it seems that the first element > returned by heappop() is always the smaller one. Yes, the heappop() function keeps the heap invariant, so it will keep giving you the smallest item. > I'd like to understand if there are cases where > deleting

Re: Dictionary bidirectional

2008-07-13 Thread bearophileHUGS
bukzor: > You need to use two dictionaries. Here's a class that someone's > written that wraps it up into a single dict-like object for you: > http://www.faqts.com/knowledge_base/view.phtml/aid/4376 It contains code like: try: del self.data[item] except KeyError: pass Exceptions are usef

Re: Dictionary bidirectional

2008-07-14 Thread bearophileHUGS
Larry Bates: > The only case where it would be faster would be if most of the keys were NOT > in > the dictionary (rather odd use case). Otherwise I believe you will find the > first way quicker as the exceptions are infrequent. I have written a small benchmark: from random import shuffle def

Re: Modify a string's value

2008-07-15 Thread bearophileHUGS
Sebastian: > I've heard that a 'str' object is immutable. But is there *any* way to > modify a string's internal value? No, but you can use other kind of things: >>> s = "hello" >>> sl = list(s) >>> sl[1] = "a" >>> sl ['h', 'a', 'l', 'l', 'o'] >>> "".join(sl) 'hallo' >>> from array import array >

Re: Regular expression

2008-07-16 Thread bearophileHUGS
On Jul 16, 4:14 pm, Fredrik Lundh <[EMAIL PROTECTED]> wrote: > Beema shafreen wrote: > > How do I write a regular expression for this kind of sequences > > > >gi|158028609|gb|ABW08583.1| CG8385-PF, isoform F [Drosophila melanogaster] > > MGNVFANLFKGLFGKKEMRILMVGLDAAGKTTILYKLKLGEIVTTIPTIGFNVETVE >

Re: Getting a unknown word out of a list with no spaces

2008-07-17 Thread bearophileHUGS
On Jul 17, 9:50 am, Alexnb: > how can I test to see if the first char of a string is "<"? I suggest you to try the interactive shell: >>> "hello"[0] 'h' >>> "hello"[0] == "<" False >>> "hello"[0] == "h" True >>> "hello".startswith("h") True Bye, bearophile -- http://mail.python.org/mailman/list

Re: checking if an object IS in a list

2008-07-18 Thread bearophileHUGS
Peter Otten: > PS: Take these numbers with a grain of salt, they vary a lot between runs. Another possibility :-) from itertools import imap id(x) in imap(id, items) >If you want efficiency you should use a dictionary instead of the list anyway: I agree, but sometimes you have few items to look

MethodChain

2008-07-19 Thread bearophileHUGS
Found from Reddit, it's for e ECMA(Java)Script, but something similar may be useful for Python too: http://jsclass.jcoglan.com/methodchain.html http://blog.jcoglan.com/2008/07/16/where-did-all-my-code-go-using-ojay-chains-to-express-yourself-clearly/ Bye, bearophile -- http://mail.python.org/mail

Re: MethodChain

2008-07-19 Thread bearophileHUGS
Marc 'BlackJack' Rintsch: > What's called `MethodChain` there seems to be function composition in > functional languages. Maybe `functools` could grow a `compose()` function. To me it looks like a quite more "refined" thing, it's an object, it has some special methods, etc. I think it's not too m

Re: Not entirely serious: recursive lambda?

2008-07-20 Thread bearophileHUGS
Kay Schluehr: > Sure, use a fixed point combinator. I've just added this recipe: > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/576366 Does it work? Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list

Almost keywords

2008-07-21 Thread bearophileHUGS
Once in a while I feel free to write about less defined things, saying mostly wrong things. This post is mostly chat, if you aren't interested please ignore it. Python is fit enough for newbie programmers, but some of its characteristics can confuse them still, like the variables referenced by nam

Re: Execution speed question

2008-07-28 Thread bearophileHUGS
Suresh Pillai: > Or 4, since the order of my nodes doesn't matter: swap the node to be > deleted with the last node in the list and then remove the last node of > the list. This is the fastest to date, if using native structures, for > low number nodes being deleted per cycle (def if only deletin

Re: iterating "by twos"

2008-07-29 Thread bearophileHUGS
Something like this may be fast enough: >>> from itertools import izip >>> xpartition = lambda seq, n=2: izip(*(iter(seq),) * n) >>> xprimes = (x for x in xrange(2, 100) if all(x % i for i in xrange(2, x))) >>> list(xpartition(xprimes)) [(2, 3), (5, 7), (11, 13), (17, 19), (23, 29), (31, 37), (41,

Re: static variables in Python?

2008-07-29 Thread bearophileHUGS
kj: > OK, I guess that in Python the only way to do what I want to do > is with objects... There are other ways, like assigning the value out of the function, because Python functions too are objects: def iamslow(): return 100 def foo(x): return x + foo.y foo.y = iamslow() # slow computat

Re: Pointers/References in Python?

2008-07-30 Thread bearophileHUGS
boblatest: > I have a long list of memory-heavy objects that I would like to access > in differently sorted order. Let's say I'd like to have lists called > by_date or by_size that I can use to access the objects in the > specified order. Just create a new list with a different sorting order, for

Non Continuous Subsequences

2008-07-30 Thread bearophileHUGS
This post is not about practical stuff, so if you have little time, you may ignore it. This is a task of the rosettacode.org site: http://www.rosettacode.org/wiki/Non_Continuous_Subsequences A subsequence contains some subset of the elements of this sequence, in the same order. A continuous subse

Re: Reasoning behind 'self' parameter in classes?

2008-07-30 Thread bearophileHUGS
Brett g Porter: > Fredrik Lundh has written a very clear explanation of this > athttp://effbot.org/pyfaq/why-must-self-be-used-explicitly-in-method-de... Today lot of people know that Ruby exists, so such FAQ explanation must explain why Python doesn't use a shorter syntax like for example @foo

Re: Native Code vs. Python code for modules

2008-07-30 Thread bearophileHUGS
John Nagle: > Personally, I think the Shed Skin approach > is more promising. ShedSkin will probably have scaling problems: as the program size grows it may need too much time to infer all the types. The author has the strict policy of refusing any kind of type annotation, this make it unpractical

Re: Case tagging and python

2008-07-31 Thread bearophileHUGS
Fred Mangusta: > Could I use the join function to reform the string? You can write a function to split the words, for example taking in account the points too, etc. > And, regarding the casetest() function, what do you suggest to do? Python strings have isupper, islower, istitle methods, they m

Re: Non Continuous Subsequences

2008-07-31 Thread bearophileHUGS
Bruce Frederiksen: Your solution is a bit different from what I was thinking about (I was thinking about a generator function, with yield), but it works. This line: > return itertools.chain( >itertools.imap(lambda ys: x + ys, ncsub(xs, s + p1)), >nc

Re: simple problem with lists I am just forgetting

2008-07-31 Thread bearophileHUGS
Alexnb: > How can I test if the list item is empty without getting that exception? In Python such list cell isn't empty, it's absent. So you can use len(somelist) to see how much long the list is before accessing its items. Often you can iterate on the list with a for, so you don't need to care of

Re: Hobbyist - Python vs. other languages

2008-07-31 Thread bearophileHUGS
fprintf: > and yet they all end at the point where a person has enough > knowledge of the syntax, but not really enough to do anything. A programming language is a tool to solve problems, so first of all: do you have problems to solve? You can create some visualizations, some program with GUI, som

Re: Non Continuous Subsequences

2008-07-31 Thread bearophileHUGS
Kay Schluehr: >[Yes, I have too much time...] Thank you for your code. If you allow me to, I may put some code derived from yours back into the rosettacode.org site. >Here is an evil imperative, non-recursive generator: I like imperative, non-recursive code :-) If you count the number of item

Re: very large dictionary

2008-08-01 Thread bearophileHUGS
Simon Strobl: > I had a file bigrams.py with a content like below: > bigrams = { > ", djy" : 75 , > ", djz" : 57 , > ", djzoom" : 165 , > ", dk" : 28893 , > ", dk.au" : 854 , > ", dk.b." : 3668 , > ... > } > In another file I said: > from bigrams import bigrams Probably there's a limit in the modu

Re: proposal, change self. to .

2008-08-05 Thread bearophileHUGS
Heiko Wundram: > > how about changing the precious self. to . > > imagine > > self.update() > > .update() > > simple right? I suggest you to start using Ruby instead. Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list

Re: ANN: matplotlib-0.98.3 - plotting for python

2008-08-06 Thread bearophileHUGS
jdh2358: > delaunay triangularization [and more amazing things] I'm impressed, it's growing very well, congratulations, I use it now and then. I know people in University that use Python only/mostly because of matplotlib. Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list

Re: Psycho question

2008-08-06 Thread bearophileHUGS
David C. Ullrich: > Thanks. If I can get it installed and it works as advertised > this means I can finally (eventually) finish the process of > dumping MS Windows: the only reason I need it right now is for > the small number of Delphi programs I have for which straight > Python is really not adeq

Re: Parsing of a file

2008-08-06 Thread bearophileHUGS
Using something like PyParsing is probably better, but if you don't want to use it you may use something like this: raw_data = """ Field f29227: Ra=20:23:46.54 Dec=+67:30:00.0 MJD=53370.06797690 Frames 5 Set 1 Field f31448: Ra=20:24:58.13 Dec=+79:39:43.9 MJD=53370.06811620 Frames 5 Set 2 Field f31

Re: Psycho question

2008-08-06 Thread bearophileHUGS
Erik Max Francis: > If len(bytes) is large, you might want to use `xrange`, too. `range` > creates a list which is not really what you need. That's right for Python, but Psyco uses normal loops in both cases, you can time this code in the two situations: def foo1(n): count = 0 for i in r

Re: benchmark

2008-08-06 Thread bearophileHUGS
On Aug 7, 2:05 am, "Jack" <[EMAIL PROTECTED]> wrote: > I know one benchmark doesn't mean much but it's still disappointing to see > Python as one of the slowest languages in the test: > > http://blog.dhananjaynene.com/2008/07/performance-comparison-c-java-p... That Python code is bad, it contains

Re: Parsing of a file

2008-08-06 Thread bearophileHUGS
Paul McGuire: > This code creates a single dict for the input lines, keyed by id. > Each value contains elements labeled 'id', 'ra', and 'mjd'. ... > d = dict( > (rec.split()[1][:-1], > dict([('id',rec.split()[1][:-1])] + > [map(str.lower,f.split('=')) >

Re: benchmark

2008-08-07 Thread bearophileHUGS
jlist: > I think what makes more sense is to compare the code one most > typically writes. In my case, I always use range() and never use psyco. If you don't use Python 3 and your cycles can be long, then I suggest you to start using xrange a lot :-) (If you use Psyco you don't need xrange). M8R

Re: benchmark

2008-08-07 Thread bearophileHUGS
alex23: > Honestly, performance benchmarks seem to be the dick size comparison > of programming languages. I don't agree: - benchmarks can show you what language use for your purpose (because there are many languages, and a scientist has to choose the right tool for the job); - it can show where a

Re: Psycho question

2008-08-08 Thread bearophileHUGS
John Krukoff: > One possibility for the performance difference, is that as I understand > it the psyco developer has moved on to working on pypy, and probably > isn't interested in keeping psyco updated and optimized for new python > syntax. > Somebody correct me if I'm wrong, but last I heard ther

Re: at_most: search "dictionary" for less than or equal

2008-08-11 Thread bearophileHUGS
slais-www, a BK-tree maybe isn't right what you need but it may be enough: http://code.activestate.com/recipes/572156/ Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list

Re: benchmark

2008-08-11 Thread bearophileHUGS
Peter Otten: > In general I think that if you want to promote a particular coding style you > should pick an example where you can demonstrate actual benefits. That good thing is that Python 3 has only xrange (named range), so this discussion will be mostly over ;-) Bye, bearophile -- http://mail

Re: list question... unique values in all possible unique spots

2008-08-11 Thread bearophileHUGS
Mensanator: > Ever tried to iterate 403 septillion times? The OP is talking about formulas, like: X + Y * Z = W Where X, Y, Z, W distinct and in [1, 26], so you have C(26, 4) combinations that's way less than 26! >>> binomial(26, 4) 14950 So this can be solved with a xcombinations() generator.

Re: Replace Several Items

2008-08-13 Thread bearophileHUGS
gjhames: > What's the better way to do it? Better is a relative term. If with better you mean "faster" (in some circumstances), then the translate method is your friend, as you can see its second argument are the chars to be removed. As first argument you can use something like: "".join(map(chr, x

Inquisitive computing

2008-08-13 Thread bearophileHUGS
Python as a language almost fit for Inquisitive computing: http://www.americanscientist.org/issues/pub/2008/5/calculemus (I think Python is one of the best ones for such purpose). Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list

Re: Inquisitive computing

2008-08-13 Thread bearophileHUGS
David C. Ullrich: > If you look at the end of the article you see the author > agrees (I don't quite follow his complaint about not feeling > at home with the interactive mode, but it's funny to read about > how he uses Lisp but realizes he's not going to talk people > into that...) That well know

Re: Replace Several Items

2008-08-13 Thread bearophileHUGS
Fredrik Lundh: > suggested exercise: benchmark re.sub with literal replacement, re.sub > with callback (lambda m: ""), repeated replace, and repeated use of the form ... > on representative data. Please, add the translate() solution too I have suggested :-) Bye, bearophile -- http://mail.python.o

Re: Why prefer != over <> for Python 3.0?

2008-03-30 Thread bearophileHUGS
hdante: > it's already time that programmer editors > have input methods advanced enough for generating this: > if x ≠ 0: > ∀y ∈ s: > if y ≥ 0: f1(y) > else: f2(y) Take a look at Fortress language, by Sun. A free (slow) interpreter is already available. (Mathematica too allows

Re: who said python can't be obsfucated!?

2008-04-02 Thread bearophileHUGS
cokofree...: > def s(c):return[]if c==[]else s([_ for _ in c[1:]if _ _ in c[1:]if _>=c[0]]) That QuickSort can be written as a lambda too: s=lambda l:[]if l==[]else s([x for x in l[1:]if x=l[0]]) Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list

Re: Efficient way of testing for substring being one of a set?

2008-04-03 Thread bearophileHUGS
Dennis Benzinger: > You could use the Aho-Corasick algorithm Aho-Corasick_algorithm>. > I don't know if there's a Python implementation yet. http://hkn.eecs.berkeley.edu/~dyoo/python/ahocorasick/ Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-l

Re: Data structure recommendation?

2008-04-08 Thread bearophileHUGS
Jochen Schulz: > This solution may be more than you actually need, but I implemented two > metric space indexes which would do what you want (and I wanted to plug > it anyway :)): Please plug such good things. It seems the Python community is an endless source of interesting modules I didn't know

Re: Data structure recommendation?

2008-04-08 Thread bearophileHUGS
Few more notes on the code: You may use the @property in such situations (or you may just use attributes, dropping the property). Note that Python doesn't inline functions calls like Java HotSpot does quite often. def __children(self): raise NotImplementedError() children = propert

Re: Data structure recommendation?

2008-04-08 Thread bearophileHUGS
More bits from your code: neighbours = list() ==> neighbours = [] If you have a recent enough version of Python you can use: candidate_is_neighbour = any(distance < n[1] for n in neighbours) Instead of: candidate_is_neighbour = bool([1 for n in neighbours if distance < n[1]]) It's shorter & simp

Re: Basic optimization of python.

2008-04-09 Thread bearophileHUGS
ShenLei: > t = self.a.b > t.c = ... > t.d = ... > .vs. > self.a.b.c = ... > self.a.b.d = ... > which one is more effective? Since each dot invokes a hash table lookup, it > may be time consuming. If the compiler can do expression folding, then no > manual folding is needed. Removing dots creatin

Re: Graphs in Python

2008-04-10 Thread bearophileHUGS
Sanhita Mallick>where can I find more in depth info about how to express graphs in python, and how to use them in a code?< You can look here: https://networkx.lanl.gov/wiki My version: http://sourceforge.net/projects/pynetwork/ Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-l

Re: sampling without replacement

2008-04-18 Thread bearophileHUGS
Alexy>But in Python it's very slow...< I'm the first one to say that CPython is slow, but almost any language is slow if you use such wrong algorithms like you do. There are many ways to solve your problem efficiently, one of such ways, among the simpler ones is to to not modify the original list:

Re: Data structure recommendation?

2008-04-18 Thread bearophileHUGS
Jochen Schulz: > Could you please send me an email with an existing From: address? I > tried to reply to you but apparently your From: is forged. Sorry for the delay, I'll send you an email. In the meantime I have created a fast BK-tree implementation for Psyco, on my PC it's about 26+ times faste

sys.maxint in Python 3

2008-04-21 Thread bearophileHUGS
In some algorithms a sentinel value may be useful, so for Python 3.x sys.maxint may be replaced by an improvement of the following infinite and neginfinite singleton objects: class Infinite(object): def __repr__(self): return "infinite" def __cmp__(self, other): if other is infinit

Light slices + COW

2008-05-03 Thread bearophileHUGS
Sometimes different languages suggests me ways to cross-pollinate them. (Note: probably someone has already suggested (and even implemented) the following ideas, but I like to know why they aren't fit for Python). Python generators now allow me to package some code patterns common in my code, t

Re: Light slices + COW

2008-05-04 Thread bearophileHUGS
David: > What do you mean by best possible? Most efficient? Most readable? What's a good wine? It's not easy to define what's "good/best". In such context it's a complex balance of correct, short, fast and readable (and more, because you need to define a context. This context refers to Psyco too)

Re: word shifts

2008-05-04 Thread bearophileHUGS
George Sakkis: > A faster algorithm is to create a 'key' for each word, defined as the > tuple of ord differences (modulo 26) of consecutive characters. Very nice solution, it uses the same strategy used to find anagrams, where keys are "".join(sorted(word)) Such general strategy to look for a pos

Re: Suggestion for improved ImportError message

2008-08-15 Thread bearophileHUGS
Lie: >I'm not sure there are any reason to test for failed import in doctest)< I have code that uses numpy if available, otherwise uses slower normal Python code. Inside the doctests I'd like to test both situations... Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list

Re: like a "for loop" for a string

2008-08-17 Thread bearophileHUGS
Wojtek Walczak: > >>> somestr = "string1 string2 string3" > >>> for i in somestr.split(): > > ...print i > ... > string1 > string2 > string3 I'm waiting for a str.xsplit still :-) If I write and submit a C implementation of xsplit how many chances do I have to see it included into Python? :-)

Re: like a "for loop" for a string

2008-08-17 Thread bearophileHUGS
Eric Wertman: > So what exactly does that do? Returns a generator, instead of a list? Allows you to iterate on the parts in a lazy way, without creating the whole list of the pieces. The arguments are the same of str.split(). Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list

Re: like a "for loop" for a string

2008-08-17 Thread bearophileHUGS
MRAB: > If it was introduced into Python v3.x then wouldn't it have to be > called str.split in order to be consistent with xrange -> range? :-) xsplit may be a name fit for Python 2.6/2.7. Regarding Python 3.0 you may be right, but then when you want the list of parts you have to do: list(somest

Re: like a "for loop" for a string

2008-08-18 Thread bearophileHUGS
Fredrik Lundh: > or you could use re.finditer, which can be used for a lot more than just > splitting. Having implemented some of them (and even invented algorithms like a new substring search, that I have appreciated) you know that string methods are simpler ways to efficiently perform specialize

Re: Is my thinking Pythonic?

2008-08-21 Thread bearophileHUGS
Hussein B: > class Car: > def setspeed(self, speed): > self.speed = speed > def setbrand(self, brand): > self.brand = brand You can also learn the _attribute and __attribute conventions. In Python getter/setters are used less often, you can remove those two setters and just access th

Re: Is my thinking Pythonic?

2008-08-21 Thread bearophileHUGS
Craig Allen: > class Car: >speed = None >brand = None > >def __init__(): > self.speed = defaultspeed #alternately, and more commonly, get > this speed as a initializer argument > self.brand = defaultbrand > > That solves the issue of being able to "see" all the members of a

Re: need help using enumerate ??

2008-08-22 Thread bearophileHUGS
Chris: > """Iterate over your input file, split the line into it's component > parts >and then lookup if the first element 'command' is contained in the >replacement data and if so change the data. >If you want all input to be saved into your output file, just > dedent >the 'outFile

dict views implementation

2008-08-22 Thread bearophileHUGS
Where can I find an explanation of how the new light dict views of Python 3 are implemented (or what's the name of the C source file to look inside for their implementation)? Thank you, bearophile -- http://mail.python.org/mailman/listinfo/python-list

Re: Should Python raise a warning for mutable default arguments?

2008-08-22 Thread bearophileHUGS
DrScheme is an implementation of Scheme that is very newbie-friendly. It has several limited sub-languages, etc. So maybe a command line option can be added to Python3 ( - newbie ? :-) ) that just switches on similar warnings, to help newbies (in schools, where there's a teacher that encourages to

Re: Generators can only yield ints?

2008-08-22 Thread bearophileHUGS
defn noob: > Any way to get around this? Your code is wrong, this is one of the correct versions: from itertools import izip def letters(): lower = xrange(ord('a'), ord('z')+1) upper = xrange(ord('A'), ord('Z')+1) for lc, uc in izip(lower, upper): yield chr(lc) yield

Re: Equivalents of Ruby's "!" methods?

2008-08-25 Thread bearophileHUGS
Simon Mullis: > h = { "1" : "a\r", "2" : "b\n" } > I have the option of an in-place method: > h.each_value { |v| val.strip! } This in-place version may be the closer code for Python 2.x: d = {"1": "a\r", "2": "b\n"} d.update((k, v.strip()) for k, v in d.iteritems()) You may also want to use v.rs

Re: Replace reduce with listcomprehension?

2008-08-25 Thread bearophileHUGS
Luis M. González, citing Guido: > A. I'm not killing reduce() because I hate functional programming; I'm > killing it because almost all code using reduce() is less readable > than the same thing written out using a for loop and an accumulator > variable. (So reduce is now in itertools). Try to pr

Re: why in returns values for array and keys for dictionary

2008-08-26 Thread bearophileHUGS
"++imanshu: > Wouldn't it be nicer to have 'in' return values (or keys) for both > arrays and dictionaries. Arrays and Dictionaries looked so similar in > Python until I learned this difference. D language works like you say, and it's awful. With a key you can find its value, but given only th

Re: What's your first choice if you have to write a C module for python?

2008-08-26 Thread bearophileHUGS
[EMAIL PROTECTED]: > I read this interesting post comparing Boost.Python with Pyd: > http://pyd.dsource.org/vsboost.html > What's your opinion about it? > What's your first choice when you have write a C/C++ module for Python? That's not exactly a post. Pyd works well enough, it's easy to use and

Re: Identifying the start of good data in a list

2008-08-26 Thread bearophileHUGS
First solutions I have found, not much tested beside the few doctests: from itertools import islice def start_good1(alist, good_ones=4): """ Maybe more efficient for Python >>> start_good = start_good1 >>> start_good([0, 0, 1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) 4 >>> start_go

Re: Identifying the start of good data in a list

2008-08-26 Thread bearophileHUGS
Sorry, in the Psyco version replace this line: for i, el in enumerate(alist): With: for i in xrange(len(alist)): because Psyco doesn't digest enumerate well. Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list

Re: How to update value in dictionary?

2008-08-27 Thread bearophileHUGS
ssecorp wrote: > dict.update({"a":1}) SETS the dict item "a" 's value to 1. That works but it's not the right way to do that, use this: d["a"] = 1 Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list

Re: Identifying the start of good data in a list

2008-08-27 Thread bearophileHUGS
George Sakkis: > This seems the most efficient so far for arbitrary iterables. This one probably scores well with Psyco ;-) def start_good3(seq, good_ones=4): """ >>> start_good = start_good3 >>> start_good([0, 0, 1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) 4 >>> start_good([]) -1

Re: Problem with list.insert

2008-08-28 Thread bearophileHUGS
Subhabrata, it's very difficult for me to understand what your short program has to do, or what you say. I think that formatting and code style are important. So I suggest you to give meaningful names to all your variable names, to remove unused variables (like n), to add blank likes here and ther

Re: file data to list

2008-08-28 Thread bearophileHUGS
Anish Chapagain: > cnt0001a 29000 xretya 01 > cnt0002a 29850 brishal 02 > cnt0003a 31250 kristal 03 > from here, I need to copy data 29000, 29850, 31250 into a single list > and > 01, 02, 03 to another so as to plot graph using these value. This may offer you a starting point: >>> line = "cnt0003

Re: Using class-attribute as key to sort?

2008-08-29 Thread bearophileHUGS
cnb: > In median grade, can I sort on Review-grade somehow? operator.attrgetter may help. Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list

Re: Advice on the style to use in imports

2008-08-30 Thread bearophileHUGS
Marco Bizzarri: > I'm just confused because PEP8 seems to suggest that the from module > import Class style is acceptable; is there a big "if you know what are > doing" before, which I'm unable to see? from somemodule import somename is often acceptable IHMO, but there are some things to consider

Re: Most pythonic way of weighted random selection

2008-08-30 Thread bearophileHUGS
Manuel Ebert, this may be related/useful: http://code.activestate.com/recipes/498229/ Note that numpy has a bisection method/function that are probably quite faster. Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list

Py 2.6 changes

2008-09-01 Thread bearophileHUGS
I have just re-read the list of changes in Python 2.6, it's huge, there are tons of changes and improvements, I'm really impressed: http://docs.python.org/dev/whatsnew/2.6.html I'll need many days to learn all those changes! I can see it fixes several of the missing things/problems I have found in

Re: Py 2.6 changes

2008-09-01 Thread bearophileHUGS
Steven D'Aprano: > productory() -- I don't know that function, and googling mostly comes up > with retail product searches. Do you mean product(), Darn my English, you are right, sorry, I meant a product() of course :-) Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list

Re: Numeric literal syntax (was: Py 2.6 changes)

2008-09-01 Thread bearophileHUGS
Ben Finney: > I don't see any good reason (other than your familiarity with the D > language) to use underscores for this purpose, and much more reason > (readability, consistency, fewer arbitrary differences in syntax, > perhaps simpler implementation) to use whitespace just as with string > liter

Re: Using NLTK in Java

2008-09-02 Thread bearophileHUGS
On Sep 1, 12:30 pm, [EMAIL PROTECTED]: >in Jython (which is assumed to replace Python), I don't think so. Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list

Re: Renumbering

2008-09-02 Thread bearophileHUGS
Francesco Pietra, few notes: - In Python and C item numbering generally starts from 0, so you talk about column 0, 1, etc. - You can also use the Italian Python newsgroup if know Italian. - The number of lines with a particular number doesn't seem important to solve your problem. - You don't need t

Re: Renumbering

2008-09-02 Thread bearophileHUGS
John Machin: > Is this homework? Have you put any effort into trying to write a script > yourself? Etc etc etc You are right, I am sorry -.- Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list

Re: converting a sed / grep / awk / . . . bash pipe line into python

2008-09-03 Thread bearophileHUGS
Roy Smith: > No reason to limit how many splits get done if you're > explicitly going to slice the first two. You are probably right for this problem, because most lines are 2 items long, but in scripts that have to process lines potentially composed of many parts, setting a max number of parts sp

max(), sum(), next()

2008-09-03 Thread bearophileHUGS
Empty Python lists [] don't know the type of the items it will contain, so this sounds strange: >>> sum([]) 0 Because that [] may be an empty sequence of someobject: >>> sum(s for s in ["a", "b"] if len(s) > 2) 0 In a statically typed language in that situation you may answer the initializer va

Re: Numeric literal syntax

2008-09-03 Thread bearophileHUGS
Ben Finney: > … for numbers with many digits the digits may be divided into > groups of three by a thin space, in order to facilitate reading. > Neither dots nor commas are inserted in the spaces between groups > of three. > http://www.bipm.org/en/si/si_brochure/chapter5/5-3-2.h

Re: converting a sed / grep / awk / . . . bash pipe line into python

2008-09-03 Thread bearophileHUGS
Roy Smith: > But, along those lines, I've often thought that split() needed a way to not > just limit the number of splits, but to also throw away the extra stuff. > Getting the first N fields of a string is something I've done often enough > that refactoring the slicing operation right into the sp

Re: Python on JavaScript VM's (such as V8)?

2008-09-03 Thread bearophileHUGS
Berco Beute: > I wonder what it would take to implement Python in JavaScript so it > can run on those fancy new JavaScript VM's such as Chrome's V8 or > Firefox' tracemonkey. Much the same as Python implementations in C# > (IronPython) and Java (Jython). It would certainly bring back the fun > in w

Re: max(), sum(), next()

2008-09-03 Thread bearophileHUGS
Laszlo Nagy: > I believe that there have been excessive discussions about this > decision, and the current implementation is very good, if not the best. I see. But note that my post is mostly about the max()/min() functions :-) Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-lis

Re: Numeric literal syntax

2008-09-03 Thread bearophileHUGS
Alexander Schmolck: > It also reads well, unlike the underscore > which is visually obstrusive and ugly (compare 123'456'890 to 123_456_789). I like that enough, in my language that symbol is indeed the standard one to separate thousands, in large numbers. It's light, looks natural, and as you say

<    6   7   8   9   10   11   12   >