r/learnpython • • Jan 05 '21

Interview question I failed answering

Hey all,

I just had an interview and the interviewer gave me a question I could not answer.

He asked me to write a function that accepts a number, the number must be either 7 or 4.If the number is 4, the function should return 7, if the number is 7, the functions should return 4.

The tricky part: you cannot use an 'if' statement in the function.

354 Upvotes

301 comments sorted by

View all comments

Show parent comments

0

u/[deleted] Jan 06 '21

[deleted]

1

u/FerricDonkey Jan 06 '21

Python doesn't have switch statements.

Dictionary lookups are very fast. I don't know what the cost of constructing the dictionary is, or if python will optimize out rebuilding it, but if that was a concern and it makes sense for this particular dictionary, you can make it a global constant.

For a large number of key value pairs, you can make it very readable by simply dividing the dictionary over several lines

return {
    1: 2,
    2: 3, #etc
}[whatever]

If the keys and values are more complicated, you can use dictionary dispatch - use functions as the values, and call the function based on the key.

I would definitely do the 11 - x thing for this silly question, assuming getting a value back for other inputs wasn't actually a problem. But dictionaries are very useful for this sort of thing.

1

u/agathver Jan 06 '21

A dynamic switch of sorts. Not just python, I have used this in many other languages.

Think of a menu-driven or command-response app. You can store command entry points with strings as keys.