Wednesday, October 14, 2015

Simple Lambda examples in Python


Simple lambda function examples (Python)

Use this to learn lambda, I do not recommend using this in your production code.

The exercises are here:

https://github.com/zhiwehu/Python-programming-exercises/blob/master/100%2B%20Python%20challenging%20programming%20exercises.txt

Solutions with the question numbers below. Had some help from http://stackoverflow.com/questions/33113720/count-in-python-lambda-function

import math
from itertools import count
from operator import itemgetter, attrgetter

mylist = ['abc', '123', '758', 'cde']
hello = "Hello world this is Testing for Caps and Lower"


# 1 print filter(lambda x : x%7 == 0 and x%5!=0, range(2000, 3200))

# 3 print  map(lambda x: (x, x*x) ,range(1,input()+1))

# 6 print map(lambda x: round(math.sqrt((2 * 50 * x)/30)) , list(input()))

# 9 print ''.join(map(lambda x: x.upper(),raw_input()))

# 11 print filter(lambda x : int(x,2)%5 == 0, raw_input().split(','))

# 12 WIP print (lambda y : int(y[0])%2 ==0 ,map(lambda x: x, str(range(1,10))))

# 13 print reduce(lambda (x,y),(a,b): (x+a, y+b), [(e.isdigit(),e.isalpha()) for e in mylist], (0,0))
# 13 print reduce(lambda (x,y),(a,b): (x+a, y+b), map(lambda x: (1 if x.isalpha() else 0, 1 if x.isdigit() else 0), mylist), (0,0))


# 14 print reduce(lambda (x,y), (a,b) : (x+a, y+b) , [(e[0].isupper(), e[0].islower()) for e in hello.split(' ')], (0,0))

# 16 intlist = [1,2,3,4,5,6,7,8,9] print filter(lambda x: x%2!=0, intlist)


No comments:

Post a Comment