Stack Exchange Network

Stack Exchange network consists of 175 Q&A communities including Stack Overflow, the largest, most trusted online community for developers to learn, share their knowledge, and build their careers.

Visit Stack Exchange

New answers tagged

3

General Points Use strict equality and inequality, === or !== rather than == or != Use const for variables that do not change. Eg let size = can be const size = Spaces between for( and if( eg for ( and if ( Problem/Bug Your code has a very serious and hard to spot bug. It seams to me that the array should be modified in place (which is the point of the ...


1

A rotation is a modular arithmic operation. The congruent value of any number n is (n % size + size) % size. public static int[] LeftRotation(int numberOfLeftRotations, int[] a, int[] b) { int n1 = numberOfLeftRotations, n2 = numberOfLeftRotations; for (int i = 0; i < numberOfLeftRotations; i++) { a[a.length - n1] = b[i]; ...


11

By reviewing your code, the first thing that comes to my mind is a lot of if statements. You should try and keep those minimal by writing solutions to be as general as they can be. Another thing that I don't like in your code is that you are doing manipulation of array passed to the function, instead of going out with a fresh one. It looks like this ...


1

Data Model I would add a restriction on the attribute and move the convenience method from the creator to this class. [AttributeUsage(AttributeTargets.Class)] class ParentAttribute : Attribute { public ParentAttribute(Type type) { Parent = type; } public Type Parent { get; private set; } } [AttributeUsage(AttributeTargets.Class, AllowMultiple=...


2

Style PEP 8 is the official style guide for Python. Unless you have a good reason to deviate, you should use lower_case_with_underscores for variable names and method names. Terminating statements with semicolons is a faux pas in Python. Also, indentation should be four spaces, which is a particularly important convention to follow in Python since ...


4

One thing to keep in mind is your variable checked_list, which serves almost no purpose in the function, as you could do without the else block. The simplest thing I can think of would be just to shorten the function down to one list comprehension, instead of appending to two lists. Revised code: def checkio(original_list: list) -> list: return [...


0

return lists your functions seem to return lists or tuples. For 2 or 3 values, this is ok, but diam returns 6 values, metrics 12. This is very unclear, and unstable when you want to add, reorder or remove a metric. Better would be then to either return a dict or a namedtuple spacing pep-8 recommends around operators (+,...) I use a code formatter (black)...


1

We don't have the lines of codes you say they are doing the "same" thing. So I should guess. If those lines of codes have the same logic, just with different data, It's a great idea to separate those lines of codes in another method. But it seems that those lines just need teams data, not the data that belong to the object. If that is the case, you should ...


2

I performed some timings of the solutions presented by @AustinHastings in his answer on my machine at work (Linux 64bit, Intel Core i7-2600, 16GB RAM, Anaconda Python 3, ). The timing function was slightly modified to use repetitions get more accurate results as well as to easier get the timings for visual display. def time_func(f, shape=1000, n_reps=10): ...


2

I tried some alternative approaches, and got this result: Time for orig: 0.15900921821594238 Time for concat: 0.18401050567626953 Time for block: 0.16700983047485352 Time for stack_ravel: 0.1760098934173584 Time for stack_flatten: 0.32501864433288574 It's worth pointing out that I'm on a 32-bit machine with not enough RAM to hang with you. So I used ...


2

Realy, dud its childish! only ones: lenf = len(folder) just one 2d array: len_types = 12 arr = np.zeros([lenf , 12]) learn how to work with numpy arrays, you will avoid the loop as well. And for example the mean can be done in one line for 2d array: means = np.mean(arr, axis = 1) https://docs.scipy.org/doc/numpy/reference/generated/numpy.mean.html


0

Review When analysing the notes of a scale, you loose information when only working with a predefined set of note names. A C# is not the same as a Db. //chromatic scale var chromatic = ['c', 'c#', 'd', 'Eb', 'e', 'f', 'f#', 'g', 'Ab', 'a', 'Bb', 'b']; I would allow for any kind of combination of a degree with an accidental: C# = Db = Ebbb = .. ...


6

Interface When I see a method named get…(), I expect it to behave like a getter method: it should retrieve data, with no side-effects. Your getNext(), though, has the side-effect of consuming one random element from the list. Therefore, next() would be a more appropriate name than getNext(). Once you rename it, you'll see that your RandomStringChooser ...


5

Here are some suggestions: Your coordinates_to_index should better return a size_t instead of int because int may not be able to hold the required values. return std::inner_product(cbegin(dimension_product), cend(dimension_product), crbegin(coords), std::size_t(0)); // note: not int You don't need to compute the strides and store ...


3

Trying to avoid duplicating any comments you have already had Why name the class "ST"? It's not very clear to another developer what a class called ST actually does Why extend EQ? Generally inheritance is use to make another class that provides the same functionality but more specialised, e.g. A "Car" might extend a class "Vehicle". I think it would be a ...


4

The default-ctor won't be implicitly declared as there are user-declared ctors. When you can define a default-ctor with reasonable behavior, consider doing so. If you use in-class initializers to 0 resp. nullptr for the members, it can even be explicitly defaulted, making the class trivially default-constructible. Top-level const on arguments in a function ...


4

I would allow the default constructor and make it default to a 0 size array. with the optimization that b_array is a nullptr. Then you can also add move constructors/assignment. Where the moved-from object gets a b_array = nullptr; On of the basic functionalities of a container is iteration. So you should add a begin() and end() that return the b_array and ...


2

Disclaimer: I am not an expert in music theory, and english is not my first language. Therefore I may use the wrong terms in the following review. Review of your current code I/O should be separated from the computation. In your case, the findUpperStructureTriads() function should return something instead of printing it. That makes the function better ...


9

Given the limited context, and no information about where the hotspot is in the code, it's difficult to give concrete advice. Here are some musings for your consideration: For ease of reading, it's preferable to have whitespace after control flow keywords and before the (. It is suggested to always include curly braces, even when they're not required by ...


6

I don't think you can beat that linear complexity since you need to look at each character to determine the Hamming distance. One small optimization you can do is to short-circuit once your count goes above one, but that adds an extra check in every iteration, so it might have worse runtime depending on the inputs.


6

A fairly simple alternative. Take the maxLength String plus one letter and cut it at the last space. If the maxLength was at the end of a word, the "plus one letter" will take care of that. The > signs in the tests are there to make any trailing spaces visible. const crop = (message, maxLength) => { const part = message.substring(0, maxLength + 1)...


4

A Code Review Your code is a mess, Inconsistent indenting. Poor use of space between tokens, and operators. Inappropriate use of variable declaration type let, var, const. Contains irrelevant / unused code. eg substr Fails to meet requirements. You list the requirement "no trailing spaces in the end." Yet your code fails to do this in two ways ...


4

Your code looks great. Oh My Goodness's solution is really great. If you wish, you might be able to design an expression that would do the entire process. I'm not so sure about my expression in this link, but it might give you an idea, how you may do so: ([A-z0-9\s]{1,11})(\s)(.*) This expression is relaxed from the right and has three capturing ...


10

This is much slower than necessary. It takes time to construct the array, and more to shorten the array word-by-word. It's easy to imagine how this would go if words contains a whole book and K is some small number. In general, you want an approach that inspects the original string to decide how much to keep, and then extracts that much, once, before ...


6

Note: After posting my answer I found out that the question is a duplicate of this question. Readability If you have no values then your code will error when you try to interact with high. You should define high outside the loop. You should use a function so it's easier to test your code. You should use full words for variable names. def ...


0

This could also be done using a single for loop in a recursive method that can calculate for each member of the array the product of all the other members of the array . this can be done like this . import java.util.Arrays; public class ArrayElementsProduct { private int[] originalArray = {3, 1, 2, 0, 4}; private int[] productsArray = {1, 1, 1, 1, ...


1

In the update() method of EffectStack, the queued property is re-assigned to an empty array: this.queued = []; You could consider truncating the array by setting the length property to zero: this.queued.length = 0; There are various responses to Is it an antipattern to set an array length in JavaScript? that may prove valuable in this regard. In ...


2

This could be done with two consecutive loops (instead of nested loops), making it O(N) instead of O(N^2). In the first loop you calculate the total product of all non-zero elements (and the number of zeros). If there are more than one zero, return result as is, since all elements already default to zero. In the second you either set the result element to ...


0

Having LinkedHashMap A and HashSet B. For each character C in string S Map C to it's position in S to A. If adding C to B returns false Remove C from A. Return value mapped to first element in A or -1 if A is empty.


2

You don’t need Objects.isNull(...). Simply using != null would suffice, and avoids an extra function call so should be faster (unless the compiler can optimize the call out). Your loop at the end is using raw types. You should use for(Map.Entry<Character, Integer> e : map.entrySey()) { instead, for type safety. Your castings then are unnecessary. ...


1

Vernacular Naming is very important and it starts by using the correct terminology. There is no such thing as a JSON object as you use the term. There are JSON strings and JSON files. There is also a JSON built-in Object. It provides an API to help convert between Objects and JSON strings JavaScript uses Object to store data in the form of properties. ...


1

Every time you feel obliged to put a comment like // Start filling up left array you really deal with a potentially important algorithm, which deserves a name, and a method of its own. In this case the algorithm is known as partial product. Consider factoring it out, and see the comments disappear. Ditto for the second loop. Regarding space ...


-1

alist= int (input (" enter the values of the list")) #list formed will have the keyboard values n= len(alist) # length of the list for r in range( n-1): for c in range(0, n-r-1): if alist[c] > alist [ c+1]: alist [ c] , alist [ c+1] =alist [ c+1] , alist [c] #toswap print( " sorted list",...


Top 50 recent answers are included