4 ms·
> a, b = b, a > (don't know why this is so famous, I never, ever used that in prod) This allows you to sort an array in place. It's heavily used in Go: https
by 2h 3y ago
> a, b = b, a
> (don't know why this is so famous, I never, ever used that in prod)
This allows you to sort an array in place. It's heavily used in Go:
https://godocs.io/sort#example-package https://godocs.io/sort#example-package
- BiteCode_dev 3y agoYeah but in Python list.sort() takes care of that.
- falcor84 3y agoTrue, but every once in a while we want to sort something that isn't a list and/or with a custom sorting algorithm.
- babel_ 3y agoSwapping variables around is also really handy for patterns like "alter list a until stable", especially with the walrus := operator allowing you to avoid declaring b outside of the while loop, keeping the intent clearer.
- roelschroeven 3y agoA variant is useful to update two (or more) dependent variables in one go without having to introduce temporary variables. For example to calculate the greatest common divisor using the Euclidean algorithm: def gcd(a, b): while b > 0: a, b = b, a % b return a
- tgv 3y agoYou can always write something like {var tmp=a;a=b;b=tmp;} in any language if you want to sort in place.
- 2h 3y ago> in place that doesn't mean what you think it means.
- Etherlord87 3y agoDo you know what it means? It seems irrelevant to the discussion, introducing a new variable won't make you unable to sort in place. You could even allocate memory on the heap and still sort in place.
- 2h 3y ago> Do you know what it means? yeah, it means no temporary variable.
- tgv 3y agoNo, it means the original data structure gets modified. In this example, the contents of the array you pass to the sort function will be sorted, without copying to a new array. Some overhead is acceptable, if only because you need loop counters.
- Etherlord87 3y agoWhat I find interesting is that you call someone out on not knowing a term, then you're being called out, then you respond claiming you know the term and explain the term… And at no point did it occur to you to actually duckduckgo it and make sure you're correct.
- 2h 3y agoIf you're creating a new variable with allocated memory, your process is no longer "in place". Sorry I didn't graduate from the school of duckduckgo like you did, instead I studied the language specification.
- Etherlord87 3y agoApparently they taught you there to never verify your knowledge not even if multiple other people point out you're wrong. A strong, religious-like conviction is all you need, it's not like you could possibly be in error. Of course a web search engine cannot lead to valuable information, therefore it is reasonable to ridicule anyone who uses it.
- Etherlord87 3y agoThe difference here is, a,b=b,a will use one less bytecode, by taking advantage of ROT_TWO