10 ms·
Interview gone wrong
- taxman22 2y agoAny time you use language specific tricks in an interview, you’re probably going to confuse your interviewer and not do well.
- necovek 2y agoI disagree: if you are demonstrating your mastery of a language (and with Python, these things are important: using appropriate syntax is the difference between dog slow code and fast code), you should use idiomatic patterns like the above. Another of Python features is a great REPL: when unsure or confused by an interviewer, I'd just fire python from shell and type in 'x' == 'x' == 'x' to confirm and demonstrate it does the right thing (or write tests). Obviously, the interviewer should be careful not to sidetrack the candidate much, and let them do the work and attempt to help only if things don't work out.
- mozman 2y agoIn the real world you iterate, profile, and optimize
- necovek 2y agoI am definitely a subscriber to not doing premature optimization, but in Python, there is a huge difference between found = searched_key in list(large_dict) vs found = searched_key in large_dict But also compare: searched_key in large_dict.keys() # O(1) and searched_value in large_dict.values() # O(n)
- carlmr 2y agoSo much this. Write code that you can reasonably expect to not be slow af, while not sacrificing readability. Then profile and optimize if necessary.
- nerdponx 2y agoIn this case the candidate evidently didn't understand it either, but was repeating a pattern they had seen before, which IMO is a form of anti-mastery: don't do things that you don't understand, especially when you're supposed to be demonstrating your skill and understanding.
- necovek 2y agoHaving a candidate understand all of the edge cases of a language syntax is a very high bar to clear: there is a lot of programmer between a "master" and "anti-master". I've used Python for 20+ years, and while I'd confidently use a == b == c or 1 < a < 10, I didn't know the specifics and wouldn't use it in cases like 10 > a < 8 (or really, any other case chaining supports). I believe myself to be an expert at Python and I'll explain differences between different loop types (while/for, ranges/iterators/generators, list comprehensions, functools, external C libraries like pandas or numpy), I think I wouldn't be confused only because I am aware I don't know the details and have a quick way to prove it works.
- nerdponx 2y agoMaybe I interpreted the article differently than you did. I got the impression that the candidate was repeating the x == y == z pattern because they'd seen it in other people's code and was pretty sure it worked, not because they knew about comparison chaining. At minimum I'd expect a candidate to be able to clarify that (x == y) == z is not the same thing, not just "idk it works whenever I do it". My reaction to that was: at some point, you do need to at least be able to reason about your own code. In a more generous light, yes, I agree with everything you wrote. The precise details of comparison chaining are out of scope and I'm sure that most Python developers (myself included) don't know or remember them.
- necovek 2y agoI agree that anyone (including an obviously juniorish candidate) using it should be able to explain it to an extent, but maybe not if you confidently and wrongly claim it doesn't work as an interviewer :)
- sgarland 2y agoThis is my opinion as well, but unfortunately isn’t always held by others. I once interviewed and by dint of knowing Python’s itertools module, absolutely destroyed the interviewer’s questions that they clearly thought would take some time to do. I was told later that while I “obviously knew Python quite well, it didn’t give a good signal for my capabilities.”
- carlmr 2y ago>I once interviewed and by dint of knowing Python’s itertools module, absolutely destroyed the interviewer’s questions that they clearly thought would take some time to do. If I see such a situation I usually ask the interviewer whether they want a concise solution using libraries or they want to see how I would do this if I had to do it from scratch. Or I just offer both, I show that I can do it, but that I know it would be easier to do with x. I think this is a great opportunity to show you're a good communicator as well as a problem solver.
- sgarland 2y agoFair point.
- throwaway313373 2y agoBut it's not a "trick", it's just a normal Python code. I don't think that anyone who main programs in Python would perceive it as some kind of cool/unusual trick and not just normal code.
- phrenq 2y agoI suspect the interviewer would have likely been fine if they’d been able to explain chained comparisons and how they work. I would probably consider the interviewer using them without understanding them to be a negative signal.
- recursive 2y agoIf you're used to python, you wouldn't consider it to be a trick. If you're giving interviews, and evaluating code in a language you don't know, don't be so confident it's wrong. Ask the candidate how it works.
- nerdponx 2y agoIn this case the candidate also didn't know.
- ball_of_lint 2y agoI've used python for ~2y now and I'd balk at and rewrite this statement, considering it unclear at best.
- recursive 2y agoThat's an entirely reasonable point of view. The important part here is that there are a substantial fraction of python developers that don't share your sentiment.
- Waterluvian 2y ago“Language specific tricks” are the entire value proposition of there being more than one language.
- Der_Einzige 2y agoMy usage of "yield" (alongside knowledge of "prange" from numba) in an interview instead of return has sealed the deal on a 200K offer (ML role circa 2020). "Confusing" the interviewer is a totally valid strategy! It's the only strategy when python async is involved!
- jyounker 2y agoIt's not a trick though. It's normal Python code. It's so common that you don't even think about it. It's just how equality comparisons work in the language.
- Kim_Bruning 2y agoThis mirrors mathematical notation for things like ranges or equality checks 5 < x <= 25 x == y == 10
- murderfs 2y agoUnfortunately, it's more permissive than mathematical notation: `3 > 1 < 2` evaluates to True.
- solveit 2y agoI think mathematicians looking at that expression would curl their lips in mild disgust, but also evaluate it to True.
- throwaway313373 2y agoI can think of some more interesting examples when it violates intuition gained from mathematical notation. When looking at `a == b == c` we naturally assume that not only `a == b` and `b == c` but also `a == c` because equality is assumed to be transitive. The problem is that in Python we can make `==` operator to do literally whatever we want, so in Python `==` doesn't have to be transitive. You may argue that no reasonable person would define equality in such way that is not transitive. To which I would reply that approximate comparison of floating point numbers looks perfectly reasonable to me. EPSILON = 10**-9 class Foo: def __eq__(self, other): return other.bar - EPSILON <= self.bar <= other.bar + EPSILON
- Kim_Bruning 2y agoI love the fact that you defined Foo.__eq__ by means of a chaining comparison!
- jyounker 2y agoAs someone who trained in mathematics, I would 100% say that mathematicians would evaluate it as true. It's not the cleanest way to write it, but intent is clear.
- mlinhares 2y agoStopped judging candidates on "style" due to stuff like this. I only comment if the code doesn't work, if it works i don't really bother to correct code style or provide feedback on it. 45 minutes interviews aren't really the place to evaluate this.
- pavel_lishin 2y agoIt sounds like the author wasn't nitpicking style - they thought the code literally wouldn't work. (But, the intent on the interviewee's part was definitely clear - I'd definitely let this pass.)
- Izkata 2y agoThe blog itself isn't clear, and I think that's confusing some of the people here: > The candidate this time was programming in python But the code blocks aren't in python. But in the paragraph afterwards they capitalize "True" which is a python thing. Then afterwards mention they're using javascript as their reference, which uses "true" instead and the code blocks could be javascript. It feels like the author has more language confusion going on than just this one feature of python.
- mlinhares 2y agoThat's why i put "style" in quotes, the interviewer didn't know about the feature but still decided it was "wrong" or "ugly" even though the code works.
- vdvsvwvwvwvwv 2y agoLinters are for this. You need to detect if someone is humble and smart enough to fit in to how you do things as a team, whatever that is. Not reject someone for not hitting a style guide on a piece of paper tucked behind a hidden secret door. (As I was once!)
- fijiaarone 2y ago[flagged]
- Buttons840 2y agoPython evaluates `2 == 2 == 2` to true. JavaScript evaluates the same to false. Somehow we've decided that Python is the weird one it seems.
- pcthrowaway 2y ago1 == 1 == 1 is actually true in Javascript due to type coercion You're probably thinking `1 === 1 === 1` which is indeed false
- dartharva 2y agoI tried 2 == 2 == 2 in my browser's (Chrome) console and it evaluated to false.
- Buttons840 2y agoI stealth edited my post. Sorry.
- throwaway313373 2y agoTo be fair, there are edge cases [0] when it does look weird. [0] https://github.com/satwikkansal/wtfpython?tab=readme-ov-file#-be-careful-with-chained-operations https://github.com/satwikkansal/wtfpython?tab=readme-ov-file...
- recursive 2y agoNot in my browser console. (but it's true for a different reason)
- zitterbewegung 2y agoI'm confused about this blog post. Python is mostly C inspired but actually more pseudocode inspired (which helps its popularity) which is why chained expressions exist. Also, why would you conduct an interview in a language where even if you don't know the syntax (and this is obscure) you could have looked it up or disallowed the interview to be done in Python? I think the due diligence with this issue is more to the interviewer than Python.
- whack 2y ago> Also, why would you conduct an interview in a language where even if you don't know the syntax (and this is obscure) you could have looked it up or disallowed the interview to be done in Python? The norm in most of my interviews has been that candidates can solve coding problems in whatever language they are most comfortable with. For most languages like Python etc, it would be a mistake to reject a candidate just because they don't have experience with that specific language.
- userbinator 2y agoThe norm in most of my interviews has been that candidates can solve coding problems in whatever language they are most comfortable with. I assume they've already filtered out candidates whose "most comfortable language" isn't the one they're hiring for, or they're going to have a difficult time when they come across the one who wants to use APL or x86 Asm.
- titanomachy 2y agoI always interview for generalist jobs in python, but most jobs I’ve done use other languages.
- lvturner 2y agoI heard a tale of a candidate white boarding in an obscure language (in a bit of an attempt to hide a deficiency), unfortunately for the candidate the interviewer happened to be well versed in the language and saw right through the charade.
- throwaway313373 2y agoI don't know why didn't the candidate just explain to the interviewer what chain expressions are.
- Buttons840 2y agoSounds like he didn't know the details, but had seen this pattern in Python code and knew it worked. When asked, he was confused about the exact details of why it worked.
- tasty_freeze 2y agoThe candidate was writing an accounting program in COBOL and he wrote "ADD 2 TO SUM.". None of the handful of languages I kind of know support that syntax. It turns out that COBOL actually supports this nonsense. I explained to the candidate that when he is writing valid COBOL syntax, it is confusing to people who don't know COBOL and he agreed. This is a fail for the interviewer, not the interviewee, nor for Python.
- Buttons840 2y agoWhy did the author consider this an "interview gone wrong"? What was "wrong" about?
- necovek 2y agoInterviewer made a mistake and confused/sidetracked a candidate in a short interview.
- Buttons840 2y agoThe interviewer made no mistake though, they made an observation; they were confused by the boolean expression. The candidate said they understood the interviewers concerns and was also confused, and didn't have an immediate answer. This is all normal and healthy, and something you'd commonly see in healthy and competent development teams. The only thing I see that's wrong is that the interviewer thinks something went wrong.
- necovek 2y agoMistake: > ...the statement even though logical, is not technically right because if we start from the left cell[0][0] == cell[1][1] would evaluate to True and then True == cell[2][2] would evaluate to False given that the cell contains a char. Interviewer seemed confident ("is not technically right") which confused the candidate: > I told the candidate about the same and he agreed but he was confused at the same time Candidates are already in a high stress situation, you don't want to add to it unless you really know what you are doing (i.e. you are specifically looking for deep language mastery). Interviewer has correctly realized they've done this and learned from it: kudos to them even if too late for this candidate :)
- wiseowise 2y agoInterviewer made a mistake, stop rationalizing.
- Buttons840 2y ago
- int_19h 2y agoIn this respect, Python makes a lot more sense since that is how you'd normally write such an equality in math, and generally how people chain them: A=B=C means A=B and B=C. Part of the problem here is that we treat true/false as "just another value" in programming, and thus the usual operators are used to compare them. In math notation, if you wanted to compare the result of comparison A=B to a Boolean value C, you'd normally write something like (A=B)≡C, using different operators for equality and equivalence. Interestingly, programming languages haven't always treated Booleans in this way. If you look at ALGOL 60, it starts by cleanly separating expressions into arithmetic and logical ones, and defines completely different sets of operators for each (the reference language also uses = for numeric comparisons and ≡ for Booleans; and boolean inequality is, of course, just XOR).
- analog31 2y agoIndeed, and likewise, I think Pascal would have thrown a compile-time error due to a type mismatch.
- throwaway313373 2y agoI think that the main issue here is not treating true/false as values but allowing them to be implicitly converted or compared to numbers with the assumption that true equals 1 and false equals 0. I think that Rust got this right. It doesn't allow you to add integer to boolean or multiply boolean by float etc, because it is unclear what does it even mean mathematically. Also, most languages implicitly assume that any value of any type is either "truthy" or "falsy" thus you can do something like `while(1) { do_stuff() }`. Rust doesn't allow this BS, `if` and `while` expect a boolean so you have to provide a boolean.
- flakes 2y agoA lot of languages have no boolean primitive to begin with. Often in older languages, the values for `true` and `false` are aliases for `0` and `1` respectively. Perl and earlier versions of C, Python, and JavaScript are notable. Perl is probably the most awkward due to context-sensitive casting. e.g. the string `"0"` in a boolean context evaluates as an integer, and the boolean interpretation for `0` is false.
- encomiast 2y agoI know the point of the piece is the python syntax here, but I got stuck on: "judge things like code quality / speed / conciseness etc." Do people generally write concise code on right off the bat when confronted with a new problem? I've always taken the same approach I would with writing: get something that works; refactor for concision. Maybe everyone else is playing 3D chess and I'm still on Chutes and Ladders?
- tbrownaw 2y agoThere are degrees of conciseness. I've seen real code that looks like if(bool_var == false) { other_bool_field = true; } else if(bool_var == true) { other_bool_field = false; } Which I suppose could be called anti-concise.
- deleted 2y ago[deleted]
- andrewflnr 2y agoYes, even the "unconcise" first draft of anyone who cares enough to be here on HN is much better than some of the code out there. There's a basic level of concision you'll have by default if you actually understand the problem and the tools. You won't go away out of the way to complicate things. Maybe it's still a far cry from optimal, and definitely not code golf, but enough that I'd be worried if I saw even a first draft without it.
- BrandoElFollito 2y agoyes, when writing this as other_bool_variable=!bool_var you make it much better because the code speaks for itself ("other_bool_variable is the opposite of bool_variable"). The risk is that you may end with such concise code that nobody understands what it does. I went that dark path with perl 20 years ago, form "oh what a cool language for someone who comes from C" to "let's squeeze that in half a line, and either do no understand what it does, or add three lines of comments to explain". But yes, there is a good middle-groud somewhere
- spacebanana7 2y ago
- cplat 2y agoIf your knowledge of Python comes from JavaScript, I would not blame Python for it. It's the failure of the person to not "read the instructions" and assume instead. Maybe conduct interviews in languages that you're familiar with?
- grujicd 2y agoIf you were programming long enough, you easily had contact with dozens of languages. How do you pick up a new language? You can't really treat it as your first one. Especially if you need it "for yesterday". You won't read about "if" or "for". No, you scan for what's different from what you already know. If you're lucky you'll find "python for javascript programmers", but that probably won't go into non-core details like this. In practice, you learn basics first and start coding. Then you find a piece of code somewhere that you don't understand. That's a learning opportunity! However, it's easy if it's a function since it's easily googlable. Operators are harder to search for, for instance in new versions of C# you have operators like "?." (just an example). Since googling is hard you go to some "operators documentation" and try to find it there. And hope that it covers the new version. For cases like this story it's even harder because it describes a concept (chaining) and you maybe don't even know which name is used for that. At least ChatGPT recognized and explained it correctly, so it makes picking up new features easier than it used to be. I'm making a mental note to ask LLMs whenever I encounter unknown constructs.
- skydhash 2y agoIf it’s a language I don’t know, I’d still read a book or check the doc for a tour of the syntax. I can scan one in a couple of hours and get an overview I can refer to later for a more specific question. Even if I needed it for yesterday.
- polyomino 2y agoThis is a tangent, but checking if all the elements in the diagonal position are the same is not sufficient. You also need to check that any of the elements are not '-'.
- bowmessage 2y agoThat’s… what the article says.
- deleted 2y ago[deleted]
- cpfohl 2y agoTo be fair to parent I read the whole thing and also missed that.
- nothrabannosir 2y agoThat’s not what the article says. The last paragraph: if (cell[0][0] == cell[1][1] == cell[2][2]) { return Winner } > Well the code is indeed correct . Well done, Python… for finding yet another way to confuse us all. The code is incorrect: if all entries are '-' there is no winner. Even ignoring the braces…
- freehorse 2y agoYou do not know how the game was implemented to assume that.
- deleted 2y ago[deleted]
- solveit 2y agoDepends how the flow goes. It's reasonable to only check the diagonal when one player has actually played on the diagonal, in which case this is fine.
- noncoml 2y agoI am idiot but I would, and have in the past, have wasted the whole interview time argue in that I am right and he is wrong. Yes, John, some switches do start sending the packet before finish receiving it. It’s called cut-though switching. Hope you googled it. And yes it was worth losing the job offer over it.
- the5avage 2y agoI would say if you know you have to later work with the guy and he will be higher up than you this is actually smart.
- blitzar 2y agoJohn says you were wrong then and you are still wrong now. When talking about the problem domain John also mentions some switches do start sending the packet before finish receiving, it's called cut-though switching.
- noncoml 2y agoDidn’t get you..
- reader9274 2y agoIf you know nothing about Python or coding, and you see a=b=c, you'd think that's true when all three a,b,c are the same. Python does that beautifully here, and that's the intent. It's not Python that's confusing, it's your previous experience with other languages that's confusing you.
- toomanyrichies 2y ago> It's not Python that's confusing, it's your previous experience with other languages that's confusing you. "There are no children here at the 4H club either! Am I so out of touch? No... it's the children who are wrong." -Principal Skinner, "The Simpsons" EDIT to clarify- I'm just being silly, not suggesting anyone is right or wrong here.
- Terr_ 2y agoYeah, the behavior is arguably much less confusing than the alternative of: 5==5==5 # All three the same (5==5)==5 true==5 false Or 1==2==false # All three different, in a troublesome way (1==2)==false false==false true
- zdragnar 2y agoI dunno, I'd expect the right hand expression (2 == false) to be resolved first, then compared to 1. Compare this with a = b = c = 5 You evaluate the innermost (i.e. the tail) expression first, and work your way out to the head. As a sexpr it is a little more obvious that way: (= a (= b (= c 5))) An argument could easily be made that python is making up special rules for the equality operator by treating the duplication of the operator as merging the expressions into one. Instead of what you would expect, per the rules of literally every other expression, 5 == 5 == 5: (== 5 (== 5 5)) It gets rewritten as (== 5 5 5) Which one is "unexpected" is really a matter of perspective: are you reading with the rules of English or the rules of your programming language as your context? I do concede one caveat to this argument: mathematical operators tend to change operator precedence around to avoid making mathematical mistakes. I am mildly of the opinion that this itself was a mistake. Most calculators don't do it, so it's not like anyone would be* that* thrown off by it.
- Animats 2y agoI remember when that went into Python. It seemed too cute. There was a lot of that around the Python 3.4, 3.5 era. The case where all items are the same type is reasonable, but if implicit type conversions are invoked, it gets really complicated. Whatever the types are, Python will probably do something. Just not necessarily what you want. I could see having this if there was a compile-time constraint that all variables be the same type. That would disallow the bad cases.
- whatshisface 2y agoIn defense of Python here, a==b==c -> (a ==_string b) ==_bool c is an extremely confusing way to write (predicate) nxor c. A principle here could be "operators that look the same shouldn't do different things when they're written close together."
- devanl 2y agoThis feels a bit like a case of a "Python from 10 years ago in my head" vs "Python from 10 years ago in reality" meme. Chained comparisons have been in Python since I started using it at 2.1. It looks to me like they've been there since at least 1.4: https://docs.python.org/release/1.4/tut/node40.html#SECTION00660000000000000000 https://docs.python.org/release/1.4/tut/node40.html#SECTION0...
- Animats 2y agoAh. I'm thinking of [1] from 2016, when there was a plan to add short-cut evaluation to short-cut comparisons. That avoids evaluating all the terms when not necessary. But that was deferred. [1] https://peps.python.org/pep-0535/ https://peps.python.org/pep-0535/
- DonHopkins 2y agoThat's so lazy!
- selcuka 2y ago> Whatever the types are, Python will probably do something. Just not necessarily what you want. Are you sure you are not confusing it with PHP? Python is not statically typed, but it is strongly typed. There is no implicit type conversion unless it's safe to do so (such as between a float and an int). For example, print(1 > "foo") will raise a TypeError, and print("1" == 1) will print False.
- alkh 2y agoIn my mind,I just automatically translate a EXPRESSION1 b EXPRESSION2 c as (a EXPRESSION1 b) and (b EXPRESSION2 c), so there's no ambiguity. But I agree, it can be very confusing,so I tend to write code that is easy to read without being a master. For example, what would have guessed this evaluates to: False is False is False. If you thought, True, you were right :) I would recommend to take a look at one of my favourite repos for more[1]. [1]https://github.com/satwikkansal/wtfpython https://github.com/satwikkansal/wtfpython
- WalterBright 2y agoD solved the problem with what happens with (a == b == c) in an unusual way. It gives an error message. Both the C way and the Python way are considered wrong. You're going to have to add ( ) to clarify.
- _niki_s_ 2y agoyou can't just add () to clarify, you have to duplicate `b` too and that is not good transformation if `b` is function call
- throwaway313373 2y agoRust also gives a custom error message [0] that explicitly explains that "comparison operators cannot be chained" and shows you how to rewrite the expression using `&&`. Which makes me wonder whether they came up with this idea themselves or if they borrowed it from D. In any case, I think that this is the only reasonable solution for new languages. Because if you go with C way it will be surprising for people who expect Python way and vice versa. So, making this syntax illegal is the only way to uphold the principle of least astonishment [1]. [0] https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=f60de05ec7ec681cfc1057a05fa21dcd https://play.rust-lang.org/?version=stable&mode=debug&editio... [1] https://en.wikipedia.org/wiki/Principle_of_least_astonishment https://en.wikipedia.org/wiki/Principle_of_least_astonishmen...
- WalterBright 2y agoI gave several presentations that included this back in the 2010-2012 timeframe, and it had already been in the language for maybe a decade. When I implemented it, I had seen many knock-down drag-out debates about which was the best way to deal with it, and none of them mentioned simply making it illegal. It was another one of those features that were based on my experience designing aircraft systems. Another one adopted by pretty much all languages since D is the _ in numeric literals (although C++ used a backtick). It was just something that was obviously right once you saw it. But I didn't originate it, I cribbed it from Ada. I've always had a soft spot for Ada.
- anonymous3411 2y agoIs nobody going to point out that the code will return that there’s a winner even when all 3 cells are empty? (Even with the fancy python chaining?)
- throwaway313373 2y agoIt has been pointed: https://news.ycombinator.com/item?id=42038027 https://news.ycombinator.com/item?id=42038027
- andrewstuart 2y ago>> I have a very basic question which I usually ask in a interview which is to implement a tic tac toe game. I like this because the logic is straightforward and it helps to judge things like code quality / speed / conciseness etc. "I like this because the logic is straightforward and it helps to judge things like code quality / speed / conciseness etc." No, it doesn't. Everyone who comes up with their own pet way of evaluating and interviewing thinks - nay has the unshakable belief - that their way of evaluating developers is 100% spot on. However it's always something they just made up, justify with plain old words and never science.
- imiric 2y agoHow did you get "unshakable belief" from that paragraph? Interviewing is inherently messy, imprecise and unscientific. The process involves a lot of guesswork and feeling, rather than accurate measurements of any kind. It creates a fictional work environment that is often stressful for candidates, so any signal you may get out if it is also inaccurate. It's natural for interviewers to have a preference for certain questions, topics or ways of conducting an interview. You're free to disagree, of course, but claiming that your way is superior is silly.
- teekert 2y agoI'd be more confused about the curly brackets, I only know python and have never seen them used like that? My brain goes like: Here comes a set or dict. Also, why not do `all(cell[0][0],cell[1][1]),cell[2][2])` if you want to have True when all 3 are True? Perhaps I'm missing something, I don't exactly consider myself a 1337 coder.
- deleted 2y ago[deleted]
- pansa2 2y ago> I'd be more confused about the curly brackets, I only know python and have never seen them used like that? Yeah, that’s C/C++/JavaScript/… syntax, it’s not valid Python. > why not do `all(cell[0][0],cell[1][1]),cell[2][2])` if you want to have True when all 3 are True? We want to test whether all three are the same, not whether they’re all True.
- joeevans1000 2y agoDid he get the job?
- laurentlb 2y agoPython chained operators can be confusing, especially as it allows you to write things like: — x < y > z — a in b not in c WalterBright mentioned that D will give you an error. When designing Starlark (a derivative of Python), I also decided to give an error for this, by making the comparison operators non associative. https://github.com/bazelbuild/starlark/blob/master/design.md#no-chained-operators https://github.com/bazelbuild/starlark/blob/master/design.md... I agree this Python feature can look cute, but I've found it's rarely useful and can easily be avoided.
- jeroenhd 2y agoI find these expressions a lot more readable for bound checks (like `if 0 <= n < len(something):`) compared to the imperative `if (n >= 0 && n < something.length)`. This was especially true when I used it for homework, where constraints described in mathematical form were a lot more common than when dealing with real life software. The way it works in Python allows for some hilariously unreadable code, but the concept itself is good. I think it just needs more constraints to maintain readability, such as not allowing flipping the comparison sign (like in x<y>z). Banning these chained comparison operators is not necessarily a bad idea as comparison operators can easily cause confusion in that manner, but the reason they cause confusion is that many programming languages use mathematical symbols differently than actual math. A=B=C is perfectly understandable and more readable than A=B ∧ B=C. Restraining ourselves to "operand operator operand" as the only infix expression model made sense decades ago when computers had storage counted in kilobits. Today, we can let go of the limitations of yore and use mathematical expressions in a way that plain sense.
- Izkata 2y agoIf you write the bounds check in the same order it's really not that bad: (0 <= n && n < something.length)
- pzo 2y agoWorth to keep in mind that python first appeared in 1991 and predates even Java, JavaScript, PHP, Ruby
- otherme123 2y agoAnd the nerve to put Javascript as the example about how equality should work, a language known for: 0 == '' evaluates to True 0 == '0' evaluates to True false == 'false' evaluates to False false == '0' evaluates to True ' \t\r\n ' == 0 evaluates to True and the === operator you need to overcome the above. I don't have anything against JS and I understand why it is done that way, but if some language has weird and confusing comparison operators is JS.
- vdvsvwvwvwvwv 2y agoIt is merely syntatically confusing. Make == be ~~ or .fuzzyCompare() And === be == And you are fixed.
- otherme123 2y agoParaphrasing: "Well done, Javascript… for finding yet another way to confuse us all." I don't know many programming languages, but of the few I know any of them has a === because == is so confusing that you don't know exactly if (or when) it would bite you. You can't attack any language for their comparison operators from the Javascript camp. It that blog post removed the sentence "And this is how it would definitely happen if the code was written in javascript" they would be fine. But you actually don't know what would definitely happen in Javascript with the line in question "cell[0][0] == cell[1][1] == cell[2][2]", unless you know 100% what is in these cells. For example: cell[0][0] is "0", cell[1][1] is 0, cell[2][2] is true and "cell[0][0] == cell[1][1] == cell[2][2]" evaluates to True.
- Izkata 2y ago> cell[0][0] is "0", cell[1][1] is 0, cell[2][2] is true If those values came from <input> elements, the second and third examples aren't possible without having manually converted it beforehand. Input values are always strings, even a checkbox. That's where javascript's conversion rules and lax equality came from, an attempt to have sane defaults for simple uses: If a string is being compared to a number, the string is likely from an input and the number was typed into the code, so convert the string to a number before comparison.
- dzonga 2y agopython was pleasant in the python 2 days. Now there's so many confusing ways to do one simple thing. and one thing Golang has made inroads is there's only one way to do something. and ruby is pleasurable because the interface is consistent i.e everything is an object.
- throwaway313373 2y agoWhat does the feature discussed in TFA (chained comparisons) have to do with Python 2 vs Python now. As another commenter pointed out [0] this feature existed since 1.4 [1]. Also, I don't understand why so many people seem to be so confused/surprised by it. I can't be 100% sure because it was a long time ago, but I think that a lot of tutorials/introductory articles mention it. Like, "Hey, did you know that Python has this cool syntaxic sugar for this thing? Fascinating!". I think that I learned about chained comparisons long before I wrote my first line of Python. [0] https://news.ycombinator.com/item?id=42038451 https://news.ycombinator.com/item?id=42038451 [1] https://docs.python.org/release/1.4/tut/node40.html#SECTION00660000000000000000 https://docs.python.org/release/1.4/tut/node40.html#SECTION0...
- carlmr 2y agoI wrote Python for years before seeing it somewhere, going huh, and then I thought it's quite neat. I still don't think it's that confusing. It does what you think it should if you're reading pseudocode, which is after all kind of Python's MO.
- kjrfghslkdjfl 2y ago[dead]
- vdvsvwvwvwvwv 2y agoUnit tests should be part of the interview too. As should googling the behaviour live. Missed opportunities to go beyond the bland exercise to see what it is like pairing up with this person.
- some1else 2y agoRegardless of the naive algorithm, wouldn't this also match empty cells?
- froh 2y agowouldn't it be lovely if someone, somehow pointed out that it should be if a == b == c != "-": return Winner ? so three empty fields in a row don't "win" the game?
- VoodooJuJu 2y ago>Well done, Python… for finding yet another way to confuse us all. Would have liked to see some humility from the author, especially since he's an interviewer, but instead he deflects the fault onto Python as being confusing, rather than attributing the fault to himself and his own lack of understanding. Unfortunately, this kind of blame game is par for the course with enginerds. I say this all the time: engineers really should do a sales or customer service job before getting into engineering. This will help you build empathy, which will build your social skills and kindle some humility within you. These traits will give you an edge over other nerds and take you further in your career.
- deleted 2y ago[deleted]
- librasteve 2y agoRaku (https://raku.org https://raku.org) supports the same design as Python3 ... 0 < 5 < 100; #True 10 == 10 == 10; #True The Chaining Binary Precedence is specified for this https://docs.raku.org/language/operators#Chaining_binary_precedence https://docs.raku.org/language/operators#Chaining_binary_pre... That means you can make your own chaining comparison ops (or overload the current ones) with something like: multi infix:<~=>(Rat $l, Rat $r) { ($l-$r) < 0.1 ?? True !! False } is equivalent('<'); Much of Raku such as the default use of Rationals (Rat) is intended to make the language more approachable for non CS experts, so yes: 0.1 + 0.2 = 0.3 # True
- ubermonkey 2y agoI don't code for a living anymore, but I think if I were writing Python I would probably AVOID using that idiom because of how jarring it could be to people who are unfamiliar with it, mostly due to how strange it is coming from other languages. There doesn't seem to be a great upside to using it, and adding confusion to the codebase for whatever poor bum has to work on it later is bad karma.
- andrelaszlo 2y agoFascinating, the task was supposed to be straightforward and a way to judge code quality etc. Yet, when the candidate solved it in a simple way, they were told they had a bug that they didn't have. This is okay of course, coding is hard. It could have been an interesting opportunity for discussion, I guess. What's interesting to me is the conclusion that it's somehow Python's fault. I wonder if that attitude would work if it came from the candidate. I think we should be more careful with tests like this. They need to be done with more humility, so it's great that the post was written!
- trustinmenowpls 2y agoYea, after spending a lot of time coding in python and then switching to js, this definitely caused some heads catching moments.