Reputation: 4521
During my interview they asked me a implement a function to reverse each word in a sentence and create final sentence from it. For example:
s = 'my life is beautiful'
output - `ym efil si lufituaeb`
I know the question is pretty simple so solved it in few minutes:
s = 'my life is beautiful'
def reverse_sentence(s):
string_reverse = []
for i in s.split():
string_reverse.append("".join(list((reversed(i)))))
print " ".join(string_reverse)
reverse_sentence(s)
Then they asked to implement the same function using a decorator
, and I got confused here. I know the basics of decorator
how it used, and when it used. They didn't mention what part of the function they want to wrap
using decorator
. They told me to implement this using args
and kwargs
, and I was not able to solve it. Could anyone help me here? How can I convert any function into decorator?
As my per knowledge, you use decorator
when you want to wrap your function
or you want to modify the some functionality. Is my understanding correct?
Upvotes: 3
Views: 134
Reputation: 3121
How about this:
# decorator method
def my_decorator(old_func):
def new_func(*args):
newargs = (' '.join(''.join(list(args[0])[::-1]).split()[::-1]),)
old_func(*newargs) # call the 'real' function
return new_func # return the new function object
@my_decorator
def str_rev(mystr):
print mystr
str_rev('my life is beautiful')
# ym efil si lufituaeb
Upvotes: 1
Reputation: 51998
Here is a different take -- it defines a decorator which takes a function which sends strings to strings and returns another function which maps the passed function over a split string and then rejoins:
def string_map(f): #accepts a function on strings, splits the string, maps the function, then rejoins
def __f(s,*args,**kwargs):
return " ".join(f(t,*args,**kwargs) for t in s.split())
return __f
@string_map
def reverse_string(s):
return s[::-1]
typical output:
>>> reverse_string("Hello World")
'olleH dlroW'
Upvotes: 1
Reputation: 113998
def reverse_sentence(fn): # a decorator accepts a function as its argument
def __inner(s,*args,**kwargs): #it will return this modified function
string_reverse = []
for i in s.split():
string_reverse.append("".join(list((reversed(i)))))
return fn(" ".join(string_reverse),*args,**kwargs)
return __inner # return the modified function which does your string reverse on its first argument
I guess...
@reverse_sentence
def printer(s):
print(s)
printer("hello world")
Upvotes: 2