Piper Merriam
Piper Merriam

Reputation: 2954

Interesting "Hello World" Interview

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
>>> 

Upvotes: 9

Views: 2465

Answers (4)

msvinay
msvinay

Reputation: 41

say = lambda y:(lambda x:print(y+' '+x))
say('Hello')('World')
hello world

Upvotes: 0

slothrop
slothrop

Reputation: 5428

At least in Python 3, print is a function that returns None, so you can do this:

def say(x):
    return lambda a: print ('Hello World')

or (saving a few more characters):

say=lambda x:lambda y:print("Hello World")

Upvotes: 5

Andrew Clark
Andrew Clark

Reputation: 208615

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

Upvotes: 14

Theran
Theran

Reputation: 3866

def say(x):
   print x,
   return say

Upvotes: 7

Related Questions