Friday, June 25, 2010

Lambda expression буюу Зарлагаагүй хэрэглэгдэх функц (үргэлжлэл)

За энд LE-д if, else-г ашигласан жишээ бичиж үзье.








>>> le1 = lambda f : f > 10 and 'bigger than 10' or 'smaller than 10'
>>> toonuud = range(5,16)
>>> for i in toonuud:
...     if i != 10 : 
...             print '{0} is {1}'.format(i,le1(i))
...     else: print '{0} equal to 10'.format(i)
... 
5 is smaller than 10
6 is smaller than 10
7 is smaller than 10
8 is smaller than 10
9 is smaller than 10
10 equal to 10
11 is bigger than 10
12 is bigger than 10
13 is bigger than 10
14 is bigger than 10
15 is bigger than 10


Энд арай өөр бичигллээр бас бичиж болно, гэхдээ дээрх бичиглэл нь арай л тохиромжтой байхаа.


>>> le2 = lambda x: ['smaller than 10', 'bigger than 10'][x>10]
>>> for i in toonuud:
...     if i !=10 :
...             print '{0} is {1}'.format(i,le2(i))
...     else:   print '{0} is equal to 10'.format(i)
... 
5 is smaller than 10
6 is smaller than 10
7 is smaller than 10
8 is smaller than 10
9 is smaller than 10
10 is equal to 10
11 is bigger than 10
12 is bigger than 10
13 is bigger than 10
14 is bigger than 10
15 is bigger than 10


Энд жаахан өөр бичиглэл байна.


>>> le3 = lambda d:'Tegsh' if d % 2 ==0 else 'Sondgoi'
>>> le3(1)
'Sondgoi'
>>> le3(2)
'Tegsh'

Дээрх хэдийг жагсаан харвал :

   le1 = lambda f : f > 10 and 'bigger than 10' or 'smaller than 10'
   le2 = lambda x: ['smaller than 10', 'bigger than 10'][x>10]
   le3 = lambda d:'Tegsh' if d % 2 ==0 else 'Sondgoi'

     байна.

    Одоо LE дотор LE ашиглаж болох эсэхийг шалгаж үзье.







    >>> leTRUE = lambda t : t%2==0 and 'True' or 'False'






    >>> leTRUE(2)
    'True'
    >>> leTRUE(3)
    'False'

    >>> outsideLE = lambda d : leTRUE(d)=='True' and 'Ene bol tegsh too' or 'Ene bol sondgoi too'
    >>> outsideLE(2)
    'Ene bol tegsh too'
    >>> outsideLE(3)
    'Ene bol sondgoi too'

    Энд стрингтэй ажиллаж байгаа жишээ байна.


    >>> str = """neg
    ... xoer     guraw
    ...   dorow """
    >>> print (lambda s: " ".join(s.split()))(str)
    neg xoer guraw dorow



    No comments:

    Post a Comment

    Сэтгэгдэл үлдээж байгаад баярлалаа :]