Differences between revisions 1 and 2
Revision 1 as of 2004-09-16 02:56:25
Size: 6101
Editor: dknrgwpxav02
Comment:
Revision 2 as of 2004-09-16 02:59:10
Size: 6104
Editor: dknrgwpxav02
Comment:
Deletions are marked like this. Additions are marked like this.
Line 41: Line 41:
== The Larger Set of Not-So-Good Solutions == The Larger Set of Not-So-Good Solutions ==

Discussion

Perl coders are proud that Perl's motto is "There's more than one way to do it."BR In comparison, Python is sometimes stereotyped as "There's only one way to do it", but this is of course not true. The Zen of Python, accessed via

import this

includes the maxims:BR Beautiful is better than ugly.BR Explicit is better than implicit.BR Simple is better than complex.BR Complex is better than complicated.BR Flat is better than nested.BR Sparse is better than dense.BR Readability counts.BR If the implementation is hard to explain, it's a bad idea.BR There should be one-- and preferably only one --obvious way to do it.BR

The net effect is that there is a limited set of good solutions for a given problem, and user are strongly encouraged to use them.

While Python attempts to discourage bad practices, and its indentation-based block structure and limited anonymous blocks (lambdas) make certain techniques difficult, it is possible to produce many more bad solutions than good for a given problem. This page attempts to demonstrate this for the benefit of non-users, and should be linked to when incorrect claims of Python's limitations are made.

Please Feel Free to extend with more examples.

The Problem

Q: How do I write code for a signature block (up to four lines of 78 characters each) that prints "Just another Pythoneer" to screen?

The Limited Set of Good Solutions

   1 print "Just another Pythoneer"

(Though someone may point out that as a Python user following correct Pythonic practice, you are more correctly a Pythonista... and give you a brief 6000 word essay on the historical debate over the naming of Python Users and the etymology of the root Python and the stem -ista... and advise you against using the combination in an impromptu Spanish examination)

The Larger Set of Not-So-Good Solutions

   1 print "Just", "another", "Pythoneer"

   1 print '''%s %s %s''' % ("Just", "another", "Pythoneer")

   1 print '%(j)s %(a)s %(py)s' % { "j": "Just", "a": "another", \
   2   "pl": "Perl Hacker", "py": "Pythoneer", "c": "C Coder", \
   3   "f": "Fortran Freak", "turtle" : "Logo Lover" }

   1 import sys; sys.stdout.write("Just another Pythoneer\n")

   1 x = ['r','e','e','n','o','h','t','y','P',' ','r','e','h','t','o','n','a',' ',
   2      't','s','u','J']
   3 x.reverse()
   4 print "".join(x)

   1 print "".join(['r','e','e','n','o','h','t','y','P',' ','r','e','h','t','o','n',
   2                'a',' ','t','s','u','J'][::-1])

   1 print "reenohtyP rehtona tsuJ"[::-1]

   1 import pickle; print pickle.loads("S'Just another Pythoneer'\012p0\012.")

   1 def k(x):
   2     if type(x) == type({}): return x.keys()[0] + k(x.values()[0])
   3     return x
   4 print k({"Just ": {"another ": "Pythoneer"}})

   1 japy = lambda x: isinstance(x,dict) and x.keys()[0] + japy(x.values()[0]) or x
   2 print japy({"Just ": {"another ": "Pythoneer"}})

   1 import sys
   2 for c in "Just another Pythoneer\n":
   3     sys.stdout.write(c)

   1 import sys; [sys.stdout.write(c) for c in "Just another Pythoneer\n"]

   1 import uu, StringIO
   2 s = StringIO.StringIO(); uu.decode(StringIO.StringIO('begin 666 '+\
   3   '-\01262G5S="!A;F]T:&5R(%!Y=&AO;F5E<@  \012 \012end\012'), s)
   4 print s.getvalue()

   1 x = ["Just", "another", "Pythoneer"]
   2 while x: print x[0], ; x = x[1:]
   3 print

   1 x = ["Pythoneer", "another", "Just",]
   2 while x: print x[-1], ; x.pop()
   3 print

   1 import string, re
   2 a = ["Pythoneer", "extra", "Just", "words", "another", "Hello!"]
   3 m = re.match("(?P<three>\d+).(?P<one>\d+).(?P<two>\d+)", "1A5l2")
   4 print a[m.start("one")], a[m.start("two")], a[m.start("three")]

   1 try:
   2   raise "Just another Pythoneer"
   3 except:
   4   print sys.exc_info()[0]

   1 import random, sys; x = "Just another Pythoneer\n"
   2 while x:
   3   y = random.choice(x);
   4   if y == x[0]: sys.stdout.write(y); x = x[1:]

   1 def f(z):
   2   '''Just another Pythoneer (and remember to document your code!)'''
   3   pass
   4 print f.__doc__[:22]

   1 class Print:
   2     def __call__(self): print
   3     def __getattr__(self, name): print name, ; return self
   4 Print().Just.another.Pythoneer()

   1 #Sometimes_code_does_not_really_need_to_have_syntacally_significant_whitespace
   2 G,U,N=range(3),"Why don't I use Java or Perl?",lambda(x),y:reduce(x.__add__,y)
   3 print"".join([U[P:H+P]for(P,H)in(zip([16,12,8,19,6,5,8,1,25,23,2,8,1,5,14,25],
   4 N(list,N(tuple,[([D],N(list,[[1+C%2]*(C+1)for(C)in(G)]))for(D)in(G)])[1:])))])

   1 class Just_another_Pythoneer(object):
   2     def __init__(self):
   3         print " ".join(self.__class__.__name__.split("_"))
   4 Just_another_Pythoneer()

   1 def Just_another_Pythoneer(fn):
   2     print fn.func_name.replace("_"," ")
   3 Just_another_Pythoneer(Just_another_Pythoneer)

   1 def _(Just, another, Pythoneer):_
   2 print " ".join(_.func_code.co_varnames)

   1 d,o=0x3B55094199ACFB742DB37F3F97B11175C0C8EL,[]
   2 while d:
   3     d,m=divmod(d,100);o.append(chr(m+32))
   4 print "".join(o)

   1 def japy(d=0x3B55094199ACFB742DB37F3F97B11175C0C8EL):
   2     while d:
   3         d,m=divmod(d,100);yield m+32
   4 print "".join([chr(x) for x in japy()])

   1 print "".join([x for x in list('reenohtyP rehtona tsuJ')[::-1]])

   1 print "".join([x for x in list('reenohtyP rehtona tsuJ')][::-1])

   1 print "Just another Pythoneer and not a Perl Hacker".split(" and")[0]

   1 print "I'm just another Pythoneer".split(" ",1)[1].capitalize()

Credits

AndrewDalkeBR HansNowakBR "Snippet 181"BR TaroOgawaBR

JustAnotherPythoneer (last edited 2008-11-15 14:01:16 by localhost)

Unable to edit the page? See the FrontPage for instructions.