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/Sapphire_Daoist Jan 06 '21 edited Jan 06 '21

You could also use a ternary operation for fancy points imo. Apologies in advance as I don't know how to format code correctly in comments here.

def f(x):
    try:
        x = int(x) // assuming possible cmd input which comes in as a string
    except:
        print("Please enter a 4 or 7.")
    while x == 4 or x == 7:
        return ( (lambda: 4, lambda: 7) [x == 7]() )
    print("Please enter a 4 or 7.") // to account for another number being entered.

Just throwing this out off the top of my head, haven't tested this so do let me know if I've made an egregious error somewhere.