Functions
Contents
Functions#
Read Functions before you start with the exercises.
Inplace Squaring#
Write a function which squares all numbers in a list. The list of numbers is the only parameter and there is no return value. The results have to be stored in the original list.
Test your code with
[1, 2, 3, 4, 5]
Solution:
# your solution
Arbitrary Keyword Arguments#
Write a function taking an arbitrary number of keyword arguments and printing all of them.
Test your code by passing
a=1, b='test', c=(1, 2, 3)
This should yield the output
a: 1
b: test
c: (1, 2, 3)
Solution:
# your solution
Apply to All#
Write a function apply_to_all
which takes an arbitrary number of arguments.
The first argument is a function taking a float and returning a float.
All other arguments are floats.
The apply_to_all
function shall apply the first argument (function) to all other arguments (floats).
Results shall be returned as tuple of floats.
Test your code with a function, which calculates the square of a number. So calling apply_to_all(lambda x: x * x, 3, 2, 5)
yields (9, 4, 25)
.
Hint: For apply_to_all
one short line of code suffices, but you may use more.
Solution:
# your solution
Composition#
Write a function apply_composition
which takes an arbitrary number of positional arguments.
The first argument is mandatory. It’s a float.
All other arguments are optional. They are real functions of a real variable, which shall be applied to the first argument.
Example: If three functions are passed to your function, then the first is to be applied to the float, the second is to be applied to the result of the first function, and the third is to be applied to the result of the second function.
Test your code with 23.42
and the following functions:
square a number
add 3
sine (from
math
module)multiply by 2
Result should be -1.9784623024455807
.
Solution:
# your solution
Sorting#
Sort a list of paths by file name. Use list.sort
with custom sort key.
Test your code with
['/some/path/file.txt',
'/another/path/xfile.txt',
'file_without_path.xyz',
'../relative/path/abc.py',
'/no/extension/some_file.txt']
Result should be
['../relative/path/abc.py',
'/some/path/file.txt',
'file_without_path.xyz',
'/no/extension/some_file.txt',
'/another/path/xfile.txt']
Solution:
# your solution
Loop versus Recursion#
Given an integer \(n\) calculate \(n!\) (see Combinatorics for a definition) using a loop. Then calculate \(n!\) by exploiting the recursive rule \(n!=n\cdot(n-1)!\). Test both functions with \(10!=3628800\).
Solution:
# your solution