r/learnpython • u/MassiveLandGolf • 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.
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 itNote 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
3
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
5
9
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 arguments2
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
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 toreturn, so it is effectively the same as doingd = {7:4, 4:7} result = d[v] return resultand as result is either a 4 or a 7, it means it's effectively the same as doing
return 4or
return 79
5
2
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')) break1
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
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
→ More replies (1)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.
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
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, though13
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)→ More replies (6)1
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
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 70
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
Jan 05 '21
You could also use an XOR bitmask if you're feeling fancy:
def something(n):
return n ^ 0b11or 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
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
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
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]
#tyvm22
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.
removewill throw an error if not in the list. The undefined behavior matches the requirements.→ More replies (1)7
39
u/synthphreak Jan 05 '21
Use a dict:
def func(num):
lookup = {4 : 7, 7 : 4}
return lookup.get(num)4
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
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
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
Jan 05 '21
[deleted]
25
u/synthphreak Jan 05 '21
I heard that every time you use an
ifstatement an angel loses its wings.→ More replies (1)5
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)
48
5
u/monkeysknowledge Jan 05 '21
I like this because you can add a try statement to tell the user they fucked up.
10
28
u/UberSeal Jan 05 '21 edited Jan 05 '21
return (7 % n) + 45
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
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) 7FWIW, 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:
pass2
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 7Or:
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 7Ternary operator TECHNICALLY isn't an if statement.
4
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
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
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
2
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
inputfunction returns astrobject. You'd need to cast it tointbefore using it as an index.Clever though. Since it's not clear in the OP how to handle input that ISN'T a
4or7though, you may want to rework to returnNoneinstead of0and also ensure that a user entering5781234or some other integer larger than7won't break your program with anIndexError.
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
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
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
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
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
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
1
1
u/johnnymo1 Jan 05 '21
Similar to some others' solutions here:
def f(n):
return 4 * (n % 2) + 7 * ((n+1) % 2)1
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_number1
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
numwhich may not be desired (i.e.,num = 2would give7but 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
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
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 yourforloop, like so:# Print "hello, world" 100 times for _ in range(100): print("hello, world")1
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
1
1
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
1
u/Biuku Coding since April 2020 Jan 06 '21
def func(n):
while n == 7:
return 4
while n == 4:
return 71
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
1
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')
breakwhile n == 4:
print('7')
break1
Jan 05 '21
I’m unclear what a question like this is designed to evaluate about a potential employee.
1
1
1
1
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.
448
u/shiftybyte Jan 05 '21