An attempt to write a whole program inside a python lambda.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 | #Dont know if this has been done
#a lot before, but I
#got inspired from the web site
#http://p-nand-q.com/python/stupid_lambda_tricks.html
#and tried to write a lambda that
#is a complete program, except for
#the import.
#Sure a lot of fun to write.
#
import sys #For the write function
#All variables are inside of the lambda
#
(lambda dbg=1, n=(lambda:0):
#start main lambda body
(
#List of characters that we filter out
#of user input
setattr(n, 'letrs', ['a', 'b', 'c', 'd', 'e',
'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p',
'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K',
'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V',
'W', 'X', 'Y', 'Z',
'.', ',', ';', ':', '*', '-', '_', '#', '@', '$', '%',
'^', '&', '(', ')', '{', '}', '[', ']', '+', '=',
'<', '>', '/', '?', ' ' ]),
#make functions n.prit, n.fac, etc.
#Use write function from p-nand-q.com web site
setattr(n, 'prit', lambda *s:
sys.stdout.write(' '.join(map(str, s) + ['\n'] ))),
setattr(n, 'fac', lambda m, ak:
((m < 1 and [ak]) or [n.fac(m-1, m*ak)] )[0]),
#Variable to test whether we get out of loop
setattr(n, 'outvr', 1),
#Use list comprehension to loop thru tuple
#until input is 0, or preset number of
#times thru the loop
[(
#Get user input
setattr(n, 'b', raw_input('Enter a number: ')),
#Filter out letters from string
setattr(n, 'c', [i for i in n.b if not i in n.letrs]),
#Join list back to string
setattr(n, 'dt', ''.join(n.c)),
#Check if we get the empty string
setattr(n, 'd', (n.dt == '' and '0' or n.dt)),
#For debug
(dbg and n.prit('n.d:',n.d)),
#If len of string is 0, return 1, else return int of string
setattr(n, 'e', ( len(n.d) <= 0 and 0 or int(n.d))),
#Set variable to see if we get out of loop
setattr(n, 'outvr', n.e),
#For debug
(dbg and n.prit('n.outvr:', n.outvr)),
#Find factorial
setattr(n, 'f', n.fac(n.e, 1)),
n.prit('Factorial of', n.e, 'is:', n.f),
#Make lists of factorials
setattr(n, 'faclis', [(i, n.fac(i,1)) for i in range(n.e+1)] ),
#print lists of facs
n.prit('Fac list:', n.faclis),
) for j in range(100) if n.outvr > 0 ] #end loop
)#end main lambda
)(dbg=0) #Call lambda program
|
Just for fun.
Tags: lambda
Great little example! :) Nice work!
--JamesMills (prologic)
Hi, you can use __import__('sys').stdout.write() to avoid the import statement.
Revised the program a little.
class inside lambda program adapted from
tutorial at pygtk website