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

1

This code looks pretty good. I don't see much I would change. This code makes good use of const and let where appropriate. The only thing that stands out is that splitting a string into an array can be done with the spread syntax instead of calling split(). The first instance: let sReverse = s.split('').reverse().join(''); Could be changed to let ...


5

Sᴀᴍ Onᴇᴌᴀ answer has the right idea for small strings, but can be improved by using a Set to hold the vowels rather than an array. This reduces the overhead of Array.includes which will iterate each character in the vowels array for non matching characters You can create a set as const vowels = new Set([..."AEIOUaeiou"]); To encapsulate the constant vowels ...


22

An alternative route is to use string.replace() and Regular Expressions to strip everything but the vowels from the string. Then count the length of the resulting string. This avoids iteration altogether. const vowelCount = s => s.replace(/[^aeiou]/gi, '').length console.log(vowelCount('The quick brown fox jumps over the lazy dog')) The regex ...


18

I'm just wondering if there's an easier way to solve this problem without the big blocky code in the if statement. Well, you could put all of those in an array: const vowels = ['A', 'E', 'I', 'O', 'U', 'a', 'e', 'i', 'o', 'u']; And then the if condition can be simplified using Array.prototype.includes(): if( vowels.includes(v)) { The fact that I have ...


5

I have seen many answers that suggest counting the number of distinct characters. But beware that this only works for 16-bit characters! A character in C# is a UTF-16 code unit. Extended unicode characters are stored in multiple C# characters. CharUnicodeInfo.GetUnicodeCategory allows us to detect whether a C# character represents a real character or ...


1

I would change the following things to your API: let tree items know their parent and children -> easier navigation encapsulate the children -> better integrity As for the rendering, it can be done more lightweight. sample code: using System; using System.Text; using System.Collections.Generic; public class Program { public static void Main() { ...


1

I'm not sure how to answer all your questions but at least I'll provide my two cents :) Don't use regex unless you really need to. Regex is notorious for its slow performance on large strings. I was thinking about some rule engine before I got to your code. So I think your class structure is perfectly fine. Regarding the code readability: - You could ...


3

Looking at your code for style #include <stdio.h> #include <string.h> // array of strings for testing These strings should be char const * unless you really want them to be altered char *strs[] = { You have the 'aperiodic comment twice here, which confuses me somewhat. If this is a section of aperiodic strings, why do you need the 2nd ...


0

I don't think buffering is the problem or solution. Creating a gigantic buffer probably hurts if the recipient has, say, a 4k buffer for reading the results. That would mean the recipient can't start working before your code has finished completely, making the process completely serial instead of parallel. Instead you should try creating a smaller buffer (...


4

Are you sure the bottleneck is the printing, as opposed to whatever new ClassThatBuildsOnBuilder(builder); is doing? Is coordinates always going to have a width of four? It appears you're building the whole string in memory, and then printing all your output at once at the end. While printing each line to standard-out individually may be slower, it also may ...


2

You could consider using the fileinput.FileInput to perform in-place substitutions in a file. The accepted answer in this Stack Overflow answer illustrates a simple solution. If you need to perform replacements across multiple lines, you will likely want to read all of the data into a variable (if possible, depending on file size), then use the re.sub ...


6

Personally, I would do this kind of thing line by line. I don't like the idea of putting my entire file into memory, then overwriting it. What if something goes wrong in between? Basically I don't trust myself to write good code! So, looping through line by line, I would write to a new file with any changes. In Python, you can open two files at once, which ...


4

(setq letters (get-letters s)) You are setting the same letters variable from different functions; in Emacs Lisp, that sets a global variable which is bad style: (1) that pollutes the global namespace, (2) that could overwrite an existing variable, and (3) the functions are not reentrant and could lead to bad suprises with side-effects. Better introduce ...


5

Your loop approach works but seems a bit convoluted. For instance you could rewrite the for loop this way: for (i in 1:number_of_characters) { end <- i + 3 if (end <= number_of_characters) { temp <- substring(text, i, end) quad_gram_list <- append(quad_gram_list, temp) } } But anyway it's generally better to avoid loops in R. ...


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.


1

On top of the other great answers, here are a few additional comments. Style There is a Style Guide for Python code called PEP 8 and I'd recommend reading it and trying to follow it more or less strictly. It your case, you could change the functions/variables names. Better tests Your test suite can be improved with a few simple details: add the edge ...


4

This can be shortened to a one-liner using regular expressions: import re def isMadeFromRepeatedSubstrings(text): return re.search(r'^(.+?)\1+$', text) The returned object will evaluate true or false, as in the original, and the substring itself is accessible via .groups(1): >>> isMadeFromRepeatedSubstrings("testtest").groups(1) ('test',)


2

My impression is that the code seems good: no suggestions at that level, other than a very minor one. Python's for-else structure is a bit of an oddball: I never use it and a almost never see it used. More to the point, it adds no clarity in this specific case. Just return False outside the loop. Regarding the algorithm, however, I do have a suggestion. It ...


5

The code is relatively concise and easy to read. Here are some points that could be improved: A general thing is the amount of commenting, you should generally resort to comments only when it's hard to make the code self-explanatory. You don't really need to comment each line of the code. stringCopy = (stringOrig+'.')[:-1] # copy string contents You can ...


0

I think extracting methods would help to make the method more readable and easier to understand. This also reduces the ABC size. # frozen_string_literal: true require "ostruct" require "active_support" require "active_support/core_ext" require "minitest/autorun" EVENT_TEXT = { edit_item: 'edited an item' }.freeze REASON_TEXT = { pickup_date: 'a pickup ...


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)...


2

The function for serializing URL parameters is horribly broken since it leaves out URL escaping. Don't invent these functions yourself. Since you're from a Java background, have a look at Apache Commons and Spring Framework, they already implemented this function and took care about all edge cases. There's probably a C++ library that provides URL encoding. ...


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 ...


5

In randrange, you initialize the random device, the engine, and the distribution on every call. So this is not suitable for every situation, i.e., when performance matters. In serialize_http_args and in general, never query the size of a container when you want to determine whether it is empty or not. For that, you should use empty(). This is idiomatic and ...


7

In general, placing constraints on your passwords, such as that they have x-many numerals and y-many letters, makes your password generation scheme slightly worse; there's no advantage. But sometimes we're required to do silly things. In this situation, it looks like the requirement is to have at least four of each, but that could change, as could the ...


7

Your passwords will be biased, with more letters appearing towards the front of the password and more digits towards the end. A better approach would be to determine how many digits you will have in the password. Then, for each character, determine if it should be a digit based on the number of digits you want to have and the number of characters left to ...


7

Your functions themselves are pretty broad, so I'm not going to review each one. However, I can tell you that what you're probably looking for is a namespace. A namespace is just a way to group together similar functions/classes/static objects. They're a little bit like Java's package in that they can be used to organize your code into related groups. A ...


3

bug You don't reset the offset when there is a mismatch, so "123 easy as b(" also returns True. Just add: else: offset = 0 optional parameter offset The caller of the function should not care about the offset if he wants to check whether a combination is part of the string. I would change the method signature to def find_mutated_string2(...


4

Apart from the other alternative of using pathlib Here are some comments on the code: rsplit strings have also a method [`str.rsplit`][1] which start at the right side of the string. So extracting the parent and leaf is as simple as: parent, leaf = path.rsplit(delimiter, maxsplit=1) delimiter Instead of hardcoding the delimiter in a few places, you ...


10

PurePath.drive allows UNC drives, but yours doesn't. pathlib implements everything you need. Which is available from Python 3.4. Note: This code doesn't require the drive to be set. That can be achieved by checking PurePath.drive if it is needed. from pathlib import PurePath def parse_file_path(path): path = PurePath(path) return str(path.parent), ...


2

In this self-mini-review, let it be clear, I just want to point out several things I do differently now. These were untouched by Toby Speight, so could be beneficial to someone. All of these are opinion-based! Styling points I add spaces around parentheses now, like in this case: bool string_contains_integer ( const std::string & str ) I write ...


5

General remarks Here are some general remarks that could make your code look a little cleaner : Avoid using ; at the end of an instruction unless you have to put multiple instructions in the same line. Document the functions properly: The description of the complition parameter of splitToFitSize isn't well formatted. The correct spelling of complition is ...


0

This is comparatively easy when we use Java streams with anyMatch. Let's look at this program. public class Test2 { public static void main(String[] args) { String a = "Gina Gini Protijayi Soudipta"; String b = "Gini"; System.out.println(WordPresentOrNot(a, b)); }// main private static boolean WordPresentOrNot(String a,...


1

If you want to support an insane large file with a small hardware footprint you should use streaming. Something like public static class Program { public static void Main(string[] args) { string text = @"SOME OTHER TEXT WHITE SPACES AND NEW LINES [HitObjects] 109,192,7241,1,0,0:0:0:0: 256,192,7413,1,0,0:0:0:0: 475,192,75865,1,0,...


0

Thanks for your reviews everyone. I updated my code using the answers and updates in my new code are as below. I now use my void main () only to create an object that can run this code , like this. public static void main(String[] args) { new ArmstrongNumberGenerator().mainMethod(); } I distributed the tasks of getting input and doing ...


0

Thanks for your reviews everyone. Using the ideas in answer I rewrote my code. Here I changed my void main () and use it to only call my methods to run the program. public static void main(String[] args) { new ArmstrongNumberChecker().mainMethod(); } I also separated the tasks by creating methods in my class and handled exceptions in the ...


2

Hello and thanks for sharing your code with us. Readability/Maintainability Variables should only be declared when they are actually used (Unless you are having to work with different scopes). It can become difficult to keep track of what is what when everything is just declared at the top of our scope. We should try to stay away from deeply nested ...


1

Why return this at the end of the constructor? I understand the point of doing it in other methods (e.g. to support chaining) but don't believe it is necessary to do so from a constructor. It is advisable to use const for any value that doesn't need to be re-assigned - this avoid accidental re-assignment later. For example, in getNextChar(), seq and index ...


2

It's clear you're performing the same operation over different ranges of cells. So I'd separate that logic in a Function which you can call with any range you like. Using arrays achieve a speed up if the ranges are large, but for now wait until you think you need it. (Needing to check the cell for .HasFormula will slow down using an array in any case.) The ...


1

The small amount of data doesn't merit the use of arrays. I agree with R. Roe comment on combining the Ranges. But first: V is a very unhelpful helper variable, I would get rid of it. Personally, I use r to iterate rows row, c to iterate columns and cell to iterate cells in a Range Techiniquelly, the two if statements are more efficient than combining a ...


3

The first number is included in the range but the last number is not. That inconsistency is odd. You should document the limitations you set to the input. If your limitations make documentation hard, it's a sign of bad programming. Knowing what I wrote above, right now you to check for both equality and greater than between firstNumber and lastNumber. Just ...


3

It's one big static main method that works only on data from System.in. Start by refactoring the algorithm into a reusable utility method that works with integers. You're working with numbers so requiring the input to be a string is not an improvement (it seems like a cop-out to make the coding easier for you). An armstrong number can not be larger than 4 * ...


1

Feedback Logic flaw I noticed that if I enter a value greater than 2 and less than 9 (e.g. 4) then the only thing written is that value that I entered. Should that be the case? And what about non-integer numbers - should 2.3 be accepted? Keywords, ES-6 features Your code uses the keyword let, which became standard with the ecmascript-61 specification, ...


4

I don't like the name of your function. Find what in string? Something like find_all_substring_indices() better describes what the function does You aren't finding words, you're finding substrings. Your code would find the word "car" twice in "carcar" even though we would consider "carcar" a single word. You mention the re package. Presumably, you're talking ...


5

Your function has two bugs Adds an extra space to the end of the string. Eg for "the cat sat on the mat" you return "eht tac tas no eht tam ". The input string is 22 characters long and the returned string is 23 characters long. Related to the first. If the input string starts with a space the returned string removes it. Eg for " the cat sat on the mat" ...


1

:-) Hello kallis, Could you please clarify why you don't want to put your string in an array ? Indeed, you could use a call back function with a map method on an array of words. The callback function would reverse each word, while keeping them at the same place in the sentence. let str = "I am Javascript" ; const arrStr = (string) => { const string2 ...


7

I would split this into two function, simply because they do different things: First a simple string reverser: function reverseString(input) { var output = ""; for(var i = input.length - 1; i >= 0; i--) { output += input[i]; } return output; } This is an easy function that everybody can understand. But we need to reverse ...


Top 50 recent answers are included