The Stack Overflow podcast is back! Listen to an interview with our new CEO.

New answers tagged

3

I added func BenchmarkSearch(b *testing.B) { c := "Hello, we want to find word Guru, so this #phrase has the word Guru." s := "word Guru" for i := 0; i < b.N; i++ { Search(c, s) } } Then i ran $ go test -v -bench=. -benchmem -memprofile=mem.out It yielded goos: linux goarch: amd64 pkg: test/boyermoor BenchmarkSearch-4 ...


3

Use std::string_view to simplify your code, avoid expensive temporaries, and to make your custom string-type more usable. You have three empty states: (0, nullptr), (0, length-zero-array), (1, length-one-array). Standardize to simplify. One option to remove special cases and still have noexcept-move-ctor would be using (0, static empty string) for all empty ...


3

I. You don't reserve space. Imagine a situation when you need to append a vector of strings of known sizes. You reallocate buffer, and copy its current contents together with appended suffix for each of those. Thus, if you add N small strings of size m each, the whole algorithm runs in N², possibly leaving the heap fragmented heavily. One typical strategy ...


4

Here's some suggestions: Header #include <ostream> incurs a lot of overhead. You do not need the whole std::ostream in the header. #include <iosfwd> is enough. It's std::size_t, not size_t. Also, you forgot to #include <cstddef>. asCString fails to propagate const. Not being implicitly convertible to const char* is one of the basic ...


1

Here's my take on it. I split the vocab into 2 set. The first set, heads if for substrings that start at the beginning of the string, and the second set tails for other substrings. The else clause on a loop gets executed when the loop terminates "normally", but is skipped when break is used. Some people don't like these else clauses, but I find them ...


1

JavaScript Javascript uses camelCase by convention not snake_case Undeclared variables are placed in global scope or throw a parsing error in strict mode. The further a variable's scope is from the current scope the longer it takes to get the reference and thus the slower the code. You have not declared words, capitalized_sentence and more in the testing ...


2

Don't do using namespace std;. inline is really only useful for defining non-template functions in header files. Modern compilers generally decide what functions to actually inline themselves. To use std::isspace correctly we must cast the argument from a char to an unsigned char before passing it into the function. std::regex_match has a version that takes ...


1

That regex visualisation you provided is really neat. It shows that there is a lot of potential overlap in the conditions. You should be able to reduce it down to something similar to this: ^[+-]?\d+(\.\d+)?([Ee][+-]?\d+)?$


1

Generate Hashmap There is a data structure that's well optimized for this task: collections.Counter. It will take any iterable and generate a dictionary with keys being elements of your iterable and values are the number of occurrences: from collections import Counter x, y = 'fairy tales', 'rail safety' c1, c2 = Counter(x), Counter(y) c1 Counter({'a': 2, ...


3

I'd just go with @Roman's suggestion. You should just leave it up to the language to decide what is and isn't valid. I'd make two further suggestions though: I don't think the parameter to is_numeric should be Optional; either conceptually, or to comply with the challenge. None will never be a valid number, so why even check it? I don't think dealing with ...


4

Instead of diving into cumbersome and lengthy regex expressions consider the following improvement/correction: The main thesis for the underlying aspect is: Numeric literals containing a decimal point or an exponent sign yield floating point numbers. https://docs.python.org/3.4/library/stdtypes.html#numeric-types-int-float-complex Therefore Python ...


2

The first step in your method is to determine the longest common prefix. Here it would be sufficient to determine the length of the longest common prefix. Building the prefix string itself is not necessary at this point. The next step is to decrease that length until it divides both string lengths. An explaining comment would be helpful here. We still don't ...


4

In Python, your check_palindrome function can be made more efficient and pythonic: def check_palindrome(original_string): """Returns true if an input string is a palindrome""" original_string = original_string.lower() return all(r == o for r, o in zip(reversed(original_string), original_string[:len(original_string)//2])) This only iterates ...


2

The following is a basic syntax and usage pass without looking into your algorithm in too much depth. I'll first show the suggested code and then highlight significant differences where it can offer improvements on the original. #!/usr/bin/env python3 from typing import Iterable, Set def tokenize( text: str, vocab: Set[str], ...


9

Boolean expression returns This applies to both your Javascript and Python implementations: if (reversed_string_1 === original_string && reversed_string_2 === original_string && reversed_string_3 === original_string && reversed_string_4 === original_string) { return true; // If the original string is not a palindrome } else {...


1

You can use guava's Splitter class, splitting on & and with key/value separator =. By looking at the source code it seems the split implementation is O(n): import com.google.common.base.Splitter; import java.util.Map; import java.util.Map.Entry; ... String input = "key={value}&key2&key3={value3}"; Map<String, String> map ...


2

To be honest: Neither. Both are equally unnecessarily complicated and difficult to read. They use old-fashioned, maybe over-optimized techniques instead of Java/OOP features. The code lacks readable variable names and any documentation for the reader/reviewer or for other programmers who need to use this. And finally (if I read it correctly) they have ...


2

Being myself new to rust, take the following with a grain of salt. I would welcome further edits. I think, generally, that there are two things your code is trying to do. On one hand, it's about string tokens and concatenation. On the other, there's the solving the 99 bottles problem. 99 Bottles For this problem, your approach seems complex and results in ...


1

boolean result = Arrays.asList(sentence.split("\\s+")).contains(word); If you want this solution to answer irrespective of lowercase or uppercase, then you can use String.toLowerCase() for all given inputs. boolean result = Arrays.asList(sentence.toLowerCase().split("\\s+")).contains(word.toLowerCase());


6

As @AustinHastings pointed out, the itertools.product solution below doesn't work right unless you start at the beginning. So here's an alternate solution: DIGIT = '0123456789' LETTER = 'ACDEFGHJKMNPQRTUVWXYZ' DIGLET = DIGIT + LETTER def mbi_gen(start=None): pattern = [DIGIT[1:], # leading non-zero digit LETTER, ...


11

This is a fun problem. I've taken the liberty of writing an alternate implementation, which I will describe below. Note that I've not focused too much on performance at all, only on simplicity and good structure. Suggested from typing import Iterable N = 11 class MBI: letters = tuple('ACDEFGHJKMNPQRTUVWXYZ') numbers = tuple(str(i) for i in range(...


2

Thanks to @Shepmaster's comment referring to one of his previous answers, I was able to make the process nicer, by using env::args as an Iterator. By doing so, it became much easier to switch to using a match statement, and avoids all the string concatenation I mentioned in my question. I've also managed to add the conversion from hex and octal values to ...


6

Explicit is better than implicit. Simple is better than complex. Readability counts. The easiest way to make it faster would be to simply convert it into code: def generate_mbis() -> Iterator[str]: """ Generate MBIs, starting with 1A00A00AA00. An MBI is a string with the following rules: [1-9] # No ...


0

Objects If there's a place to drink OOP kool-aid, it's Java. Your static main should be much more limited. Consider: Make findOccurrences an instance, not static, method Give Matrix a convenience constructor accepting a Scanner, and another constructor accepting two ints Make patternMatrix and textMatrix instance member variables Remove all method ...


0

Depending on how exactly you want to output the punctuation, possibilities range from the one-liner def split_merging_punctuation(line): return ("".join(cs) for _, cs in itertools.groupby(line, is_punctuation)) to a function that produces output equivalent to yours: def split_not_merging_punctuation(line): for is_p, chars in itertools.groupby(line,...


2

This kind of function could be designated for an API and should be clear for every developer that would use it. As you probably know , there is already a split method in string object. This method doesn't return separators (as they are usually useless). For example: "this.is.codereview".split('.') outputs: ['this', 'is', 'codereview'] The naming of ...


3

First things: You can trim off a little just by making the loop tighter. Python does pretty cool "for" loops: for char in chars will loop through every character in the list 'chars'. That means you don't need to deal with the variable 'i'. In fact, you don't even need to cast the input to a list called 'chars'. Python can iterate through a string as if it ...


14

Billy Mays here for the regex library! It's API-compatible with the standard Python re module. It's powered by open source, and it's safe for colored fabrics and carpets! The regex library offers things like \p{Punctuation}, which is actually a shorthand form of p{Punctuation=Yes} which is really a shortening of p{General_category=Punctuation}. If you can ...


8

Return Simplification This def is_punctuation(char): return True if unicodedata.category(char).startswith("P") else False can be def is_punctuation(char): return unicodedata.category(char).startswith("P") Since unicodedata.category(char).startswith("P") evaluates to a boolean expression, you can return the expression. Type Hints These function ...


-2

I like the original code best. I don't know of a better way than iterating through the string and the original code is actually pretty readable and likely no slower than any of the other options.


2

You could use Iterator:any to write this in a succinct way: fn string_ends_with_any(s: String, suffixes: Vec<&str>) -> bool { return suffixes.iter().any(|&suffix| s.ends_with(suffix)); } Because this pattern returns true on first match of the predicate: for suffix in &suffixes { if s.ends_with(suffix) { return true; ...


1

String vs. line Read string of any length in C User input in C is better described as reading a line than a string. A string is a contiguous sequence of characters terminated by and including the first null character. A text stream is an ordered sequence of characters composed into lines, each line consisting of zero or more characters plus a ...


3

Please improve the variable names - it's not at all obvious what a, k and p are (and conventionally, p is usually used for a small-scope pointer, not an integer). Always check whether malloc() (or calloc(), or realloc()) returns a non-null pointer before dereferencing. The algorithm is so opaque that I'm not going to attempt to unravel it. It's nowhere ...


8

I don't have much to say, but this stuff does look useful. The types are designed to be exposed to the world, so it's transparent to the consumer and could make the intentions clear. There is one huge problem: public string Text { get; set; } Anyone can change this value and by-pass all the rules: I assume this is a typo and you intended for this to be ...


2

There are not much to say other than the usual missing argument null check: It is valid to write the following: string test = null; test.RemoveDuplicateChars(); and RemoveDuplicateChars will be called with a null for the this argument text. Therefore you'll have to test for null: public static string RemoveDuplicateChars( this string text, Func&...


3

Welcome to Code Review and welcome back to C++! Here's my two cents: Use <cmath> instead of the deprecated <math.h>. Sort the #include directives according to alphabetical order. This is not true: namespace { // anonymous namespace, things in here are "private" to wu_manber namespace Everything inside this anonymous namespace is effectively ...


6

Usability I would have expected Optional to transform null and whitespace only content into String.Empty, not the around way around. Optional(string text) => Text = IsNullOrWhiteSpace(text) ? string.Empty : text; And Required to throw on null or whitespace only content. Required(string text) => Text = !IsNullOrWhiteSpace(text) ? text : throw new ...


9

Not sure that adding a 7-line validator class per validation rule (plus typecasting abuse) is any shorter/better than a set of more straightforward composable validating one-liners, something like: public static class ValidatingTransformers { public static T ThrowsIfNull<T>(this T s, string msg = "") => s != null ? s : throw new ...


8

Edit: the tone of this might seem a bit negative, so I'll add that this was a fun one to review in hopes of lightening the mood ;) Miscellaneous thoughts: This is horrifying! Why did you do this?! You can just about get away with this for properties, but for method calls with required/optional fields, a FormatException will be inadequate (an ...


0

Here's another approach. It takes in an arbitrary iterable and streams out characters. This could be useful if you passed in an asynchronous generator, such as if the items in the list were being received from a remote location, or being typed in by the user. def print_iterable(iterable): iterator = iter(iterable) to_print = None try: ...


Top 50 recent answers are included