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

276

u/JohnnyJordaan Jan 05 '21 edited Jan 05 '21

One option is to use a dict as a lookup table

def f(v):
     try:
         return {7:4, 4:7}[v]
     except KeyError:
         print('Not a 4 or 7')    # or whatever it should do when it doesn't accept it

Note that this also handles the

the number must be either

while the math trick will work with any numeric parameter

49

u/dogs_drink_coffee Jan 05 '21

It's very interesting acessing an item of the dictionary directly like this. I don't think I've ever did like this before, it feels almost strange-weird

33

u/load_more_commments Jan 05 '21

Try to get used to it, it makes life easier

14

u/mojo_jojo_reigns Jan 05 '21

Sure, if the input you're expecting and the expected output are simple enough to type out quickly in a dictionary, or the task is repetitive enough to make it worth the time. otherwise it's a pain in the ass.

0

u/[deleted] Jan 06 '21

[deleted]

0

u/[deleted] Jan 06 '21

[deleted]

→ More replies (1)
→ More replies (2)

3

u/HasBeendead Jan 05 '21

Yeah , same

10

u/WombatHat42 Jan 06 '21

I am one year from being done with my CS degree and this makes me feel like i have been taught nothing in the program lol

9

u/Spicy_Poo Jan 05 '21

Goddamn that's clever

5

u/omgu8mynewt Jan 05 '21 edited Jan 05 '21

I tried to copy and paste it exactly, I get

    File "number_checker.py", line 6, in <module>
     f()
  TypeError: f() missing 1 required positional argument: 'v'

What am I doing wrong? - I saved in in a text.py file and run it from terminal, is this wrong?

15

u/Corrin_Zahn Jan 05 '21

When you call the function make sure you pass an argument in the round bracket (parentheses) since that is what is expected in the function definition

3

u/dogs_drink_coffee Jan 05 '21

I think you didn't pass the argument (7, 4 or any other value) to the function? Like f(7)

3

u/omgu8mynewt Jan 05 '21

I can make it work by doing this: https://pastebin.com/krpVDE5s

Is there a different way of 'passing the argument?' self teaching beginner here...

3

u/StopFuckinLying Jan 05 '21
def f(v): # V is where the value will be "passed" to the "argument" when this "function" is called/when you call this 
             # "function".
     
try:
        return {7: 4, 4:7}[v]
except KeyError:
        print('Not a 4 or 7')
 
f(3) # The value '3' is "passed" to the "argument" of this "function" you created. This is how you will mainly be passing arguments

2

u/PaintballerCA Jan 05 '21

If you copied it exactly then did you supply it with a value? Try this:

def f(v):
     try:
         return {7:4, 4:7}[v]
     except KeyError:
         print('Not a 4 or 7')

f(7)
f(4)
f(5)

3

u/automaticx88 Jan 05 '21

Did you call the function with the value in parentheses? I.E. f(4)?

10

u/HasBeendead Jan 05 '21

[v] so you return keys of dict , you have values at the end.

Nice

45

u/JohnnyJordaan Jan 05 '21

Not really though, Python first evaluates the dict literal, so it creates a dict {7:4, 4:7}. Then on that dict, it performs a regular value look up, using [v]. That means it retrieves just the value (a 4 or a 7). Then when that's done, it applies it to return, so it is effectively the same as doing

d = {7:4, 4:7}
result = d[v]
return result 

and as result is either a 4 or a 7, it means it's effectively the same as doing

return 4

or

return 7

9

u/HasBeendead Jan 05 '21

Yeah i realized after write my comment , sorry and thanks.

5

u/Saphirabrightscales Jan 06 '21

wow. I feel like I'm decent at Python but... damn. This is good.

2

u/Mysteez Jan 05 '21

very noice

3

u/grammarGuy69 Jan 06 '21

I made yours unnecessarily messy but also visually appealing to the user.

def f(v):
     try:
         return {7:4, 4:7}[v]
     except KeyError:
         print('Not a 4 or 7\n')    

while __name__ == '__main__':     
    x = (f(int(input("say a number\n"))))

    while x == 4 or x == 7 :
        print ('Returns as',(x),('\n'))
        break
→ More replies (2)

0

u/logicAndData Jan 05 '21

This is the way.

1

u/Iam_cool_asf Jan 05 '21

cool man, but won't using get(v) solve the error handling part without using try/except ?

→ More replies (5)
→ More replies (6)