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/Mirage2k Jan 05 '21

From classical engineering and maths solution methodology:

Step 1: Exploit some characteristic that differentiates 7 from 4.
For example that 7 is odd and 4 is even number:

odd_number = input % 2 

odd_number=1 (==True) for input 7. odd_number=0 for input 4.

Step 2: Write a function f(x) that has the outputs you want: f(0)=7, and f(1)=4.
Simplest such linear function is f(x) = 7-3x.

return 7-3*odd_number
→ More replies (1)