By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
446,206 Members | 998 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 446,206 IT Pros & Developers. It's quick & easy.

[perl-python] 20050211 generating expression by nested loops

P: n/a
# -*- 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

# 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"),
# look for the function named Table.

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


Jul 18 '05 #1
Share this question for a faster answer!
Share on Google+

This discussion thread is closed

Replies have been disabled for this discussion.