Open Source Your Knowledge, Become a Contributor
Technology knowledge has to be shared and made accessible for free. Join the movement.
Functions - Part I
Here are a few examples of user-defined functions in Python:
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
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)
Enter to Rename, Shift+Enter to Preview
Open Source Your Knowledge: become a Contributor and help others learn. Create New Content