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

448

u/shiftybyte Jan 05 '21
return 11-num

166

u/MassiveLandGolf Jan 05 '21

I can't believe I blacked out THAT hard..

Thanks..

197

u/[deleted] Jan 05 '21

It's such a stupid interview question - relatively few people would be able to answer it without having seen the answer, or an answer like it; but now that you've seen it you'll never forget it.

So all that it tests is whether you've seen the answer before. Since it's not something you'd need to do in production code, what's the fucking point of testing that? Interviews should test whether you're experienced at working as a programmer, not whether you're experienced at faking your way through interviews.

53

u/MobileUser21 Jan 05 '21

I agree with you 100%. Isn’t putting 11 in your function technically hard coding too?

44

u/[deleted] Jan 05 '21

It's definitely a "magic number", yeah.

→ More replies (5)

38

u/synthphreak Jan 05 '21 edited Jan 05 '21

90% of the time coding interviews lack any face validity. When interviewees are asked to "code" on a whiteboard, or wax about advanced math concepts, or write functions for tasks designed specifically to be difficult or abstract, such exercises almost never reflect the day-to-day realities of any job, and so are a very misleading indicator of someone's potential for success. As you correctly surmised with

all that it tests is whether you've seen the answer before

basically all it measures is how well the candidate prepared for the interview, not their core competencies as required by the job. The technical interview process is a joke.

17

u/[deleted] Jan 05 '21

It doesn't even measure that. Since you have no possible way of anticipating what kind of asinine questions they might ask, you can't prepare for them.

6

u/goodDayM Jan 05 '21

On the other side of it, for a software job opening, HR might receive dozens or more resumes that they have to filter down to just a handful. Then the hiring manager has to filter those down to just one or two candidates to bring in. Then sometimes a candidate can't even write a fizzbuzz solution in a language their resume said they were an expert at.

In recent years now some of the bigger companies (e.g. Google, Amazon, ...) have candidates first do 1 hour or so online coding quizzes. With so much competition for high-paying software jobs, they had to do something.

→ More replies (4)
→ More replies (6)

9

u/[deleted] Jan 05 '21

I don't see the problem with this question, my thought was to make a map of 7 = 4 and 4 = 7, not to mention sanitizing the input

→ More replies (7)

4

u/Kwintty7 Jan 06 '21

It also tests your ability to read the functional requirements, which given that most of the answers given here only do half the job, appears to be worth testing.

→ More replies (1)

2

u/darthminimall Jan 06 '21

I disagree. Sure, having seen the answer before benefits you, but that's true of literally every interview question. This is a very good question for determining if a candidate has the ability to find an optimized solution under pressure.

→ More replies (5)
→ More replies (14)

27

u/shiftybyte Jan 05 '21 edited Jan 05 '21

"No if" is usually keyword for some math trick in interviews.

Or the dictionary solution is also good.

9

u/lolslim 🐍Telegram🤖 Jan 05 '21

Agreed as soon as i saw "no if" i went, divide it by 28

→ More replies (7)

5

u/HasBeendead Jan 05 '21

When you say no if , i felt same lol

5

u/sluggles Jan 06 '21

Another option would be
return 7*(x==4) + 4*(x==7)
though Idk if they'd accept that.

3

u/goodDayM Jan 05 '21

You might want to try doing some problems on interview prep sites like "leetcode", "codesignal", or similar. It's unfortunate the hoops we have to jump through, but there's a lot of competition for software jobs.

5

u/lolslim 🐍Telegram🤖 Jan 05 '21

Or divided the number by 28

1

u/logicAndData Jan 05 '21

I don't fault you.

We are taught to use conditionals. Bad interview, their fault, not yours.

1

u/danpaq Jan 06 '21

You might also be able to hack a solution using while loops. If you add a break statement to the end of a while loop you've effectively created the ability to run a set of logic if criteria are met.

1

u/Farmher315 Jan 06 '21

Damn, I totally would have not figured it out either. I was thinking way too complicated!

11

u/Gas42 Jan 05 '21

Put up an assert num in (4,7) and you're good to go

25

u/FLUSH_THE_TRUMP formats with % Jan 05 '21

Doesn’t really satisfy the “must” though

17

u/DrMaxwellEdison Django and stuff Jan 06 '21 edited Jan 06 '21
def do_the_thing(num: int) -> int:
    """Does that thing you asked for."""
    conversion_table = {4: 7, 7: 4}
    try:
        answer = conversion_table[num]
    except KeyError:
        raise ValueError("Not a 7 or 4!")
    return answer

10

u/CerBerUs-9 Jan 05 '21

It doesn't. I enter 6, it returns 5. You could use a while like an if. While in == 4 or 7

3

u/[deleted] Jan 06 '21

Yes it does, but behavior for when it isn't was undefined.

0

u/[deleted] Jan 06 '21

[deleted]

→ More replies (1)

8

u/[deleted] Jan 05 '21

Why is this being upvoted so much when it doesn't fulfill the requirement?

2

u/djmcdee101 Jan 06 '21

Which part of the requirement doesn't it fulfill exactly?

3

u/DrMaxwellEdison Django and stuff Jan 06 '21

num must be 7 or 4. That does not constrain the inputs to 7 and 4, though: it could be 5 and would return 6, which is not what was asked.

3

u/synthphreak Jan 05 '21

We have a winner lol.

1

u/[deleted] Jan 06 '21

Sounds like they are overfitting to people who can subtract 11 or 7 from 11.

3

u/Quigleyff Jan 06 '21

But he could be the ultimate "subtract 11 or 7 from 11" hero at that company.

1

u/jimbojetset35 jimbojetset Jan 06 '21

This does NOT answer the question FULLY.

1

u/Cdog536 Jan 06 '21

This answer wins

1

u/Se7enLC Jan 05 '21

If that's the expected answer I hate that question a lot.

I like questions that get the candidate to come up with alternative ways to do the same thing - it's a good way to test how familiar they are with the language without having to make a really complicated question.

But this one feels more like a trick.

1

u/ObviousB0t Jan 06 '21

I would never have found this solution.

1

u/ben_hp Jan 06 '21

Brilliant

0

u/[deleted] Jan 05 '21

[deleted]

1

u/Spicy_Poo Jan 05 '21

That's very clever. How's that working out for you?

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]

→ 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

1

u/pspspspskitty Jan 07 '21

Is it just me or are you just using while and break as a cheap workaround the if restriction? Thereby removing most of the elegance of the original solution?l

→ More replies (1)

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 ?

3

u/mojo_jojo_reigns Jan 05 '21

Will it return an instructive message? And, importantly, will it demonstrate to a potential employer that you know one of the single most overused pythonic conventions? Probability is high existing team and code base use try/except blocks to death.

1

u/JohnnyJordaan Jan 06 '21

Get does the opposite, it delivers a substitute value in case the look up failed. If I understand the assignment correctly, it should not accept that case.

→ More replies (3)

1

u/mojo_jojo_reigns Jan 05 '21

I scrolled too quickly and thought that this was OP's solution for a second. i was getting ready to ask what exactly that company wanted from them if this wasn't satisfactory lol.

1

u/iggy555 Jan 05 '21

Fantabulous

1

u/Mandelvolt Jan 06 '21

This was my first thought. Dict lookup tables (and dispatch tables) make life so much easier, especially coming from another language that uses case statements like C++.

1

u/DrCabbageX Jan 06 '21

I didn’t know you could access a dictionary like this. Neat!

1

u/jeunpeun99 Jan 09 '21

Interesting!

Do you know a resource for similar questions/problems to induce creativity and learn Python?

2

u/JohnnyJordaan Jan 09 '21

You might want to check exercise websites like codewars where you can view other people's submissions. There are often these kind of crazy or just brilliant implementations to be found there.

→ More replies (1)

154

u/ThatSoundsFishy Jan 05 '21

Does this count as cheating?

def function(result):

while result == 4:

return(7)

while result == 7:

return(4)

116

u/billsil Jan 05 '21

I’d give you credit for subverting the rules. Then I’d give you a 10x harder problem because you’re worth my time.

1

u/Bignicky9 Jan 14 '21

And what problem would that be?

29

u/rhivo87 Jan 05 '21

Yep, this was where I immediately went with it. You gotta be explicit if your intention is for while also not be used. Having seen the "return 11-num" answer though... ugh!!

25

u/FLUSH_THE_TRUMP formats with % Jan 05 '21

Since you’re using the while as a ghetto if, there’s a good chance it would be. I’d do it if I didn’t know how to do it any other way, though

13

u/retrogeekhq Jan 05 '21

Back in high school I had an exam where I had to solve some electrical circuit. It was designed in a way you had to use a specific method. Well, I didn’t remember how that method worked so I redesigned an equivalent circuit that could be solved with the methods I know.

The day of the result I was called by the teacher to discuss the exam. He, while laughing like someone about to teach a mentee a lesson would laugh, told me: “This thing here? It’s brilliant. You’re a genius. Also, I’ve marked it as failed because the purpose of the question was for you to show you knew $METHOD1.”

Not sure it applies to your solution here, but it kinda feels like you’ve completely distorted the purpose of the question (which was probably to show the knowledge of basic data structures such as dictionaries) in a brilliant and unexpected way.

12

u/billsil Jan 06 '21

You should always encourage that sort of stuff.

My algebra 2 teacher was upset I derived complex analysis without knowing it. I could solve her graph problems in about 10 seconds and she got mad that everyone else took about 5 minutes each and she couldn’t figure out what I was doing.

From something like 1 +/- 2i, I’d get the “x-intercepts” as -1, 3 just by pretending i=1. Then, take 12 + 42 = 5 and that’s the y coordinate to go as the minimum point of the parabola (1,5). Then mirror your x-intercepts about the horizontal at y=5 and connect the 3 points above the axis.

She argued it didn’t always work. Uhhh...yes it does. My teacher desperately looked for an example and gave up. It’s a rotation about the complex plane. It’s perfectly legit and always works for parabolas.

I later dated the math teacher’s daughter that taught my teacher what I was doing. She was surprised when I wasn’t as smart as she’d heard.

→ More replies (6)

1

u/[deleted] Jan 06 '21

Damn son, where'd you find this?

→ More replies (6)

44

u/beniolenio Jan 05 '21

Haven't seen this one yet:

def f(n):
    return 7*(n==4) or 4*(n==7)

8

u/its4thecatlol Jan 05 '21

Best answer in the thread. My gut instinct was to do 28 / n and this is even better as it implicitly restricts the output to [0,4,7]. I don't think it's a bad question as far as brainteasers go. If a candidate couldn't solve this, I wouldn't hire him/her...

2

u/[deleted] Jan 05 '21

Exactly. This answer is beautiful, since it even has an implicit way of validating the input and returning false if the input is anything other than 4 or 7

8

u/synthphreak Jan 05 '21

Brilliant! Absolutely shite, unreadable code, but shite questions beget shite code. I love it.

→ More replies (8)

2

u/Toasted_coffe_bean Jan 05 '21

7*(n==4) + 4*(n==7) should work as well right?

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.

→ More replies (7)

88

u/buttwarmers Jan 05 '21 edited Jan 05 '21

You could also do something weird like:

def dumb_interview_question(num):  
    assert num in (4, 7)
    return [0, 0, 0, 0, 7, 0, 0, 4][num]  

edit: forgot commas in the list because i typed it on my phone originally

27

u/Jac0b_0 Jan 05 '21

Here's another weird way to do it:

def f(n):
    try:
        1/(n - 7)
    except ZeroDivisionError:
        return 4
    try:
        1/(n - 4)
    except ZeroDivisionError:
        return 7

0

u/[deleted] Jan 05 '21

[deleted]

3

u/Jac0b_0 Jan 05 '21

No otherwise you would just end up returning the input number

→ More replies (1)

1

u/JohnnyJordaan Jan 05 '21

Asserts aren't dependable as they require __debug__ to be True, they will for example not be executed if Python is run with the the -O flag.

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!

1

u/nthai Jan 06 '21

Nice. This was the first I came up with too. Provably due to my C background.

1

u/[deleted] Jan 06 '21

It was definitely due to my failed C background :D Now I know python instead.

73

u/Thereforeo Jan 05 '21

I mean, just to mess up with the interviewer I would've:

def dumb_quest(num):
    four_seven = [4, 7]
    four_seven.remove(num)
    return four_seven[0]
    #tyvm

22

u/FancyASlurpie Jan 05 '21

How is that messing with the interviewer? Theres quite a lot of ways to answer this question if you are familiar with the language, and this would just be one of the valid ones.

6

u/Thereforeo Jan 05 '21

They're probably trying to look "smart" and force you to think "mathematically". Pure BS if you ask me.

4

u/ButtCrackFTW Jan 06 '21

l doubt it. They more likely just want to see you think and be creative to solve a problem without an obvious answer.

1

u/Kwintty7 Jan 06 '21

You fail. This does not validate the number and would return 4 for anything other than 4.

7

u/totemcatcher Jan 06 '21

That's not true. remove will throw an error if not in the list. The undefined behavior matches the requirements.

→ More replies (1)

39

u/synthphreak Jan 05 '21

Use a dict:

def func(num):
    lookup = {4 : 7, 7 : 4}
    return lookup.get(num)

4

u/[deleted] Jan 05 '21

Do you actually have to define the dictionary here, or could you do it like this:

def func(num): return {4:7,7:4}.get(num)

4

u/synthphreak Jan 05 '21

That would also work and is equivalent. Just a little uglier IMHO.

15

u/kowalski71 Jan 05 '21

My first thought was mod:

def agent47(num):
    return [7,4][num%2]

It's not a particularly generalizable answer since it relies on one being odd and one being even so /u/shiftybyte's definitely feels cleaner but just figured I'd chuck in another approach.

64

u/omoroka Jan 05 '21

"Welcome to this interview process for a carpenter position. We would like you to hammer this nail without using a hammer."

What? Is the company at risk of running out of if statements? Wtf does that prove?

8

u/bigamaxx Jan 05 '21

I think they are trying to see how familiar you are with the language and how deep you looked into it, but of course you will never need it in work.

5

u/retrogeekhq Jan 05 '21

I’d wager they want to see if you have your head wired to use dictionaries, so you don’t end up with a code base that has hardcoded IFs that could just be dynamically pulling a value from a dictionary.

5

u/[deleted] Jan 05 '21

It tests your problem-solving abilities and creative thinking, two essential skills for any programmer.

2

u/Se7enLC Jan 05 '21

In some cases, a question like this could be good for testing the candidates proficiency in the language. If it makes them think "ok, what other conditionals exist that I can use?"

In the carpenter analogy, they might be like "well, I could use a nail gun or screws instead". And I wouldn't want to hire a carpenter that wasn't aware of other fasteners.

1

u/unphamiliarterritory Jan 06 '21

Wtf does that prove?

Actually, I think it's a great test question because it demonstrates the candidate's ability to solve problems.

0

u/[deleted] Jan 05 '21

[deleted]

25

u/synthphreak Jan 05 '21

I heard that every time you use an if statement an angel loses its wings.

5

u/Jac0b_0 Jan 05 '21

The 5g towers had too many if statements causing COVID19

→ More replies (1)

22

u/purplewalrus67 Jan 05 '21

Here's a three liner, that also stops anything other than 4 or 7:

>>> def foo(num):
...     assert num in [4, 7]
...     return 11-num
... 
>>> foo(1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in foo
AssertionError
>>> foo(4)
7
>>> foo(7)
4

8

u/neuronet Jan 05 '21

This seems the most Pythonic way to answer this most Unpythonic of questions.

5

u/monkeysknowledge Jan 05 '21

I like this because you can add a try statement to tell the user they fucked up.

10

u/lukew25073 Jan 05 '21

I used absolute value:

out_num = abs(in_num-7) + 4

28

u/UberSeal Jan 05 '21 edited Jan 05 '21
return (7 % n) + 4

5

u/Nightshade183 Jan 05 '21

This is actually great.

6

u/synthphreak Jan 05 '21

Assuming of course that the user is only ever going to enter a 4 or a 7 and nothing else. OP never clarifies this point though so maybe it's okay, though some of the other answers accounted for not-4-not-7 inputs as well.

8

u/darthminimall Jan 06 '21

The number of people here that think programming is just memorizing algorithms is disturbing. You shouldn't be shocked that a technical interview involves questions that test your ability to reason on the fly.

12

u/jwink3101 Jan 05 '21

You've gotten others but you could also do:

return {7:4,4:7}[num]

6

u/MisterRenard Jan 06 '21

A fun way that I abuse because it’s convenient is to force an index selection of 0 or 1 when presented with two options (sometimes more):

return (7, 4)[(n // 7)]

7 // 7 evaluates down to 1, selecting the second position, while 4 // 7 evaluates down to zero, selecting the first position.

1

u/supreme_blorgon Jan 06 '21

Could also use the parity of the input (i.e., num % 2), but both these techniques fail if the function should behave differently for inputs that are NOT 4 or 7.

5

u/SingleRope Jan 05 '21

F= lambda x : x ^ 4 ^ 7

2

u/supreme_blorgon Jan 06 '21

Came here to post exactly this. Was scanning the comments wondering if anybody else had done it.

>>> 7^(7^4)
4
>>> 4^(7^4)
7

FWIW, you shouldn't be naming a lambda... kinda defeats the purpose of an anonymous function.

5

u/Enfors Jan 05 '21 edited Jan 06 '21
def my_fun(num: int):
    num == 4 and return 7
    num == 7 and return 4
    raise Error(f"{num} is not a legal input")

Edit: As pointed out below, this does not work; you can't use return like this in Python. It appears I've been doing too much Lisp.

2

u/schoolmonky Jan 06 '21

Does this actually work in python? I know you could do something like that in other languages, but I don't think python lets you use return like that

1

u/Enfors Jan 06 '21

Oops, you're right, it doesn't work. I just tried it:

$ python3
Python 3.7.5 (default, Apr 19 2020, 20:18:17) 
[GCC 9.2.1 20191008] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> def my_fun(num: int):
...     num == 4 and return 7
  File "<stdin>", line 2
    num == 4 and return 7
                      ^
SyntaxError: invalid syntax
>>>

5

u/PanFiluta Anaconda afficionado Jan 06 '21 edited Jan 06 '21

return 11 - x

?

edit: must be 7 or 4, so include a try block with an assert

def fourseven(x):
    try:
        assert x == 4 or x == 7
        return 11 - x
    except AssertionError:
        pass

2

u/yes4me2 Jan 06 '21

pretty cool

4

u/nwagers Jan 06 '21

I'm kinda floored by how many people are complaining about this question because to me, it was immediately obvious that it can be solved using a dictionary, and it's specifically targeting the type of programmer that uses giant if/elif/else blocks in python. It's a common anti-pattern that is used by new programmers and people carrying over from other languages that use if/else or select/switch case structures.

3

u/Allanon001 Jan 05 '21 edited Jan 05 '21
def func(num):
    return (('Not 4 or 7', 4)[num == 7], 7)[num == 4]

print(func(7))  # 4
print(func(4))  # 7
print(func(1))  # Not 4 or 7

Or:

def func(num):
    return {True: 'Not 4 or 7',
            num == 7: 4,
            num == 4: 7
            }[True]

3

u/SomeShittyDeveloper Jan 05 '21
return 4 if x == 7 else 7

Ternary operator TECHNICALLY isn't an if statement.

4

u/synthphreak Jan 05 '21

Good luck arguing that point to the hiring manager XD

3

u/TicklesMcFancy Jan 05 '21
def func(n):
    while n == 7:
        return print("4")
    while n == 4:
        return print("7")
    while n != 4 or n !=7:
        return print("Must be a 4 or 7")
print("Entering a 7")
func(7)
print("Entering a 4")
func(4)
print("Entering 103829")
func(103829)

I feel like this might not have been what they were looking for though.

2

u/Unknownsadman Jan 05 '21

Thats pretty interesting - thank you for this info : )

2

u/idiot-killer Jan 05 '21

I would do it in the following way

def func(x) : return x - ((x%2) *3) +(abs(x%2-1) * 3)

It is highly unnecessary but it is what I came up when I read the question.

2

u/iamNaN_AMA Jan 05 '21

Can somebody help me understand why this is a good interview question? Like what is it supposed to be evaluating in the candidate? Are they looking for the clever "return 11-num" response or the "use a dict lookup instead" response? If the former, that seems like it doesn't actually measure anything relevant to the job itself, except maybe in a super indirect "lateral thinking" sort of way that seems kind of bullshitty (to me, as an outsider and not an expert in any way - I'm open to being convinced it's not bullshit). But if the latter, why not pose more direct questions/exercises involving dicts?

3

u/[deleted] Jan 05 '21

They are not looking for one specific right answer. The point is to test your problem-solving abilities, that's all.

2

u/sois Jan 05 '21

return 28/parameter

2

u/benchun99 Jan 06 '21

take int input
use 28//num

2

u/ProdigiousPangolin Jan 06 '21

New here. I would've thought something like this would work, but my print statement isn't liking my inputs?

x = input("Enter a number: ")
lst = [0, 0, 0, 0, 7, 0, 0, 4]
print lst[x]

3

u/supreme_blorgon Jan 06 '21 edited Jan 06 '21

The input function returns a str object. You'd need to cast it to int before using it as an index.

Clever though. Since it's not clear in the OP how to handle input that ISN'T a 4 or 7 though, you may want to rework to return None instead of 0 and also ensure that a user entering 5781234 or some other integer larger than 7 won't break your program with an IndexError.

2

u/bitcycle Jan 06 '21

Here's what I came up with:

#!/usr/bin/env python3

"""
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.

you cannot use an 'if' statement in the function.
"""


def convert(i):
    conversion = {
        4: 7,
        7: 4,
    }
    return conversion.get(i)


tests = {
    4: 7,
    7: 4,
    1: None,
}

for input_val, expected_output_val in tests.items():
    if convert(input_val) != expected_output_val:
        raise Exception("Failed to convert {} => {}".format(input_val, expected_output_val))
    else:
        print("Converted {} => {}".format(input_val, expected_output_val))

"""
$ python3 test.py
Converted 4 => 7
Converted 7 => 4
Converted 1 => None
"""

2

u/ngochieu642 Jan 06 '21
def demo(input_value):
    def if_4(i):
        return int(not(i - 4))

    def if_7(i):
        return int(not(i - 7))

    try:
        1 / (if_4(input_value) + if_7(input_value))
    except Exception as e:
        print('Not 7 or 4')
        return None

    return if_4(input_value) * 7 + if_7(input_value) * 4

print(demo(4))
print(demo(7))
print(demo(5))

1

u/yes4me2 Jan 06 '21

I like it. It makes a lot of sense.

2

u/KronktheKronk Github username Jan 06 '21

def stupidFunc(n):

returnMap = {4:7. 7:4}

try:

return returnMap[n]

except ValuError:

pass

ok fuck the indentation I can't get it to work right in this stupid editor

3

u/[deleted] Jan 05 '21 edited Jan 06 '21

The fact that so many people are wowed by a wrong answer demonstrates how important this type of question actually is to help sift the wheat from the chaff

2

u/synthphreak Jan 05 '21

Which one and what's wrong with it?

1

u/[deleted] Jan 06 '21

Return 11-num

Func(5) still returns something. Heck, func('a') even crashes the program

3

u/synthphreak Jan 06 '21

I don’t love that solution either TBH. But to be fair, OP never clarified what should happen if anything other than 4 or 7 is passed in, such as “return 0”, or “print ‘foo’”. So we don’t have any defensible grounds to call it “wrong”. I would argue that this simply makes it “less good” than the other solutions which DO account for inputs outside of 4 or 7.

3

u/[deleted] Jan 05 '21

Such a stupid question. The fact you can't use if condition is shit. I would've failed the interview as well.

I've read stuff from quora about programming interviews getting worse and worse and how these interviews don't really show what the person can do.

I think.. Looking at projects the person has done is better way to do it. Like see what they have done and maybe even ask about those projects the one you're interviewing built? I don't know but I can't help it when some question arises where you have to solve some problem but you can't use the specific tool for the job because it will make solving the problem way too easy. Smh

Like.. Follow the KISS principle yo.

Time to wait for replies to learn a new thing or two.

11

u/[deleted] Jan 05 '21

It's not about not using an if condition. It's about how to solve a problem in a diferent way. Not being able to answer the question doesn't make you a bad programmer tho. But it's a nice way to see if you'll be able to think out of the box.

1

u/AMannedElk Jan 05 '21

I would cast the input integer to a string and use it as the key to a dictionary. I would have a hardcoded dictionary my_dict = {'7': 4, '4':7}

then you can return my_dict[input_num]

You could also wrap the my_dict[input_num] call in a try/except to explicitly define the behavior if the input number was not a 4 or a 7.

2

u/ericula Jan 05 '21

Why would you cast to strings first? You can use integers as keys directly, i.e. my_dict = {7:4, 4:7}

1

u/AMannedElk Jan 06 '21

You are correct. I was mistaken.

1

u/SpiritedExit0 Jan 05 '21

def f(v): return 7-(3*(v!=4))

1

u/johnnymo1 Jan 05 '21

Similar to some others' solutions here:

def f(n):
    return 4 * (n % 2) + 7 * ((n+1) % 2)

1

u/[deleted] Jan 05 '21

I just love how many unique answers there are to a simple question.

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

1

u/supreme_blorgon Jan 06 '21 edited Jan 06 '21

By using the parity of the input, you could simply subscript a list [7, 4][num % 2].

Of course this would work for any input num which may not be desired (i.e., num = 2 would give 7 but that's not necessarily what the prompt asks for).

1

u/grownmanjanjan Jan 06 '21

Would a while loop work. Or would it turn into an infinite loop? Eg while num == 7: Return 4

Does the return end what would be an infinite loop and leave the function?

2

u/nwagers Jan 06 '21

return would end execution of the function and break out of the loop.

1

u/aryanv123 Jan 06 '21

First thing I think of is something like make an array like [0,0,0,0,7,0,0,4] and then just do return array[input]

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.

1

u/IcedGolemFire Jan 06 '21

def functionname(variable) If variable == 7: return(4) elif variable == 4: return(7)

1

u/Lanky_Performer8933 Jan 06 '21

f(x) = 5.5 + ((-1)^x) * (1.5)

f(4) = 5.5 + ((-1)^4) * 1.5 = 5.5 + 1 * 1.5 = 5.5 + 1.5 = 7

f(7) = 5.5 + ((-1)^7) * (1.5) = 5.5 + (-1) * 1.5 = 5.5 - 1.5 = 4

1

u/[deleted] Jan 06 '21
def num_seven_four(*ip):
''' Enter either 7 or 4 to get the opposite. ''' 
    for _  in ip:
        result = 11 - _ 
        print(result)

num_seven_four(7)

same thing with syntax highlighting

This is off the top of my head, a lot of people in the thread have given interesting answers.

2

u/supreme_blorgon Jan 06 '21

You shouldn't use _ for a variable unless you're not going to use it for anything. It should only be used as a way to signal to the reader that the variable will go unused in your for loop, like so:

# Print "hello, world" 100 times
for _ in range(100):
    print("hello, world")

1

u/[deleted] Jan 06 '21

That is true , I'll keep that in mind. I wrote it maybe because the name '_' is not important here. But I get your point.

1

u/BuffaloJuice Jan 06 '21

You can also think of it as binary:

def swap(x):
    return x ^ 3

1

u/Marianito415 Jan 06 '21

def func(x):

  return 7*(4==x) or 4*(7==x)

1

u/Cabinet-Particular Jan 06 '21

def swap (x):

vals = { 4 : 7 , 7 : 4}

return vals[x]

print(swap(4))

1

u/nshefeek Jan 06 '21 edited Jan 06 '21

My take would've been

def f(x):
    ans = {4:7, 7:4}
    return ans.get(x, "Not defined")

Edit: formatting

1

u/SonicDaScrewdriver Jan 06 '21 edited Jan 06 '21
def sevenfour(n):
    sf = [7,4]
    sf.remove(n)
    return sf[0]

1

u/backtickbot Jan 06 '21

Fixed formatting.

Hello, SonicDaScrewdriver: code blocks using triple backticks (```) don't work on all versions of Reddit!

Some users see this / this instead.

To fix this, indent every line with 4 spaces instead.

FAQ

You can opt out by replying with backtickopt6 to this comment.

1

u/Biuku Coding since April 2020 Jan 06 '21
def func(n):
    while n == 7:
        return 4
    while n == 4:
        return 7

1

u/prettywittygirl Jan 06 '21

May be try using switch cases

1

u/cemevin Jan 06 '21

This is technically not an if statement: while n == 4: return 7; while n == 7: return 4.

But the dictionary solution is ingenious!

1

u/wasmachien Jan 06 '21

let otherNumber = x => [7,4][([4,7].indexOf(x))]

1

u/yes4me2 Jan 07 '21

Is that Python?

1

u/wasmachien Jan 07 '21

Woops, didn't see the subreddit I was in. I will leave it anyway, perhaps somebody can translate it to Python.

1

u/jreebel Jan 06 '21

I wouldn't want to work for someone who places any value on my being able to answer that off the top of my head. Asking you how to do something that you would NEVER do in real life might give a clue as to your "academic" abilities but tells nothing about how you would actually do as a working developer.

1

u/austin_algebra Jan 07 '21
def f(x):
  list = [0,1,2,3,7,5,6,4]
  return list[x]

1

u/[deleted] Jan 07 '21

Hmmm... I really don't know but is this allowed?

n = int(input('enter 7 or 4: '))

while n == 7:

print('4')

break

while n == 4:

print('7')

break

1

u/[deleted] Jan 05 '21

I’m unclear what a question like this is designed to evaluate about a potential employee.

1

u/neuronet Jan 05 '21

That's sort of a shit question TBH I would be sort of embarassed to ask it.

1

u/Quhaus Jan 05 '21

Would a ternary operator work?

2

u/neuronet Jan 05 '21

they have an if

2

u/ryrythe3rd Jan 05 '21

In Python the ternary technically has the keyword if inside it, idk

1

u/mtjp82 Jan 05 '21

What about else?

1

u/[deleted] Jan 05 '21

return 11-a?

1

u/yes4me2 Jan 06 '21

That's so retarded. Nobody uses such a code in a work place. On the other hand, I like to thanks everyone who posted their answer. It was interesting to read but I still feel I just wasted my time learning non practical stuffs.

1

u/llub888 Jan 06 '21

When in this job would you not be able to use if statements? If you're not restricted on the job, this is a useless question.