We have a question we ask at our office during interviews that goes like this. For the sake of consistency, I am restricting the context of this to python. I'm sure there are other answers but I'm really only interested in python answers.
Write me a function named say
that when called like this:
>>> say('Hello')('World')
It ONLY Prints (not returns):
>>> say('Hello')('World')
Hello World
>>>
We got into a meta discussion after the interview today where I stated that I am always hoping the applicant will answer with the following.
def say(x):
print "Hello World"
return lambda a:None
I realized that there is a possibility of shortening this further by replacing the lambda
function with a built in of some sort that returns None
but I've dug and can't seem to find one that is shorter than lambda a:None
So the overall question here is...
Can you think of a way to make this shorter, as in less overall characters (ignoring line breaks). Any import statements are counted in your character count. (52 Characters)
UPDATE
(39 Characters)
>>> def p(x):
... print "Hello",x
>>> say=lambda x:p
>>> say("Hello")("World")
Hello World
>>>
Python 3 Answer (48 Characters)
>>> def say(x):
... return lambda a:print("Hello World")
>>> say("Hello")("World")
Hello World
>>>
Python 2.x answers
The obvious answer that doesn't actually count because it returns the string instead of printing it:
>>> say = lambda x: lambda y: x + " " + y
>>> say('Hello')('World')
'Hello World'
This one is 45 characters counting newlines:
def p(x):
print "Hello World"
say=lambda x:p
This method drops it down to 41 characters but it looks kind of odd since it uses one argument but not the other:
def p(x):
print "Hello",x
say=lambda x:p
Python 3.x answers
36 characters:
>>> say=lambda x:lambda y:print(x+" "+y)
>>> say('Hello')('World')
Hello World
38 characters:
>>> say=lambda x:print(x,end=' ') or print
>>> say('Hello')('World')
Hello World
def say(x):
print x,
return say
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