Created
December 15, 2014 22:30
-
-
Save dhaffner/b909e6f4018963b9bd3f to your computer and use it in GitHub Desktop.
Python features
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
from random import randint | |
def compose(*funcs): | |
'''Return a function that represents the composition | |
of an arbitrary number of functions. | |
''' | |
compose_once = lambda f, g: lambda x: f(g(x)) | |
return reduce(compose_once, funcs) | |
def double(x): | |
'''Double a number.''' | |
return 2 * x | |
def square(x): | |
'''Squre a number.''' | |
return x ** 2 | |
def random_numbers(count): | |
'''Return a given amount of random integers''' | |
return [randint(0, 100) for x in xrange(count)] | |
# Create a function that doubles a number and then squares it. | |
double_and_square = compose(square, double) | |
# Create a function that squares a number and then doubles it. | |
square_and_double = compose(double, square) | |
if __name__ == '__main__': | |
k = 10 | |
nums = random_numbers(k) | |
print('{} random numbers: {}'.format(k, nums)) | |
print('') | |
lst1 = [double_and_square(n) for n in nums] | |
print('Doubled and squared: {}'.format(lst1)) | |
lst2 = [square_and_double(n) for n in nums] | |
print('Squared and doubled: {}'.format(lst2)) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment