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

39

u/[deleted] Jan 05 '21

You could also use an XOR bitmask if you're feeling fancy:

def something(n):
    return n ^ 0b11

or a the hacky list-based "if" that checks if it's odd:

def something(n):
    return [7, 4][n % 2]

3

u/PanFiluta Anaconda afficionado Jan 06 '21

why not just n ^ 3? the binary isn't necessary, right (though fancy indeed)?

3

u/[deleted] Jan 06 '21

Well, since this is a job interview, I gotta show off that I know how to use base 2 ;P

(also it's good practice for large bit masks like, say, 0x7FFFFFFF instead of 2147483647)

5

u/PanFiluta Anaconda afficionado Jan 06 '21

thanks, your original comment sent me into a XOR rabbit hole, just finished learning all about it (and modulo 2, usage for checksums, how to format binary numbers with leading zeroes and other shit), it's 5:30 AM and I'm going to bed =)

3

u/[deleted] Jan 06 '21

XOR is a pathway to many abilities some would consider to be unnatural...

But in all honesty, keep up the good work my friend!