Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to chain Python function calls so the behaviour is as follows

Tags:

python

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 
like image 805
Javi Avatar asked Jun 03 '19 11:06

Javi


People also ask

How does Python handle function calls?

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.

How do you call a specific part of a function in Python?

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.

Can you call a function within a function Python?

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.


1 Answers

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.

like image 155
sloth Avatar answered Sep 21 '22 15:09

sloth