New answers tagged

1

If this is true: the main folder contains 36 subfolders which in turn contain 10 subfolders and we assume your F1 / I1 naming scheme is accurate and the contradictory Model / image naming scheme is not, then my recommendation is: Don't make separate output files; make one six-dimensional array output to one file. The result turns out to be about 12MB ...


2

In addition to Toby Speight's excellent answer: Avoid repeating names unnecessarily Every type you add starts with Myth. However, once you put everything in a namespace, there is no reason to repeat parts of the name of the namespace. I would also recommend renaming MythFramework to just Myth. It then becomes: namespace Myth { using Callback = std::...


1

Reducing maintenance burden: void drawBoard(gc*, int); void updatePieces(gc*, int[8][8], int, const char*[12]); int findMousePosX(int[8][8], int, int, int, SDL_Event); int findMousePosY(int[8][8], int, int, int, SDL_Event); We could avoid having to maintain these declarations by moving the function definitions here instead. Declare variables as locally ...


3

We're missing some includes in the header file: #include <functional> #include <map> #include <vector> And in the implementation: #include <memory> I'm not a fan of the singleton, which can be hard to unit-test independently. However, if that's a done deal, I don't think there's any call for instance methods and data - it can simply ...


1

I propose an optimization based on the multiprocessing module, to parallelize the requests. Unfortunately, if you want to get the results as soon as possible, you will have to "DDOS" Wikipedia at some point, and the sleep needs to be removed. Some notes and suggestions In the following piece of code, the page variable might not be defined in the ...


2

TL;DR The current groupby.apply code computes an extra cumsum (_year) and requires a lot of extra index manipulation (set + drop + reset + drop). Instead use groupby.cumsum, which is more idiomatic and ~20x faster for larger dataframes. Issues This groupby.apply adds a lot of overhead: ...groupby('_year').apply(lambda x: x.set_index('quarter').cumsum()) ...


2

It’s an adventure game, why not seeing the code also from an adventurous perspective. Let’s imagine a character that traverses a sequence of scenes that each has: a story: With your newly discovered {element} powers, you mysteriously wake up in a whole new world. You're in a crowded forest and there's noises coming from every direction. A small furry animal ...


1

Here, I shall work with the assumption that the "playing sound" part works fine. Firstly, congratulations! The concept you came up with to resume the execution of the recin function is known as a continuation, and it is available in Python natively through generators and the yield keyword. Rewriting your code to use generators and still polling the ...


0

You don't need to hide/unhide columns to access data. It's ok while testing but takes time. There are a few more time consumig automations that can be disabled for the time of operation, see: Changing the formatting of sheets. Minor impovements can be achieved with applying array operation (for horizontal contiguous ranges only) like Range("A2:I2")....


1

Firstly, please put the headers: #include <vector> #include <algorithm> #include <queue> I wonder if you could may be do this set up in a constructor or something. Because otherwise you are just telling the user to do a two-phase initialization. If the user of this class misses this, the function won't work. void setConfig(int key_length,...


0

I see no reason for using const in either char_lower or char_upper. I would implement it much more simply: char char_lower(char char_) { if((char_>='A')&&(char_<='Z')) char_+=('a'-'A'); return char_; } char char_upper(char char_) { if((char_>='a')&&(char_<='z')) char_+=('A'-'a'); return char_; } Also given you have ...


3

A few additional points to the ones people have mentioned. I agree that many of these should not be class functions, but algorithms working on generic strings or ranges. I also agree that you should model the interface after the STL. Use Move Semantics When Appropriate One major missed optimization is that you only ever make deep copies of the string data. ...


17

Justify text. (.rjust, .ljust, center) That is becoming a "fat interface". These functions should be generic algorithms that can work with any string class, including yours, std::string, std::string_view, and even vectors, arrays, and C-style strings. They should not be members of this class. Am I using new and delete properly? Probably not. ...


4

It looks pretty good! The coding style is consistent and it seems to follow the main PEP8 guidelines. There are some things that I would change though. Adding a main function Adding the following pattern avoids polluting the global scope with local names: def main(): ... if __name__ == '__main__': main() It allows to define functions containing ...


9

This looks pretty good for 1-month coder. Keep it up! Use functions, classes and tests If you have already learned them - use them. If you haven't - learn them. Start with functions. They are in the language to organize the code. When you have functions, you can test the code. Avoid "magic numbers" What's 40? What's 6? If you ever want to change ...


4

A few more points: The C++ standard library provides many helpful algorithms in the <algorithm> header which can be used to implement several of the functions here, e.g.: std::copy (or std::memcpy) can be used in many places. operator==() can use std::equal upper() and lower() could use std::transform. reverse() can use std::reverse. contains(char) ...


5

Names beginning with __ are reserved for the implementation to use, for any purpose. That means that macros could redefine your identifiers, to give very obscure errors. Stick to the permitted identifiers for your code. Why are we implementing our own case-conversion functions, instead of using the properly-localised ones in <cctype>? The header file ...


0

First some problems. (1) Your tokenizing function tries to accomplish the task character by character, but that fails if any operators are multi-character. (2) The tokenizer fails if the input string contains spaces, which seems user-unfriendly. (3) Because it returns the hard-earned results as an non-delimited string, the infix-to-postfix conversion ...


5

I was trying to implement an efficient (in terms of size of code and time and memory-efficient) of Infix to Postfix in python without the use of any modules and with only necessary parts (such as without class). First of all, there is nothing intrinsically bad about classes. You should feel free to decide between object based programming or not based on the ...


3

Quick improvement*: put your code through an automatic formatter. Python has a guideline called PEP8 which gives recommendations on where to put linebreaks, spaces, how to name things consistently. I use black to format code since it is PEP8 compliant and does all the decision making for you so you can focus on more important things (it doesn't do everything ...


1

using namespace std; is a harmful habit you'd do well to shake off. It's less effort to write std:: in the four places you use it (two if you stop flushing with every newline) anyway. Instead of passing a pointer to your function, it's probably simpler to pass the invocable itself. That allows g to be something other than a plain function - perhaps a std::...


1

Better algorithms I'm not quite a specialist in this area; so I assume you have selected the best possible algorithm and the best possible parameters, so microoptimizations are the only thing left to do here. Python is not fast I don't like to say this; usually Python is fast enough if you choose the right tools. OpenCV has HCT implementation; have you tried ...


3

I see one substantial problem with your implementation: f() calls fref() twice - bad enough if each call consumes considerable resources, probably plain wrong where the call has side effects. (The funny part is main() introducing a variable to hold the result without need.)


1

The tests You have test cases - that's already better than a majority of review requests here, so well done! There seem to be some missing cases. For example, we have no tests where either argument is an empty string - it's a good idea to start with those so that we have to think about edge cases and perhaps error reporting to begin with. We have very few ...


3

Improving performance There are a few ways to improve performance. You already have the basic structure right: Do a few quick checks to see if it's possible at all that there is a permutation in the string. For every window position, do a quick check first to see if this could possibly be a permutation. If it is indeed possible, do a full check. In order ...


3

I try to avoid spelling out how apply a sliding window to the challenge at hand. The whole point of a sliding window approach is to get independent of the size of the window and only spend effort on things entering and leaving it. You do so with the character counts. But method 1 even uses viewSize prominently. Method 2 exchanges this for, say, alphabet size....


1

Fix your function signature. Most Python programmers use lowercase for function names. Even more important, don't swap the order the left and right: # No: why is "left" to the right of "right"?!? def QuickSort(array, right, left): ... # Yes: less chance for confusion. def quicksort(array, left, right): ... Don't make the ...


2

Error Handling Similar to the Excel part, an exception in the writing can cause an orphaned Word instance. Placing the Quit() in a finally block will help that try { var wordDoc = wordApp.Documents.Add(); FormatDocMargins(ref wordDoc, wordApp); AddTitleToMailBoxList(wordDoc, mailboxdata.AddressStreetNumber, addDateToTitle); ...


3

I also have a couple of suggestions... CExcelInteropMethods is creating an Excel instance and destroys it in CloseWorkbookExitExcel. A more C#-ish approach would be to make this class IDisposable and rename this method to Dispose. Consequently removing the call to it from SaveEditsCloseWorkbookExitExcel and let it only save. You can make you code less ...


5

I managed to speed up reading the tenant data by making a single interop call to get all the data from the range and then iterating through that private void AddTenantDataToTenantTable(Range TenantDataRange, ref System.Data.DataTable tenantTable, int headerLine, int firstColumn) { int columnCount = TenantDataRange.Columns.Count; int rowcount = ...


3

I stuck with the book's methodology since it already provided much of the code except the block but I incorporated the default sum method in my block so I don't have to create a global variable set to a false-y value. I used the f'string so I could easily print the keys and values in the required format rather than use the pprint module. Inventory_List = {'...


2

Just an idea... I'd consider turning this query into a stored-procedure taking the CustomerNumber as a parameter and working directly with the data without the view. I'm pretty sure it's slow becuase it cannot take the advantage of CustomerNumber being probably indexed and it has to perform a full-scan of the view.


2

POS 1 and POS 2 represent coordinates of a small cluster on a big grid (matrix) Unfortunately not all comparisons are in the table. Some are missing. This is a job for sparse matrices. The selection of which sparse matrix format to use is non-trivial but BSR lends itself well to direct construction from your data. I'd cut out Pandas and use Numpy file ...


2

Improving your brute-force solution. Your current approach will time out because it conducts an exhaustive search. Nonetheless, it's still instructive to think about improvements. (1) The question is framed in terms of a and b, both within an inclusive range from 1 through n, but your code renames those values to m and n. The latter is particularly confusing,...


1

The first way, you are using high-overhead string manipulation. That will dominate the time. The second way is closer to a "normal" implementation. Instead of an array of int for the digits produced, which you then format using printf(!), generate the char for each digit. Fill the buffer from right to left so you have the finished string of ...


2

sigma, mu and u should be capitalised because they're constant (if they remain as constant globals; however, in my suggested code I show them instead as function parameters that are lower-case). Move your simulation out of the global namespace into a function. Consider adding numerical tests. I have only shown a regression test and cannot vouch for its ...


3

Running your code in Release build after a tweak like i < count instead of i <= count and increased array size by 10 times, and assign 1 for each array element (needed for further comparison): Time is 177 sum is 10000000 Then I've made some changes public const int numberofthreads = 7; public const int count = 10000000; static void Main(string[] args)...


2

There are a couple of problems with your code we'll have to clear up before looking at performance. I'd like to write a comprehensive review about it, but I'd have to make too many assumptions. So instead it's going to be a more general one and one of the problems with that is that I can't touch the performance issue. You have not specified your Python ...


5

This answer only addresses the original spinlock version in the question. Ensure the code is self-explanatory Before reading the code, I recommend running it first and see how each state is encoded. Rather than me trying to explain the pattern, I think you'll be quicker to catch the pattern by actually looking at the output of each state before a task has ...


3

There are a few things you can do that are very very likely to speed up execution of your code. I see you are turning Applications.EnableEvents off at the start of your code and then back on and the end. You should do the same for Application.ScreenUpdating and also turn automatic calculation off temporarily. i.e. do the following for each sub: Sub ...


0

To add to Peter's answer, it is worth thinking about creating a data structure to support what you need, instead of managing it yourself. I almost always find myself making some type dict these types of situations, which makes the code cleaner. class ArrayMap { add(code, country) { this[code] ??= [] this[code].push(country) } } This greatly ...


3

The computations you are doing are absolutely trivial. Summing integers is pretty much one of the fastest operations a CPU can do. In particular, the computation is much faster than the time it takes to even spin up a single thread, let alone spin up six of them – and that's not even talking about merging back the results and destroying the threads. The ...


0

Code should be correct, maintainable, robust, reasonably efficient, and, most important, readable. Your code reads as a tangled web of nested conditionals. It's not clear that 'notEntries' always exists. Catch error handling merely writes a message to the console.log. You have not provided test input data. Let's use stepwise refinement: Program Development ...


6

When optimising APL programs, always strive for few computations on large arrays. Here, you want to compute the first 99 squares, so start by generating the 99 first integers: ⍳99 Now square them, either with (⍳99)*2 or 2*⍨⍳99 or by multiplying them with themselves: ×⍨99 Ideally, you'd want to print them as a single printing action (⎕←) too, so format the ...


3

Oh, an APL question. I believe you’d be better off generating a vector of the numbers between the ceiling of the square root of your lower bound and the floor of the square root of the upper bound, then multiplying that with itself, using +.×. This computation will be much faster than the loop, because it will vectorize.


2

Is there a way to speed up the code? The speed is determined only be the nested for loop. Nothing glaring stands out to me. Are you compiling in debug mode (without most optimizations) or in release mode (with optimizations on)? I cleaned up your code somewhat, though I don't expect it to have any performance impact, mostly reducing necessity of casts and ...


5

Multiple lines First off, don't try to do everything on one line. This line is doing way too much: x = str(np.reshape([random.randint(1, 3) for i in range(100)], (-1, 10)).tolist()).replace("[", "").replace("]", "\n").replace("\n,", ",\n").replace("\n ", "\n").replace("\n\n&...


Top 50 recent answers are included