Welcome, guest | Sign In | My Account | Store | Cart

An attempt to write a whole program inside a python lambda.

Python, 90 lines
 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.

6 comments

James Mills 14 years, 9 months ago  # | flag

Great little example! :) Nice work!

--JamesMills (prologic)

Ryan Lie 14 years, 9 months ago  # | flag

Hi, you can use __import__('sys').stdout.write() to avoid the import statement.

nxw (author) 14 years, 4 months ago  # | flag

Revised the program a little.

# It now uses a while loop.



(lambda dbg=1, n=(lambda:0):

# Start main lambda body
(
 # For the write function.
 setattr(n, 'sys', __import__('sys')),

 # while in a lambda.
 setattr(n, 'wil', lambda cndcn = 'True', 
                   fn=(lambda:0), 
                   dcn={} : (

   setattr(n.wil, 'fn', fn),
   dcn.update({'wil': n.wil}),  #add to dictionary to tell eval where 'wil' is.
   dcn.update({'n': n}),   #tell eval where 'n' is.
   setattr(n.wil, 'kod', 
     compile("while " + cndcn + " : wil.fn.__call__()\n", '', 'exec')),
   eval(n.wil.kod, dcn),
  )
),




 # 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.prin, n.fac, etc.


 setattr(n, 'prin', lambda *s:
    n.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 while to loop 
 # until input is 0 

 n.wil('n.outvr > 0', lambda:
 (

 # 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.prin('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.prin('n.outvr:', n.outvr)),


 # Find factorial
 setattr(n, 'f', n.fac(n.e, 1)),
 n.prin('Factorial of', n.e, 'is:', n.f),


 # Make list of factorials 
 setattr(n, 'faclis', [(i, n.fac(i,1)) for i in range(n.e+1)] ),

 # print list of factorials 
 n.prin('Fac list:', n.faclis),


)
), 



)  #end main lambda 


)(dbg=0) # Now call the lambda program
nxw (author) 13 years, 11 months ago  # | flag
#Simpler Example
#Idea to put statements inside expressions.
#
#Use: eval(compile())
#
#
#For python 2.5. 
#
#
#Entire program is inside lambda. 
#

(lambda dbg=1, den=(lambda:0):
#Start main lambda body.
( 

  #Need this for the write function.
  setattr(den, 'sys', __import__('sys')),

  #Letters to filter out of user input.
  setattr(den, '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', 
    '.', ',', ';', ':', '*', '-', '_', '#', '@', '$', '%',
    '^', '&', '(', ')', '{', '}', '[', ']', '+', '=',
    '<', '>', '/', '?', ' ' ]),

  #Useful functions: fak, fib, prin, etc.

  #print function
  setattr(den, 'prin', lambda *s:
    den.sys.stdout.write(' '.join(map(str, s) ))),

  #factorial function   
  setattr(den, 'fak', lambda n, ak=1: ak if n < 1 else 
    (den.fak(n-1, n*ak))    
    ),

  #fibonacci function
  setattr(den, 'fib', lambda n, p=1, q=1: 0 if n == 0 else (
       p if n < 2 else den.fib(n-1, q, p+q))
    ),

  #Function to loop
  setattr(den, 'asknmbr', lambda: (

    #Get user input.
    setattr(den, 'b', raw_input('Enter a number: ')),

    #Filter out letters from string.
    setattr(den, 'c', [i for i in den.b if not i in den.letrs]),

    # Join list back to string.
    setattr(den, 'd', ''.join(den.c)),

    #debug
    dbg and den.prin("d: ", den.d, '\n' ),


    #Check if get the empty string.
    setattr(den, 'e', (den.d == '' and '0' or den.d)),

    #If len of string is 0, return 1, else return int of string.
    setattr(den, 'f', ( len(den.e) <= 0 and 0 or int(den.e))),

    #debug
    dbg and den.prin("f: ", den.f, '\n' ),


    #Make list of numbers.
    setattr(den, 'lis', range(0, den.f+1)),

    #debug
    dbg and eval(compile('for i in den.lis: print i', '', 'exec')),


    #Make and print maths. 
    setattr(den, 'faklis', [(i, den.fak(i)) for i in den.lis]),

    den.prin('factorial list: \n', den.faklis, '\n'),

    setattr(den, 'fiblis', [(i, den.fib(i)) for i in den.lis]),

    den.prin('fibonacci list: \n', den.fiblis, '\n'),


    #Last item of list for return value.
    den.f

    #Get function return value.
  )[-1]  

  #End of asknmbr.
  ), 


  #Loop until function returns 0.
  eval(compile('while den.asknmbr() > 0: pass', '', 'exec')),

)

#Now call the lambda program.
)(dbg=0)
nxw (author) 13 years, 7 months ago  # | flag
#Another version.


#Run the set of nested lambdas and return a list
#while the length of the returned list > 1.
#Exit the while loop if the user presses only 
#the enter key, or enters only the digit 0,
#or enters no digit characters.

while(
 len(
   #Lambda to print a list of pairs of integers and their factorials.
   (lambda n: 
       #The second element of the list, n[1], is the set of functions that
       #the lambda below passed up.  
       #The first element of the list, n[0], is the result number 
       #that the lambda below passed up.

       n[1].pri1(

          [
            (i, n[1].fak(i) ) for i in range(0, n[0]+1)
          ]
                )#pri1

    )( #Apply this lambda to the lambda below.


(lambda n,
      #This parameter lambda that will hold the useful functions:
      ben=(lambda:0):
      #Here define some useful functions.

      setattr(ben, 'fak', lambda m, ak=1: ak if m < 1 else ben.fak(m-1, m*ak)) or

      setattr(ben, 'sys', __import__('sys')) or
      #A print function that returns its argument: 
      setattr(ben, 'pri1', lambda s: ben.sys.stdout.write(str(s)+'\n') or s) or

      [ben.pri1(n), ben] )( #Apply this lambda to the lambda below.

#If the result exceeds the recursion limt, then return 1
#otherwise return the result.
(lambda x: x if x < 998 else 1)( #Apply this lambda to the lambda below.  

#If the length of the string is 0, then return 0, 
#otherwise return the int value of the string.
(lambda e: len(e) <= 0 and 0 or int(e))( #Apply this lambda to the lambda below.  

   #Return the string '0' if the string is the empty string.
   #otherwise return the string. 
  (lambda d: (d == '' and '0' or d)) ( #Apply this lambda to the filtered string below.

    #Join list of strings into 1 string.
    ''.join(
    #Get user input and filter out letters and other non digit characters
    #from the input string, and build a list of strings.
      [i for i in raw_input('Enter an integer number: ') if not i in 

        [ 
          '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', 
          '.', ',', ';', ':', '*', '-', '_', '#', '@', '$', '%',
          '^', '&', '(', ')', '{', '}', '[', ']', '|', '+', '=',
          '<', '>', '/', '?', ' ', '!' , '\\'

        ]

      ]

    )
   )
  )
 )
)

)

) > 1): pass
nxw (author) 13 years, 2 months ago  # | flag

class inside lambda program adapted from
tutorial at pygtk website

(lambda b=(lambda:0),
sa=setattr :(


sa(b, 'pygtk', __import__("pygtk")),
b.pygtk.require('2.0'),
sa(b, 'gtk', __import__("gtk")),


sa(b, 'hk', type('hkt', (), 
{ 

 'nm' : 0,
 'fnm': 0,

 'prin' : lambda self, *s: 
   __import__('sys').stdout.write(
   ''.join([str(i) for i in s])
 ),


 'fac' : lambda self, n, d=(lambda:0):(
   sa(d, 'ak', 1),
   [0 for i in range(1, n+1) 
   if sa(d, 'ak', i*d.ak) < None],
   d.ak
 )[-1],


 'calbak': lambda self, 
                 widget, 
                 dta:(

   dta == 'bt1'  and 
     (
       sa(self, 'nm', self.nm + 1),
       self.prin(self.nm, '\n'), 
     ),


   dta == 'bt2' and 
    ( 
      sa(self, 'fnm', self.fac(self.nm)),
      [0 for i in 
        range(0, int(self.nm + 1)) if
        self.prin(i, ', ', self.fac(i), '\n')
      ]
     ), 


   dta == 'btn3'  and 
    (
       sa(self, 'nm', self.nm - 1),
       self.prin(self.nm, "\n"), 
     ),  

 ),



'__init__': lambda self :
( 


  self.prin(self.nm, '\n'),

  sa(self, 'window', 
    b.gtk.Window(b.gtk.WINDOW_TOPLEVEL)),

  self.window.set_title("Calc"),

  self.window.connect("delete_event", self.delete_event),

  sa(self, 'box1', b.gtk.VBox(True, 10)),

  self.window.add(self.box1),

  sa(self, 'bt1', b.gtk.Button(label='+')),
  self.bt1.connect("clicked", self.calbak, "bt1"),
  self.box1.pack_start(self.bt1, True, True, 0),
  self.bt1.show(),


  sa(self, 'bt2', b.gtk.Button(label = 
      "  Factorial  ")),
  self.bt2.connect("clicked", self.calbak, "bt2"),
  self.box1.pack_start(self.bt2, True, True, 0),
  self.bt2.show(),


  sa(self, 'btn3', b.gtk.Button(label='-')),
  self.btn3.connect("clicked", self.calbak, 'btn3'),
  self.box1.pack_start(self.btn3, True, True, 0),
  self.btn3.show(),



  self.box1.show(),

  self.window.show(),
  None 
  )[-1], 

 'delete_event' : 
   lambda self, 
   widget, 
   event, 
   data=None:(
   b.gtk.main_quit(),
   False 
   )[-1],


})), 


sa(b, 'mn', lambda: b.gtk.main()),


( 
 sa(b, 'helo', b.hk()),
 b.mn()
) if __name__ == "__main__" else 0))()
Created by nxw on Fri, 3 Jul 2009 (MIT)
Python recipes (4591)
nxw's recipes (1)

Required Modules

Other Information and Tasks