60

The second sample is definitely better. I would be inclined to continue to improve the code by separating mechanisms from policies. The policy is the code that actually expresses the meaning of the program; the mechanism is the code that expresses what specific operations implement the policy. This idea comes from security design; you don't want the code ...


38

Why do most people (on the internet) recommend using recursion because it's simpler and easier to write the program? Logically I thought that we should write it in a way that is fast and simple. This is a perceptive question. I wrote an article about exactly this topic in 2004, which you can read here: https://docs.microsoft.com/en-us/archive/blogs/...


36

It would be worth your while to take a look at the implementation of random.sample to see how it works. (It's different from all 20 implementations in the post, and it will be instructive to figure out why.) In this answer I will confine myself to describing bugs (or ways in which the code in the post is inadequate in comparison with random.sample). 1. ...


32

Your second solution is basically a brute-force if-else tree, with lots of repetitive code, and not particularly interesting to review. I'll just focus on the first solution. Your terminology is confusing, as exemplified by this line near the end of converter(): # Selects the calculated equation for the selected conversion temp_conversion = (...


31

I prefer your solution to his. My reasoning is that: yours has constants only in the String manipulation you do not do string concatenation the logic is distinct for each remainder. Both options could be better though. The lack of 'breathing space' (white space between keywords, variables, values, and operators) leads to hard-to-read code. Lines like: for(...


30

TL;DR: Just use PyPy; it gets you to about 10x the time of C++. If you really want to use CPython, a lot of clever optimizations (not algorithm changes) gets you as fast as PyPy and then using Numpy gets you close to C++ (2x the time). The first thing of note is that your Python code is broken: if m > len(marked): break Remember that Python ...


29

This question demonstrates why Test-Driven Development (TDD) is a valuable discipline. If TDD had been strictly followed, the answer would have almost presented itself. To demonstrate that, I copied the tests only (not the 'production code') to a code base, and attempted to figure out what the implementation should be in order to pass each test. Keep in ...


28

First and foremost: Anyway, should performance be always the top priority? Definitely not. Don't write things that are needlessly unperformant, but only be overly concerned with performance when you have a reason to be. Most of the time JS execution time is irrelevant, because you're waiting for user interaction, or for a network request, or something ...


25

I would prefer the first one for a few reasons. It's more readable and easily understandable in my opinion. There's only one string, so less overhead. (Which is negligible unless this is being called a lot.) There's only one array. Reverse creates a second array. That being said, an actual review is in order. Methods that return a boolean value should ...


22

You don't need fancy logic. Good old closure is good enough here. function addg ( left ) { if ( left === undefined ) return undefined; return function addg_chain ( right ) { return right === undefined ? left : ( left += right, addg_chain ); }; } This simplistic approach creates an execution context, a closure, on the first call, with the ...


21

Then he asked me which I would prefer if I was handed that code Here's what I would say: It depends. rolfl has already added some comments about your solution so I'll add some comments (pros and cons) about the second solution. First of all, rolfl's comment about spacing applies here too, of course. The biggest pro about his solution is that it's more ...


21

The existing answers mostly have just said is is wrong here. Which it undoubtedly is. The reason it's bad to use here is if you pass 257 and above, or -6 and below, you may get incorrect output. The best way to show how it's bad is to ask you what the output of the following are: sum_double(2, 2) sum_double(1 + 1, 2) sum_double(257, 257) sum_double(256 + 1, ...


21

Recursive Approach Review In this method you are performing too many look-ups. First, you are looking up the 0th value of p two or three times. List indexing does take time, so it may be faster to store p[0] in a local variable, to avoid repeatedly indexing into the list. Second, you are performing a dictionary looking ups two or three times. While ...


20

A more efficient way to do this is to keep doubling the product while you can.... So, for example, \$5^2\$ is: $$\begin{eqnarray*} 5 +& 5 &\longrightarrow 10 \\ 10 +& 10 &\longrightarrow 20 \end{eqnarray*} $$ then add the last 5 to get 25. This can be done efficiently by using bit shifting: public static int sqr (int val) { int ...


20

All three versions can be improved. The first function has the problem that strlen(s) is likely to be called twice. strlen() is an expensive operation, as it walks along the entire string until it finds the NUL terminator. The second version (the macro) has the same issue, with the additional caveat that it breaks if s is an expression with a side-effect, ...


20

Why does it has to be a while? Maybe it is preference but for loops look cleaner. Reversing can be done by using reversed function which reverses a iteration countdown = 3 for count in reversed(range(1, countdown+1)): print(count) print('action!') Or you could use the step parameter in range(start, end, step) and rewrite the for loop to for count in ...


19

The second one is much easier to read, it expresses the developers intent. At first sight I (as a maintainer or another developer in the same team, for example) just want a quick overview about the code and don't care about the details. (How the code creates a server socket, for example.) The second one exactly gives that. The System.exit side effect could ...


19

First of all, the parenthesis around LocalDateTime.now() are useless. Now, let's see what we're really doing here: return LocalDateTime.now().format(DateTimeFormatter.ofPattern(format)); We're creating a unique LocalDateTime each time, but I am assuming that you always use the same format, and therefore the DateTimeFormatter.ofPattern(format) object will ...


19

You can get rid of some instructions by writing this instead: count_down = 3 while (count_down): print(count_down) count_down -= 1 print('Action!') Note that I have replaced countDown by count_down to comply with PEP8' naming conventions. Code explanation: count_down -= 1 is equivalent to count_down = count_down - 1. You can read more on Python ...


18

Here is the most common solution for this problem: public static bool IsPalindrome(string s) { char[] array = s.ToCharArray(); Array.Reverse(array); string backwards = new string(array); return s == backwards; } and if you are using Linq: public static bool IsPalindrome(string s) { return s == new string(s.Reverse().ToArray()); } ...


18

I would do something like: def sum_of_squares(n): return sum(i ** 2 for i in range(1, n+1)) def square_of_sum(n): return sum(range(1, n+1)) ** 2 def sum_square_difference(n): return sum_of_squares(n) - square_of_sum(n) Notice the use of a generator expression in sum, where I have omitted the square brackets.


17

Beyond the already mentioned[1] disadvantages[2], your code takes an avoidable performance hit if strlen(s) ≫ M_MAX_SIZE, since strlen() needs to count all bytes even if they exceed the limit. I'm going to outline a way to avoid this performance hit below. POSIX.1-2008 has strnlen(3) (available in glibc v2.10+; Microsoft's CRT has an equivalent strnlen() ...


17

I find myself struggling more to understand and read what is going on This is the key insight. A chunk of code is likely to be read more times than it was written. So write your code to be read. Use comments, docstrings, whitespace, type hints, etc. to make it easier for someone unfamiliar with the code (including your future self) to read and understand ...


16

As far as I see no-one has mentioned temporal coupling yet, so here it is. The second one (which returns void) has this code smell. Consider the following constructor code: createMonsters(); ... doSomethingWithMonsters(); A maintainer easily could mix up the order of the called methods which breaks your class and might turn out only at runtime. It's not ...


16

There is a subtle difference between == and CompareTo: the latter is current-culture-aware (or you can pass another one in), the former is not. However, as Ben points out in the comments, the official recommendation is to use Equals instead of CompareTo outside of sorting operations. Your devs might also be coming from a Java background where == and equals ...


16

You should not use eval without a very good reason. This is not a very good reason. Even though here you are actually fully in control of what gets passed to eval, this is good general advice. Whenever you find yourself using eval, there is probably a better way. Here I would use globals() to get a dictionary of all globally defined objects (see below). But ...


16

Correctness of the solution On reflection, I'm not sure either the C++ or the Rust code solves the problem as stated. I'm not completely sure I understand the shoe shine shop model so I may be wrong. Here's what it looks like the code does: you generate a bunch of random events of all kinds, and order them in time. Then you process the events one by one ...


16

Apart from performance, there are several other problems in your implementation which the other answers did not address. This should not be a class. It should be a function, because it being a class offers no advantage whatsoever and it makes its usage more complex. The variable palindrome is unnecessary and confuses the reader: this variable is always ...


16

Looking at the two implementations side by side, ignoring the goal of the exercise and alternative implementations, I'd say the second example is better: It uses one fewer variables. It does a simple index lookup rather than a slice. The implementation is easier to follow. For simple problems like this it's often useful to think of the complexity of the ...


Only top voted, non community-wiki answers of a minimum length are eligible