undefined

Open Source Your Knowledge, Become a Contributor

Technology knowledge has to be shared and made accessible for free. Join the movement.

Create Content

Functions - Part I

Here are a few examples of user-defined functions in Python:

def scale(vector, factor):
return [x * factor for x in vector]
print(scale([1, 2, 3], 2))
print(scale({1, 2, 3}, 2)) # unordered
print(scale(factor=2, vector=(1, 2, 3)))
# the * operator works with lists and tuples as well,
# but it has different semantics:
print(scale([(1, 2, 3)], 2))
# Example: recursion
from collections import Sequence
def scale(vector, factor, recursively=False):
if recursively:
# call scale recursively for sequence elements
return [scale(x, factor, True) if isinstance(x, Sequence)
else (x * factor) for x in vector]
else:
return [x * factor for x in vector]
print(scale([(1, 2, 3)], 2)) # recursively is False by default
print(scale([(1, 2, 3)], 2, recursively=True))
# Example: recursion (two functions)
def scale_recursively(vector, factor):
return [scale_element(x, factor) for x in vector]
def scale_element(element, factor):
if isinstance(element, Sequence):
return scale_recursively(element, factor)
else:
return element * factor
print(scale_recursively([1, [2, 3]], 2))
# Example: nested functions
def scale_recursively(vector, factor):
def scale_element(element):
if isinstance(element, Sequence):
return scale_recursively(element, factor)
else:
return element * factor
return [scale_element(x) for x in vector]
print(scale_recursively([1, [2, 3]], 2))
# Example: currying
def create_line_printer(prefix):
def print_suffix(suffix):
print(prefix, suffix)
return print_suffix
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Open Source Your Knowledge: become a Contributor and help others learn. Create New Content