Back
Close

Computing with Data

elgeish
33.3K views

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
Create your playground on Tech.io
This playground was created on Tech.io, our hands-on, knowledge-sharing platform for developers.
Go to tech.io
codingame x discord
Join the CodinGame community on Discord to chat about puzzle contributions, challenges, streams, blog articles - all that good stuff!
JOIN US ON DISCORD
Online Participants