New answers tagged

0

Question Review If you work with types that are not included in the standard .NET Framework, include the library and namespace for these types in the question: FourierTransform, FourierShifter, Complex. Code Review Check arguments against null to avoid the nasty NullReferenceException. Give meaningful names to variables. Do not use ft and fft prefixes. ...


5

Currently I just got the one scenario for each method, with the input of 40, the goal of this test is to test which method is the most efficient for large numbers. Running one iteration of a test case is not resilient to external interference. What if your CPU is doing other stuff at the same time. To get better comparison results, you should benchmark ...


5

DynamicFibonacciCalculator is slow because you create a new memoArrays for each recursion, so it will never contain any precalculated values, and it behave just as the normal recursive version (and even worse because of the overhead of allocating the arrays. public long DynamicFibonacciCalculator(long number) { long result; var memoArrays = new long[...


1

We need to include <stdlib.h>, to have a prototype for calloc(). There's no definition of struct Entry here; this isn't valid C: typedef struct { struct Entry *next; struct Entry *neighbor; } Entry; Let's have a look at how we create a HashMap object: (*map) = (HashMap *) calloc(1, sizeof(HashMap)); It's not necessary to cast the result ...


1

The major compilers did not really auto-vectorize this, but it can be done manually. For example with AVX, we could do something like (not tested) int indexOfMin(double pt_x, double pt_y, double pt_z, int n) { __m256d ptx = _mm256_set1_pd(pt_x); __m256d pty = _mm256_set1_pd(pt_y); __m256d ptz = _mm256_set1_pd(pt_z); __m256d xdif = ...


2

There is math.factorial function. So no need to reinvent it. Using try/except for control flow is a bad practice. It's better to explicitly check whether a list contains a value using the condition if int(digit) in factorials. It also will eliminate the code duplication in except branch. It's even better to pre-calculate all factorials for digits from 0 to 9....


1

Your comprehensions are hard to understand, as you have two on one line. I recomend you spread them over multiple lines to increase readability. There is no benifit to using a dictionary comprehension, and only makes me think you're abusing comprehensions. Just use a normal for loop and use yield. You don't need to pass n, you can find the limit by using ...


0

using python 3 to find armstrong numbers within a user specified range in less than 6lines of code l = int(input('enter lowest number in the range: ')) h = int(input('enter highest number in the range: ')) for i in range(l,h): a=[] b=[] a = list(map(int,str(i))) b = list(map(lambda x : x**len(a),a)) if sum(b) == i: print(i,' is ...


4

dfhwze has addressed the structural and other issues with the code, so I will focus on eliminating the pyramid of doom in AllPasswordCodes: private static IEnumerable<byte[]> AllPasswordCodes { get { for (char a = '0'; a <= '9'; a++) { for (char b = '0'; b <= '9'; b++) { for (char c = '...


0

Your docstring is misleading. The function does not return a sequence; it returns a generator. It states “for a and b in range(n)”, which is incorrect. They are in range(2, n+1). If you don’t want to confuse the issue with range() excluding the last value, say “for a and b in the range from 2 to n, inclusive”. The problem refers to a “sequence”, where the ...


6

I'm trying to balance the code readability/size with the performance benefits, .. Your code could be optimized for readability and object-oriented design without introducing a performance penalty. The entropy generation could be written more elegantly. original code for (char a = '0'; a <= '9'; a++) { for (char b = '0'; b <= '9'; b++) { ...


-2

I find this a simpler solution to the problem with shorter code. const arr = []; let sum = 0; for (i = 1; i < 1000; i++) { if (i % 3 == 0 || i % 5 == 0) { arr.push(i); sum = arr.reduce((total, a) => total + a, 0); } } console.log(sum);


1

Inside the inner loop, \$1/k\$ is a constant term. So you could extract that multiplication from the inner loop, and apply it on the computed subtotal. This won't change the order of complexity though. I was wondering if there is a closed form for computing the sum of reciprocal powers (to replace the summing and thereby speed things up), but I couldn't ...


5

Note that we don't have a fully-compilable program, or the example data. But you do! So you can actually measure what's taking up the time using a profiler. However, I would guess that the following lines are the problem: QString line = QString::fromLatin1(line_BA); // Split line by spaces QStringList words = line.split(QRegExp("\\s+"), QString:...


7

Well, it's not much of a mystery. Your code is simple and pretty. Their code is ugly because it performs exactly what it needs to do, and no more: } else if (!strncmp(sz,"vertex",6) && ::IsSpaceOrNewLine(*(sz+6))) { // vertex 1.50000 1.50000 0.00000 if (faceVertexCounter >= 3) { ASSIMP_LOG_ERROR("STL: a facet with more than 3 ...


2

From a short review; patient is a global variable, global variables are bad var patient = [] is more idiomatic than var patient = new Array(); Comments should be all German or all English (I would go for all English, its the common language of the developers) You can group switch labels, this is valid JavaScript: switch(key){ case "id": ...


0

Here are a few suggestions: You should get in the habit of wrapping all code that isn't contained in a function, in a main guard. This will protect the code from being run when the file is imported. Instead of code like, for example, s = "x" + str(i) + "x", you should use f""in front of your strings so you can directly include variable names into the ...


4

A few observations: s_t = np.zeros(n) and r_t = np.zeros(n) are more than you need. Since you don't actually use the array values but solely overwrite them, you can use np.empty here. You're doing quite a bit of redundant work in the for loop. When calculating s_t[i], numpy basically has to repeat all the computations it has already done for s_t[i-1]. If ...


2

Don't like this: if(i > preroll) { t += duration_cast<duration<double>>(high_resolution_clock::now()-start).count(); } The call to finish the clock is inside the if statement. Thus you are timing branch failure successes. auto end = high_resolution_clock::now(); if(i > preroll) { t += duration_cast<...


2

General suggestions: black can automatically format your code to be more idiomatic. isort can group and sort your imports automatically. flake8 with a strict complexity limit will give you more hints to write idiomatic Python: [flake8] max-complexity = 4 ignore = W503,E203 That limit is not absolute by any means, but it's worth thinking hard whether you ...


1

That will not speedup your code, but there are some code improvements: follow naming conventions getAttribute -> get_attribute https://visualgit.readthedocs.io/en/latest/pages/naming_convention.html You can create set using set literal my_set = {1, 2, 3} You can compile tableReg = re.compile(r"^.+?(?<=[.])") once


2

You can simplify bin(...)[2:].zfill(columns) to f'{...:0>{columns}b}'. This can use f'{int(row[:2], 16):0>{columns}b}'. I'd recommend you convert to a NumPy array out of the function, as it's not really that important to be in there. Your code isn't idiomatic, as Python uses snake_case not camelCase. def from_hex(values, columns): return [ ...


3

Without same table and data scripts it is very hard to identify performance issues. However, here are a few observations that might help: Unless I'm reading this wrong, this seems pointless, just adding overhead: ON ((r.ArrivalAirportIATA <> r1.DepartureAirportIATA) OR (r.ArrivalAirportIATA = r1.DepartureAirportIATA)) When using expressions, ...


1

Comparison A comparison of performance of 2 classes only makes sense if both adhere to the same specification. Does your class do what a ConcurrentDictionary does? Review Why would you allow access to the underlying dictionary? If you must allow it, return a IReadOnlyDictionary. Checking arguments before taking a lock prevents unnecessary locks on bad ...


1

Problems There is one correcntness and two performance problems with your approach, both connected with running through the problem from the high numbers and down. For the correctness problem consider the number 91, it has the factorization of 7*13, but your approach would find 7 to be the largest, since 9 < 91**0.5 < 10 < 13, but the correct one ...


6

Lots of good comments already given. I'll just point out that you should most likely not be writing your own math primitives. It's easy to get wrong, it takes time away from actually creating what you're trying to create, you'll tear your hair out fixing hard to spot bugs and your code (contrary to what most people who write their own math primitives seem ...


3

I see some things that I think could help you improve your code. Don't abuse using namespace std Putting using namespace std at the top of every program is a bad habit that you'd do well to avoid. Eliminate global variables where practical Having routines dependent on global variables makes it that much more difficult to understand the logic and ...


0

order You wrote: if is_prime(divisor) and number % divisor == 0: that is, if A and B:. But B is typically false and is quickly computed. Prefer if B and A: stride Rather than for divisor in range(int(number ** 0.5) + 1, 0, -1): you might want to begin with an odd number and then use a stride of -2. You needn't special case for when number is ...


5

General - it might be better to create a matrix class and your own vector class in a namespace. Allow The Tools to Help You Improve the Code There are compiler settings that can help you improve your code, these can be specific the the c++ compiler you are using or they can be common. A common c++ compiler switch is -Wall which indicates a errors and ...


0

How to resolve the output size issue (many GB in memory and console) is highly specific to your overall setting, i.e. how you want to use the data further, so I restrict my answer to look into possible performance gains. Performance baseline I determine the baseline by restricting you original loop logic to the first 20 pairs: t0=res.tolist() t0=[tuple(x) ...


2

#define int long long Not only is redefining int a bad idea, but using long long should be reserved for legacy code. Use <cstdint> and (given the ranges used in this code) std::uint_fast32_t. if (limit > 2) cout<<"2 "; if (limit > 3) cout<<"3 "; ... 21 lines ... for(int i=sieve._Find_first();i< ...


1

Here are a few things you could try... Including those mentioned by @tinstaafl I think that you can avoid a lot of the computations. I had a brief look at the Wikipedia page, it seems that you are otherwise properly following the algorithm. #include<bitset> #include<vector> #include<iostream> #include<algorithm> #pragma GCC target (...


2

Well, your regex solution is obviously badly broken - it will fail if the attributes are in a different order, if they are separated by newlines, if they are delimited by single quotes, etc etc. If you try to replace it with a more correct regex (it will never be 100% correct of course) then you are quite likely to lose some of this speed - perhaps ...


1

Subclassing What's the point of this code? Since __CLASS__ always refers to the class in which the code appears, rather than the class of the current object, this method doesn't work with subclassing. That is, with the following code, (new SubModel())->getModelName() would produce base_model, not sub_model: class BaseModel { public function ...


3

You tagged laravel, so this answer assumes you are using Laravel. Laravel has two built in helper functions that will help you do this. class_basename() will return the name of the class with the namespace stripped off, and snake_case() will convert a string to snake case. Combine them, and you get: public function getModelName() { return snake_case(...


1

Efficiency & Clarity For efficiency the only "flaws" (it's more for "good habit" than noticeable optimization - it doesn't matter for such a small strings) would be the order of functions (regexp is costly so it should be called on string processed as far as possible) and regexp itself which could be optimized for least amount of steps. When it comes ...


3

I'm not sure what your optimizations are doing(comments would be nice), but I did notice several inefficiencies: Never include a calculation in the limit test in a for loop. It get's re-calculated on every iteration. In this case set the limit to sqrt(limit). the calculation is kind of expensive but it's done only once. The same goes for the iteration ...


3

Congratulations to you for finding a major bottleneck yourself. There are a few more to get rid of. Generally speaking it's quite a performance killer to convert data between Python and numpy repeatedly. And you do that a lot. You even do it to determine the number of iterations for some loops, e.g. in for j in range(np.array(alphas).shape[1]):. Since ...


1

I won't go down the rabbit hole of debating what constitutes a "valid Pascal/Studly-cased string" but there is plenty of debate here if you want to read about fringe cases (like acronyms and multibyte characters). I will merely cross my fingers and hope that your project's naming convention does not wonder into tricky territory. Either way, the post-...


1

There's actually not much I can do when it comes to efficiency, but it is clear that the code is not very readable. All these nested function calls make it very hard to track what's going on. My suggestion would be to split this single method into multiple methods. This is a very normal strategy in programming. A method should only do one thing, and do it ...


3

I searched around this forum a bit more and found some advice to use the package cProfile. This helped me locate the problem which was the sum(sum(indicator_normalized)) which took more than 95% of the total time for the complete algorithm. I just moved out the sum and the total time for my algorithm went down to 1/19 of the total time it took before. So ...


2

O(n) Solution You don't need to keep track of all the places you can reach. You only need to know what is the highest index you can reach, because you can reach any lower index by choosing a shorter jump. Scan the list from 0 to the end keeping track of the maximum reachable index. If you ever reach an index greater than the maximum reachable index, you'...


1

First and foremost: Never use datetime to measure performance! There is timeit and profile/cProfile for that. With that out of the way, let's talk about NumPy. Python in general does not like loops if you want to go fast. NumPy can help you here since a lot of the heavy lifting can be done by the C backend where loops are orders of magnitudes faster. But ...


2

IntelliJ reports: . . . While occasionally intended, this construction is confusing, and often the result of a typo. I agree with the first part, but it's letting you know about this mainly for the second part. It's pretty common on Stack Overflow to see problems arise from people putting a semicolon in weird places and having odd behavior as a result: ...


0

Optimization starts from a sound logical process Let's think about the problem in particular. Given a positive integral number n, return a strictly increasing sequence (list/array/string depending on the language) of numbers, so that the sum of the squares is equal to n². If there are multiple solutions (and there will be), return the result with ...


1

When you ask if your first solution is faster, if you are talking about theory it isn't faster. To understand why you need to understand the the difference between big O complexity and actual run time. For the purposes of this question, it is important only that you realize that big O complexity does not guarantee that a piece of code with O(n^2) run time ...


3

Initially, I thought maybe the process is slower as it uses two memory containers, as opposed to simply comparing two halves of a single string. I think you hit on an excellent idea right there. I'd read a line of input into a string, the compare the first half of the string to the second half in reverse order. You can use std::getline to read the string. ...


3

I'd question your objectives here. Yes, it's admirable to keep code concise, but we should also strive to make it robust. As it currently stands, we will return 'many' for any of these inputs: 0 -5 0.1 True None "foobar" [] Consider throwing an exception if the input is not a positive integer.


11

While it is not quite definitive, it looks like you use using namespace std;. That namespace is not designed for wholesale inclusion, being vast and subject to change at the whim of the implementation, aside from providing what is standardised. Read "Why is “using namespace std” considered bad practice?" for more detail. Synchronizing C++ iostreams with C ...


1

for (size_t left = 0, right = size - 1; first[left] == second[right]; ++left, --right) { if (left == size) { return true; } } Completely incorrect. IIRC, accessing sizeth character of first is UB. Even more, at this moment right is (size_t)-1, so you may guess. For instance, when size is 0, right is initialized to -1. Were it a real ...


Top 50 recent answers are included