Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interesting "Hello World" Interview

Tags:

python

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
>>> 
like image 466
Piper Merriam Avatar asked Aug 10 '11 21:08

Piper Merriam


2 Answers

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
like image 159
Andrew Clark Avatar answered Oct 11 '22 19:10

Andrew Clark


def say(x):
   print x,
   return say
like image 28
Theran Avatar answered Oct 11 '22 21:10

Theran