[perl-python] 20050211 generating expression by nested loops

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

# -*- coding: utf-8 -*-
# Python

# David Eppstein of the Geometry Junkyard fame gave this elegant
# version for returing all possible pairs from a range of n numbers.

def combo2(n):
    return dict([('%d,%d'%(i+1,j+1),(i+1,j+1)) for j in range(n) for i
in range(j)])
print combo2(5)

# this construct uses a irregular syntax to generate a expression
# built by nested loops.  Semantically, this expression generation is
# akin to applying a function to a tree. Morons in the computing
# industry and academia like to call this "list comprehension".

# In Python, this syntax irregularity works like this, for example:

# double each number from 1 to 5
myExpression = [ i*2 for i in range(1,6)]
print myExpression

# built a list of couples of the form (n*2,n*3)
myExpression = [ (i*2,i*3) for i in range(1,6)]
print myExpression

# in general the this expression generating syntax has the form
# [<expression> <iteration>]

# the iteration part can be nested.
myExpression = [ (i,j) for i in range(1,6) for j in range(1,4)]
print myExpression

# remember, this jargonized "list comprehension" is nothing more
# a irregular syntax for building a expression from nested loops.  Its
# purpose is primarily of syntactical convenience. Advanced languages
# such as functional languages often have this power without the
# syntax irregularity.

# For Python's official tutorial on this topic, see
# http://python.org/doc/tut/node7.html


# Perl does not contain facilities to generate expressions based on
# trees. Of course, one can just do with for loops. One can however
# write a function that are syntactically more succinct in generating
# expression thru trees than the so-called "list comprehension"),
# http://xahlee.org/PerlMathematica_dir/perlMathematica.html
# look for the function named Table.

his is Perl-Python a-day. To subscribe, see


Site Timeline