Re: Is this possible in Python?
Paul Rubin wrote: > [EMAIL PROTECTED] writes: >> assert magic_function(3+4)=="3+4" >> assert magic_function([i for i in range(10)])=="i for i in range(10)]" >> >> It is not trivial at all and might require some bytecode hacking that i >> am unable to do myself BUT you are the experts ;-) > > Guhhh... you'd want to use the traceback system and reach back into > the source code to get and parse the statement that called the magic > function, sort of like a debugger does. That's one way > I don't think messing with > the bytecode would help. Well, the following package http://packages.debian.org/stable/python/decompyle might permit something like that. -- http://mail.python.org/mailman/listinfo/python-list
Re: Programming challenge: wildcard exclusion in cartesian products
sa wrote: > in k: > > cp:{[c;n;p]+(n#c)_vs(!_ c^n)_dvl,/{2_sv+(,/,/:\:)/(),/:@[x;&x=-1;:[;!c]]}'p} That one goes a long way as a proof of eg evolution theory, you know, monkeys reproducing shakespeare with a typewriter k-board and all that :) > > examples: > > cp[2;3;,0 -1 1] > (0 0 0 > 0 1 0 > 1 0 0 > 1 0 1 > 1 1 0 > 1 1 1) > > cp[2;3;(0 -1 1;1 -1 0)] > (0 0 0 > 0 1 0 > 1 0 1 > 1 1 1) > > cp[2;3;(0 -1 1;1 -1 1)] > (0 0 0 > 0 1 0 > 1 0 0 > 1 1 0) > > arguments of cp: > > c = cardinality of the input set > n = power > p = list of patterns (-1 = wildcard) > > the algorithm directly computes the target set. in other words, > it does not generate the set, then filter the matches from the > target. > > modifying cp to accept s instead of the cardinality of s, > patterns expressed in terms of elements of s, &c. adds nothing > of interest to the problem. -- http://mail.python.org/mailman/listinfo/python-list
Re: What's The Best Editor for python
Wildemar Wildenburger wrote: > just to bloat this thread some more: > > Am I the only one using jEdit? I've yet to find better for developing in jython -- http://mail.python.org/mailman/listinfo/python-list
Re: "The World's Most Maintainable Programming Language"
John Salerno wrote: > There is an article on oreilly.net's OnLamp site called "The World's > Most Maintainable Programming Language" > (http://www.oreillynet.com/onlamp/blog/2006/03/the_worlds_most_maintainable_p.html). > > > > It's not about a specific language, but about the qualities that would > make up the title language (learnability, consistency, simplicity, > power, enforcing good programming practices). I thought this might be of > interest to some of you, and I thought I'd point out the two places > where Python was mentioned: > > from Part 4, Power: > "Of course (second point), a language that requires users to extend it > to be productive has already failed, unless it can enforce that there is > one obvious solution to any problem and autonomously subsume the first > working solution into the core language or library. Python is a good > example of this practice. There is a strong polycultural subcommunity in > the world of free and open source, and the members of this group > consider the lack of competing projects in Python (one XML parser, one > logging library, one networking toolkit) to be counterintuitive and even > counter to the goal of language progress. They’re wrong; this is > actually a strong force for cohesion in the language and community, > where the correct answer to a novice’s question of “How can I parse > XML?”, “How can I publish a database-driven web site?”, or even “How can > I integrate the legacy system of an acquired company from a different > industry with our existing legacy system?” (to prove that this principle > does not only apply to small or toy problems) is usually “Someone else > has already implemented the correct solution to that problem — it is > part of the standard library.”" xml templates ? ORM ? -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Decompilers?
Peter Hansen wrote: > flamesrock wrote: >> Hi, >> >> Are there any good decompilers for python? > > Decompyle can manage any version from 1.5 up to 2.3.3. I was disappointed when I started to play with decompyle for python 2.3 to observe that it failed on non-trivial list comprehensions. -- http://mail.python.org/mailman/listinfo/python-list
small challenge : limit((x+1)**0.5 for x in itially(2))
generators challenge define "limit" and "itially" so that limit(foo(x) for x in itially(bar)) works out the same as limit2(foo,bar) with def limit2(foo,bar) : bar1 = foo(bar) while bar != bar1 : bar1,bar = foo(bar),bar1 return bar Note : be careful with your choice of foo and bar, to prevent infinite loops when the iterated value won't converge. To think of it, perhaps "abs(bar-bar1)>epsilon" would be more appropriate than "bar != bar1" in the above loop - I can imagine roundoff errors leading to tiny oscillations in the least significant bits of an otherwise convergent computation. Best, az -- http://mail.python.org/mailman/listinfo/python-list
Re: small challenge : limit((x+1)**0.5 for x in itially(2))
Azolex wrote: > generators challenge > > > define "limit" and "itially" > > so that > > limit(foo(x) for x in itially(bar)) > > works out the same as > > limit2(foo,bar) > > with > > def limit2(foo,bar) : > bar1 = foo(bar) > while bar != bar1 : > bar1,bar = foo(bar),bar1 oops, this should read bar1,bar = foo(bar1),bar1 sorry > return bar > > > Note : be careful with your choice of foo and bar, to prevent infinite > loops when the iterated value won't converge. > > To think of it, perhaps "abs(bar-bar1)>epsilon" would be more > appropriate than "bar != bar1" in the above loop - I can imagine > roundoff errors leading to tiny oscillations in the least significant > bits of an otherwise convergent computation. > > Best, az -- http://mail.python.org/mailman/listinfo/python-list
Re: small challenge : fixpoint((x+1)**0.5 for x in itially(2))
Paul McGuire wrote: > Howzis? > > -- Paul > > > class Bag: > pass > data = Bag() > data.x = None > > def itially(bar): > if data.x is None: > data.x = bar > while 1: > yield data.x > > def limit(z): > eps = 1e-10 > done = False > z2 = z.next() > z1 = z2 + 1 > while abs(z2-z1) > eps: > data.x = z2 > z2, z1 = z.next(),z2 > print "dbg>",z1,z2 > return z1 > > print limit( x**0.5 for x in itially(2) ) It fits the bill, I'd say. Below is my simplest solution, renaming "limit" to a more appropriate "fixpoint". Like yours, this solution as concurrency issues. Note that (z+1)**0.5 has a more interesting attractive fixpoint that z**0.5, namely the golden mean 1.618... def itially(z) : echoback.z = z while True : yield echoback.z def echoback(gen) : while True : echoback.z = gen.next() yield echoback.z def fixpoint(gen) : z = echoback(gen).next while True : if z()==z() : return z() print fixpoint((z+1)**0.5 for z in itially(2)) -- http://mail.python.org/mailman/listinfo/python-list
Re: Counting all permutations of a substring
[counting all (possibly overlapping) occurences of a substring in a string] def count_subs(s,subs,pos=0) : pos = 1+s.find(subs,pos) return pos and 1+count_subs(s,subs,pos) or equivalently def count_subs(s,subs) pos,cnt = 0,0 while True : pos = 1+s.find(subs,pos) if not pos : return cnt cnt += 1 or even (using the helper functions of my last post in the "small challenge" thread) def count_subs(s,subs) : cnt = 0 for pos1 in echoback(1+s.find(subs,pos) for pos in itially(0)) : if not pos1 : return cnt cnt += 1 (I've minimally tested only the first version) -- http://mail.python.org/mailman/listinfo/python-list
Re: efficiency of range() and xrange() in for loops
Steve R. Hastings wrote: > On Thu, 06 Apr 2006 09:08:45 +1000, Steven D'Aprano wrote: >> Yes, the above example is a good use case for xrange. Did you think that >> anyone denied that there were good cases for it? > > I am now officially sorry for starting this thread. Don't. It's quite funny, thanks. -- http://mail.python.org/mailman/listinfo/python-list
Re: how to convert string
a couple more exotic variations print (10 * "%s ") % tuple(range(10)) print filter(lambda x : x not in "[,]",str(range(10))) -- http://mail.python.org/mailman/listinfo/python-list
Re: efficiency of range() and xrange() in for loops
Steve R. Hastings wrote: > On Thu, 06 Apr 2006 02:33:16 +0200, Azolex wrote: >> Don't. It's quite funny, thanks. > > I guess I should laugh. :-/ > > > When you read my original articles, did *you* think I was proposing that > range() be changed to always return an iterator? I thought what I wrote > was pretty clear... I just re-read your original post, and in fact this appears to have been your drift with "is there any chance this optimization could be added ?". Anyway that wasn't really controversial (since indeed, as was noted by John Salerno who first replied to you, it is slated for py3k - and with good reason). -- http://mail.python.org/mailman/listinfo/python-list
Re: Counting all permutations of a substring
I wrote: > [counting all (possibly overlapping) occurences of a substring in a string] > > def count_subs(s,subs,pos=0) : > pos = 1+s.find(subs,pos) > return pos and 1+count_subs(s,subs,pos) > . now to push lisp-style to the extreme, a recursive one-liner solution with presumably better stack behavior (assuming proper tail-recursion elimination, which I doubt is the case in Python). Python 2.5a1 (r25a1:43589, Apr 5 2006, 10:36:43) [MSC v.1310 32 bit (Intel)] on win32 ... >>> cnt_ss = lambda s,ss,p=-1,n=-1 : n if n>p else >>> cnt_ss(s,ss,s.find(ss,p+1),n+1) >>> cnt_ss("AABBAAABABAAA","AA") 5 >>> cnt_ss("foolish","bar") 0 >>> cnt_ss("banana split","ana") 2 note though that the first solution beats this one on token count: 37 vs 42 -- http://mail.python.org/mailman/listinfo/python-list
Re: pre-PEP: The create statement
Michele Simionato wrote: > Steven Bethard wrote: >> The PEP is based on a suggestion [1]_ from Michele Simionato on the >> python-dev list. > > True, but I would also mention that the idea of the 'create' keyword > come from > Nick Coghlan: > > http://mail.python.org/pipermail/python-dev/2005-October/057531.html > > >Michele Simionato > I'd advocate for the shortest possible keyword, and - maybe because English is not my native language - I'd thus prefer "make" if any is really required. -- http://mail.python.org/mailman/listinfo/python-list
xml <-> python Re: pre-PEP: The create statement
Steven Bethard wrote: ... > > Optional Extensions > === > > Remove the create keyword > - > > It might be possible to remove the create keyword so that such > statements would begin with the callable being called, e.g.: > > module mod: > def f1(): > ... > def f2(): > ... > > interface C(...): as someone else noted, this is not the ideal example > ... > > However, this would probably add some complexity in the grammar and > so far I (Steven Bethard) have not been able to implement the feature > without the keyword. Well, I can't pronounce myself on the technical difficulties, but I'd like to point out that the proposal of the pep (especially without keyword I'd say) offers part of what would be needed to endow python with a standard bidirectional source-to-source transform to/fro xml. But it might as well miss the opportunity... I feel the python grammar offers more readable solutions (or near-solutions) to the problems solved by the cumbersome grammar of xml. So whenever I need to work with xml source or templates, I dream of a reversible transformer that would allow me to work with a transparent "mock-python" rendering of my xml file - it would replace closing tags with indentations, attributes with keyword parameters syntax, cdatas with triple quotes and perhaps xmlns with import statements - doing away with all the unnecessary cruft. Symmetrically, I feel a (family of) standard xml rendition(s) of python source would be quite useful. For one, it would facilitate access of python source to vehicles designed for xml. For two, it would provide python with an equivalent to lisp s-expression syntax. To illustrate : imagine processing python source code using xslt over an xml representation of python source with the relevant xslt itself expressed in transparent python source. So what I'd ideally want (and also to attract "foreign" programmers to python) is to modify python syntax and semantics conservatively to eg "xpython" that would make the following possible : (a) given arbitrary "xpython" source code, there is a clearly obvious way to express in xml a superficial parse of the code (ie a parse of statement-level syntax). (b) given arbitrary xml, there is a clearly obvious way to transform it to mimetic "xpython" source code. (c) the transforms are mutual inverses. (d) running any "xpython" obtained from arbitrary xml will reconstruct the original xml. Similar wish, anyone ? As relates to the pre-pep : +1 for adding this general style of statement, -0.5 on requiring a keyword, -1 on choosing a *verb* keyword that forces to the imperative interpretation of the code (since I'd want "xpython" to function as well as a declarative language equivalent to xml) -0.8 on the parameter syntax that restricts to positional parameters while leaving out keyword arguments Cheers. -- http://mail.python.org/mailman/listinfo/python-list
Re: how to make a generator use the last yielded value when it regains control
just couldn't help taking the bait... def morris(seed) : """ >>> m = morris('3447221') >>> m.next() '1324172211' >>> m.next() '1113121411172221' >>> m.next() '31131112111431173211' """ assert isinstance(seed,basestring) and seed.isdigit(),"bad seed" def itially(z) : feedback.z = z while True : yield feedback.z def feedback(gen) : while True : feedback.z = gen.next() yield feedback.z def morrisify(number) : from itertools import groupby for digit,sequence in groupby(number) : yield str(len(tuple(sequence))) yield digit return feedback(''.join(morrisify(number)) for number in itially(seed)) -- http://mail.python.org/mailman/listinfo/python-list
Re: "The World's Most Maintainable Programming Language"
Michael Yanowitz wrote: > > At-least Pythetic isn't a word (yet). > :))) "now that's quite pythetic !" hmmm, clearly that word could become damaging to python, so I suggest the best course is to preventively focus the meaning in a way that prevents the danger, by providing canonical examples of, hem, pythos, that will direct the contempt away from your beloved programming language. My contribution (2001) : filter(lambda W : W not in "ILLITERATE","BULLSHIT") -- http://mail.python.org/mailman/listinfo/python-list
Re: how to make a generator use the last yielded value when it regains control
Lonnie Princehouse wrote: > Here's my take on the thing. It only prints one term, though. > > http://www.magicpeacefarm.com/lonnie/code/morris.py.html > > (a bit too long to post) > excerpt : def morris(seed, n): """...""" if n == 1: return seed else: return length_encode(morris(seed,n-1)) What's wrong with the following ? def morris(seed,n) : """...""" for k in xrange(n-1) : seed=length_encode(seed) return seed or even def morris(seed,n) : return reduce(lambda x,y:y(x),n*[length_encode],seed) I'd defend using recursion when it allows a more concise expression of an algorithm, but not in other cases. Mmmhhh, btw, strangely, it looks like a hole in the library that you can't write eg morris= lambda seed,n: reduce(operator.__rcall__,n*[length_encode],seed) -- http://mail.python.org/mailman/listinfo/python-list
Re: Characters contain themselves?
WENDUM Denis 47.76.11 (agent) wrote: > > While testing recursive algoritms dealing with generic lists I stumbled > on infinite loops which were triggered by the fact that (at least for my > version of Pyton) characters contain themselves. Note that the empty string is contained in all strings, including itself. >>> bool('') False >>> '' in '' True -- http://mail.python.org/mailman/listinfo/python-list
Re: how relevant is C today?
Daniel Nogradi wrote: >> "The Dice" (find tech jobs) has offerings >> (last 7 days, U.S. + unrestricted) for: >>*SQL 14,322 >>C/C++11,968 >>Java 10,143 >>... > > Can anyone shed some light on the secret of Java? How is it that they > are so high on this list? Sun invented a roundabout strategy to enroll programmers to Java by first attracting the attention of the Wall Street Journal with Hotjava, and thus the attention of the programmers' management. -- http://mail.python.org/mailman/listinfo/python-list
Re: updated pre-PEP: The create statement
Steven Bethard wrote: > I've updated the PEP based on a number of comments on comp.lang.python. > The most updated versions are still at: > > http://ucsu.colorado.edu/~bethard/py/pep_create_statement.txt > http://ucsu.colorado.edu/~bethard/py/pep_create_statement.html > > In this post, I'm especially soliciting review of Carl Banks's point > (now discussed under Open Issues) which asks if it would be better to > have the create statement translated into: > > = ("", *, **) > > instead of the current: > > = ("", , ) > > The former allows the create statement to be applied to a wider variety > of callables; the latter keeps a better parallel with the class statement. ... > and named, nested hierarchies like XML documents could be created > like:: > > create ETobject html: > "This statement would generate an ElementTree object" > > create ETobject head: > "generate the head" > ... > > create ETobject body: > "generate the body" > ... I think this is is a most important eventual use-case, and would like to see it better worked out - or else declared outside the scope of the proposed statement. As far as I can see, this does not cut it, since xml and html allow /sequencial repetition/ of tags and the results of the statement suites are passed as unordered namespaces/dicts. Cheers, az. -- http://mail.python.org/mailman/listinfo/python-list
Re: Sorting a list of objects by multiple attributes
Raymond Hettinger wrote: > > The cult of lambda avoidance has lost contact with reality. [...] > Lambda avoidance is rooted in two things, an aversion to the keyword > name [...] Let's push the diagnosis a bit further : the aversion to the keyword "lambda" has to do with the fact that it ignores the english word used by all non-geeks to convey the meaning, eg "given" -- http://mail.python.org/mailman/listinfo/python-list
Re: Looking for a language/framework
Alex Martelli wrote: > Jeffrey Froman <[EMAIL PROTECTED]> wrote: > >> Alex Martelli wrote: >> >>> I've never seen an "object-relational mapping" (technical >>> term for cruft that tries to avoid people having to learn and use SQL) >>> which doesn't drive me into a murderous, foam-at-mouth rage in a very >>> short time -- I WANT my SQL, I LOVE SQL, it's WAY more powerful >>> and suitable for access to data than all those simulated "OO DB" people >>> lay on top of it >> How refreshing to discover I'm not the only person on earth who feels this >> way. > > Hey, there's two of us, if this was Italy we could found a new political > party!-) Me too - I rather prefer using SQL to ORMs, *but* my basic reason is that I find it ridiculous for python ORMs to claim they lower sql/python impedance while they lead away from the python construct that's the obvious fit in the role of sql representative : I mean generator expressions. And OK, generator expressions aren't quite as powerful as SQL, but... well, maybe they can yet be perfected. -- http://mail.python.org/mailman/listinfo/python-list
Re: Sorting a list of objects by multiple attributes
Raymond Hettinger wrote: > Azolex: >> Let's push the diagnosis a bit further : the aversion to the keyword >> "lambda" has to do with the fact that it ignores the english word used >> by all non-geeks to convey the meaning, eg "given" > > Right. However, Guido has said that lambda is here to stay, > so it's time to get over it. You are saying lambda is a given ? ;) I've not observed the BDFL's pronouncement, so I have to ask : was it clear from his words that he meant the actual keyword, or could it be he just meant the construct while refering to it by the keyword ? -- http://mail.python.org/mailman/listinfo/python-list
Re: Figure out month number from month abbrievation
Bill wrote: > Hello -- > I'm parsing the output of the finger command, and was wondering > something...If I'm given a month abbrievation (such as "Jan"), what's > the best way to figure out the month number? > I see that there's > something called "month_abbr" in the calendar module. However, when I > try to do calendar.month_abbr.index("Jan"), I get "_localized_month > instance has no attribute 'index'." So it seems that month_abbr isn't > a regular list. I'm currently doing it this way: > > def month_number(monthabbr): > """Return the month number for monthabbr; e.g. "Jan" -> 1.""" > for index, day in enumerate(calendar.month_abbr): > if day == monthabbr: > return index > > which works well enough but isn't very clever. I'm pretty new to > Python; what am I missing here? > Thanks -- Bill. well, you can define the equivalent of your function with month_number = list(calendar.month_abbr).index or else "! Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec".split().index -- http://mail.python.org/mailman/listinfo/python-list
Re: Figure out month number from month abbrievation
John Salerno wrote: > Bill wrote: > >> def month_number(monthabbr): >> """Return the month number for monthabbr; e.g. "Jan" -> 1.""" >> for index, day in enumerate(calendar.month_abbr): >> if day == monthabbr: >> return index >> >> which works well enough but isn't very clever. I'm pretty new to >> Python; what am I missing here? >> Thanks -- Bill. > > I'm curious, does that really work, or is there a problem with the first > index being 0? Or is that avoided somehow? you don't have a python shell always at hand for such cases of curiosity ? >>> import calendar >>> tuple(calendar.month_abbr) ('', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec') -- http://mail.python.org/mailman/listinfo/python-list
Re: trying to grasp OO : newbie Q?
[EMAIL PROTECTED] wrote: > Hi, > > I just started with Python and I am new to OO programming. > Here is a simple code: > " > class Obj: > myVar = 1 > > def __init__(self): > myVar = 2 > > # > > > myObj = Obj() > > print myObj.myVar > " > > The output is of this script is '1'. I would except it to be '2'. > I not understanding something fundamentally here. You want to replace "myVar = 2" by "self.myVar = 2" to get the result you expect. > > Can anybody explain? > Your "myVar = 1" sets a variable in the namespace of the class Your "myVar = 2" sets a variable in the local frame of execution of the __init__ method, that is invisible outside that frame Putting "self.myVar = 2" will set a variable in the instance dict that will shadow the class variable of the same name when you access myObj.myVar hth -- http://mail.python.org/mailman/listinfo/python-list
Re: PEP 359: The "make" Statement
Steven Bethard wrote: > Rob Williscroft wrote: >> I don't know wether this has been suggested or not, but what about def: >> >> def namespace ns: >> x = 1 >> >> def type blah(object): >> pass >> >> def property x: >> def get(): >> return ns.x > > I think that's probably a bad idea because it would make people think > that the statement acts like a function definition, when it actually > acts like a class definition. maybe this could be marked with an appropriate decorator ? @namespace(mytype) def ns(base1,base2) : ... the decorator could take the function object apart, recover the bases arguments, run the code with a referenced local dict... hum, since in 2.4 exec allows a dict-like object as locals, it should even be possible to hack together a pretty concise hierarchical xml builder syntax embedded in current python - using neither the 'with' nor the 'make' statement, but simply defs ! Note that only the root of the (sub)tree would need to be a decorated "def" since embedded defs could then be caught through the locals pseudo-dict. Looks possible... at a first glance, the one thing that's unclear (to me) is how to deal with closure variables. To learn more, my tendency would be to launch a challenge : "Simulate function call and execution using an exec statement, as precisely as possible" I'll repeat that question in another thread... Best, az. -- http://mail.python.org/mailman/listinfo/python-list