I stumbled upon the following problem on a python challenge: Write a function that satisfies the following rule for any number of function calls.
f()()()()()(s) == 'fooooo' + s;
example:
f('it') == 'fit'; f()('x') == 'fox'; f()()('bar') == 'foobar'; f()()()('l') == 'foool';
The function should be stateless and should not use any variables outside the scope.
The function signature was:
def f(s=None): # Your code here
I thought that in order to be able to chain multiple calls we will have to return a function when no string is passed into the function, but can't figure out how to build the expected string with no external variables. Suggestions?
def f(s=None): if s is None: # concatenate an 'o'? return f else: # Last call, return the result str. return s
Python also accepts function recursion, which means a defined function can call itself. Recursion is a common mathematical and programming concept. It means that a function calls itself. This has the benefit of meaning that you can loop through data to reach a result.
The only way to run just part of a function is to change the function so it includes some kind of conditional check, in which case it's not really the same function and you might as well rewrite it completely to separate out the part you don't want.
In Python, any written function can be called by another function. Note that this could be the most elegant way of breaking a problem into chunks of small problems.
An alternative to Nikola's answer is something like this:
def f(s=None): if s: return f'f{s}' def factory(prefix): def inner(s=None): return f'f{prefix}{s}' if s else factory(prefix + 'o') return inner return factory('o')
using a closure and no helper function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With