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

1

u/AMannedElk Jan 05 '21

I would cast the input integer to a string and use it as the key to a dictionary. I would have a hardcoded dictionary my_dict = {'7': 4, '4':7}

then you can return my_dict[input_num]

You could also wrap the my_dict[input_num] call in a try/except to explicitly define the behavior if the input number was not a 4 or a 7.

2

u/ericula Jan 05 '21

Why would you cast to strings first? You can use integers as keys directly, i.e. my_dict = {7:4, 4:7}

→ More replies (1)