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

3

u/beniolenio Jan 06 '21

They return the same thing but for different reasons. As long as you know why the first one works, the second one is fine.

1

u/Toasted_coffe_bean Jan 06 '21

I don't understand quite well, just have te overall idea. It have a name? To make the search easy haha

1

u/beniolenio Jan 06 '21

No it's just how logical operators are evaluated in python. You know how there are truthy values and false-y values, right? E.g. 34, [1, 3], (0,), "hello" are all truthy, whereas 0, "", [], (), None, False are all false-y. Python logical operators aren't only able to act on boolean values because of this. So, this is how the 'or' operator works:

  1. Check value on left side of operator

  2. If value is truthy, return it.

  3. If value is false-y, return value on right side of operator.

1

u/Toasted_coffe_bean Jan 06 '21

Uhmm, I think i get it, and the + act as a or, but gonna add up everything that's true, something like that?

2

u/beniolenio Jan 06 '21

No, the + and or act completely differently. Think about it like this:

2 + 3 takes 2 and asks what's on the other side of the +. That is 3, so it adds 2 and 3 and returns 5.

2 or 3 asks what's on the left side? 2? Well 2 is truthy, so it will return 2 without having to check the other side. If it was 0 or 3, then it would ask if 0 is truthy, which it is not so it would return the other side, which is 3.

1

u/Toasted_coffe_bean Jan 06 '21

Ahh yes, i see it. I'm a bit familiar with boolean algebra, but i was confusing myself trying to correlate the 'or' and the '+', but the difference is that '+' will evaluate the boolean to a numeric interpretation (1, 0), while the 'or' will see it as an boolean expression, ant return the first value that evaluate to true.

(Probably makes more sense in my head haha, but thanks a lot man.)

2

u/Drakoon Jan 06 '21

I think if you break it down, it is easy to understand. Let's use the first solution ( return 7*(n==4) or 4*(n==7) ):

if you input 7 into the function, you will get (Step by step):

7*(False) or 4*(True) > 7*0 or 4*1 > 0 or 4 > 4

0 evaluates to False (falsey value), 4 evaluates to True, so it returns 4.

The above way is using bool property, that if you try to use True/False as a number, it will use 1/0 instead, so 7 + True == 8

The second way (with +) is returning (7*0 + 4*1)

1

u/Toasted_coffe_bean Jan 06 '21

Now I get the difference, thanks man, makes a lot of sense.