text stringlengths 1 2.12k | source dict |
|---|---|
javascript
<div class="result-number font-bold">error</div>
</div>
</div>
</template>
<script src="./script.js"></script>
</body>
</html>
expand the code snippet to full screen to see the button
Answer: Review
Your code is way too complex
The Card object is not a card, rather it is a utility function to copy a template. There is no need for it or you could have implemented it as a singleton with static functions and properties to create cards.
The generate card function has complicated what is just a simple substitution task. There are about 50 lines of code for a task than can be done in a quarter of that.
The HTML template contains unneeded content, Eg <div class="operator">error</div> that has typos, eg <div class="first-number flex-grow">errpr</div>
You can use eval (it is not evil) to evaluate the result of the operation on the two random values. This will greatly reduce the complexity of the source code. see rewrite.
Use String.padStart or String.padEnd to pad strings. This will simplify the function
function addZeroPrefix(num) {
if (num < 10) {
return `0${num}`;
}
return num;
}
to
const addZeroPrefix = num => (num + "").padStart(2, "0");
Avoid indirect calls You use a function to call a function.
document.querySelector("#btn").addEventListener("click", () => { generateCard(); });
This is redundant and just makes code noisier and thus harder to maintain and read. The line can just be
document.querySelector("#btn").addEventListener("click", generateCard);
Random Bug
You state that the values are from 1 - 99 yet you generate random values via Math.round(Math.random() * 100); which will create values 0 to 100 with the values 0 and 100 being half as likely as any of the other values.
To create a random value within a range and a even distribution you can use something like.
const rnd = (min, max) => Math.floor(Math.random() * (max - min) + min);
const randNumber = rnd(1, 99); | {
"domain": "codereview.stackexchange",
"id": 43831,
"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",
"url": null
} |
javascript
Rewrite
Rewrite uses a static object Card to create a card from a template via the function Card.create. There is no need to instantiate the class.
There are helper functions at the top to simplify and reduce the verbosity of DOM APIs.
The function rnd and rndItem create random values.
generateCard uses Card to create a card and then adds it to the page.
I have remove the scroll into view as I could not see why it is needed. To add a card the button needs to be in view, and if the button can be see the next card will also be in view.
I removed all the CSS styling as you did not provide the CSS (only a indirect reference "https://cdn.tailwindcss.com") and added some basic CSS just for the answer.
Using templates forces you to use classes to reference elements. Ideally element ids are best for referencing elements as it means you do not need to change code if you change the CSS and class names. Personally I would have created the card in code rather than via a template | {
"domain": "codereview.stackexchange",
"id": 43831,
"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",
"url": null
} |
javascript
const qry = (qStr, el = document.body) => el.querySelector(qStr);
const append = (el, ...sibs) => sibs.reduce((p, sib) => (p.appendChild(sib), p), el);
const rnd = (min, max) => Math.floor(Math.random() * (max - min) + min);
const rndItem = items => items[rnd(0, items.length)];
class Card {
static create() {
const card = qry("div", qry("#cardTemplate").content).cloneNode(true);
const num1 = rnd(1, 99) + "", num2 = rnd(1, 99) + "", operator = rndItem("+-*");
const result = (eval(num1 + operator + num2) + "").padStart(2, "0");
qry(".first", card).textContent = num1.padStart(2, "0");
qry(".second", card).textContent = num2.padStart(2, "0");
qry(".result", card).textContent = result;
qry(".operator", card).textContent = operator;
return card;
}
}
function generateCard() { append(container, Card.create()); }
generateBtn.addEventListener("click", generateCard);
<div id="container"></div>
<div><button id="generateBtn">Generate</button></div>
<template id="cardTemplate">
<div>
<div>
<div class="first"></div>
<div class="operator"></div>
</div>
<div>
<div class="second"></div>
<div>=</div>
</div>
<div>
<div class="result"></div>
</div>
</div>
</template> | {
"domain": "codereview.stackexchange",
"id": 43831,
"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",
"url": null
} |
python, algorithm, classes
Title: ReversibleList: a list that is "reversed" in O(1) time
Question: UPDATE: Thanks everyone for the suggestions! I made a follow up version here which fixes the bugs, incorporates the feedback, and has more tests.
A ReversibleList behaves like a normal list when ReversibleList.reversed == False, but it behaves as if it had been reversed when ReversibleList.reversed == True. The trick is that the underlying list is never actually reversed. This can be a boon for performance [citation needed] if whatever one's doing requires reversing and unreversing a particular list many times, or reversing many lists.
Any suggestions for improvement are welcome! Interested in whether my subclass is properly written and whether the concept makes sense to you/is self-consistent. I have overridden only a few of list's method - just enough for my use case and I'm aware there may be other list methods I may need to override in the future for expanded use cases.
Thanks in advanced for any suggestions!
Implementation
class ReversibleList(list):
def reverse(self):
self.reversed = True
def forwardAll(self):
self.reversed = False
def toggleDirectionl(self):
self.reversed = not self.reversed
def __init__(self, iterable):
super().__init__(iterable)
self.reversed = False
def __getitem__(self, key):
if self.reversed:
key = self._getReverseKey(key)
if isinstance(key, slice):
return ReversibleList(super().__getitem__(key))
return super().__getitem__(key)
def __setitem__(self, key, val):
if self.reversed:
key = self._getReverseKey(key)
if isinstance(key, slice) and not isinstance(val, type(self)):
super().__setitem__(key, reversed(val))
return
super().__setitem__(key, val) | {
"domain": "codereview.stackexchange",
"id": 43832,
"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, algorithm, classes",
"url": null
} |
python, algorithm, classes
def __delitem__(self, key):
if self.reversed:
key = self._getReverseKey(key)
return super().__delitem__(key)
def __str__(self):
if self.reversed:
return '[' + ', '.join(map(str, reversed(self))) + ']'
return super().__str__()
def __repr__(self):
return f'ReversibleList({super().__repr__()})'
@classmethod
def _invalidKeyTypeErrorMsg(cls, key):
return f'list indices must be integers or slices, not {type(key).__name__}' # same error one gets when doing [0,1,2][1, 2]
def _getReverseKey(self, key):
if isinstance(key, slice):
# PRECONDITION: key.step == 1
N = len(self)
i, j, _ = key.indices(len(self))
assert i >= 0 and j >= 0, 'I assumed that slice.indices returns positive values for start and stop, but was wrong.'
i = i or -N
j = j or -N
return slice(-j, -i)
if not isinstance(key, int):
raise TypeError(type(self)._invalidKeyTypeErrorMsg('key'))
return -1-key
Usage
a = ReversibleList([0, 1, 2, 3, 4, 5])
print(a[1]) # 1
print(a) # [0, 1, 2, 3, 4, 5]
print(a[:]) # [0, 1, 2, 3, 4, 5]
print(repr(a)) # ReversibleList([0, 1, 2, 3, 4, 5])
a.reverse()
print(a[1]) # 4
print(a) # [5, 4, 3, 2, 1, 0]
print(a[:]) # [5, 4, 3, 2, 1, 0]
print(repr(a)) # ReversibleList([0, 1, 2, 3, 4, 5])
a[:] = a
print(a) # [5, 4, 3, 2, 1, 0]
a[2:5] = a[2:5]
print(a) # [5, 4, 3, 2, 1, 0]
print(a[2:5]) # [3, 2, 1]
a[2:5] = [3, 2, 1]
print(a) # [5, 4, 3, 2, 1, 0]
a[2:5] = ReversibleList([1, 2, 3])
print(a) # [5, 4, 3, 2, 1, 0] | {
"domain": "codereview.stackexchange",
"id": 43832,
"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, algorithm, classes",
"url": null
} |
python, algorithm, classes
a[2:5] = ReversibleList([1, 2, 3])
print(a) # [5, 4, 3, 2, 1, 0]
Answer: Consider composition over inheritance
Doing inheritance right is very hard.
Keep in mind that subclass coupling (when class A is a subclass of class B) is the strongest type of coupling between two classes.
I suggest to only subclass a class when its documentation explicitly encourages that.
This is the case for example in frameworks such as Django.
I cannot find such guidance in Python's docs on data structures,
and I would take that as a clue.
Also note that overriding just the methods for your use case doesn't prevent calling other methods,
which may work in unexpected ways.
For example I would expect from a list r that r[:] and list(r) and for x in r will produce elements in consistent order with [r[i] for i in range(len(r))],
but this is not what happens when r is a ReversibleList that's currently in reversed mode, even though it is a list.
Composition is a lot simpler and widely recommended.
Instead of inheriting from list,
make the class contain a list attribute,
and implement precisely the methods that you want to support.
Calling an unsupported operation will be a hard failure,
rather than something unsupported without a warning.
Consider for example:
class ReversibleListView:
"""
A view over a list of items.
Supports accessing items with integer indexes using [] operator.
Can present a reversed view in O(1) time.
"""
def __init__(self, items):
self.items = items
self.reversed = False
def reverse(self):
self.reversed = not self.reversed
def __getitem__(self, key):
return self.items[self._key(key)]
def __setitem__(self, key, value):
self.items[self._key(key)] = value
def _key(self, key):
if not isinstance(key, int):
raise TypeError("indices must be integers")
if not self.reversed:
return key | {
"domain": "codereview.stackexchange",
"id": 43832,
"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, algorithm, classes",
"url": null
} |
python, algorithm, classes
if not self.reversed:
return key
size = len(self.items)
if key < 0:
key += size
return size - 1 - key
Demonstrate usage with asserts instead of printing
print statements and the expected outputs as comments are weak.
It's better to use assert statements,
which also make it easy to make changes to the code and verify it still works.
def tests():
def to_list(r: ReversibleListView) -> list:
return [r[i] for i in range(len(r.items))]
a = ReversibleListView([0, 1, 2, 3, 4, 5])
assert a[1] == 1
assert to_list(a) == [0, 1, 2, 3, 4, 5]
a[1] = 9
assert to_list(a) == [0, 9, 2, 3, 4, 5]
a = ReversibleListView([0, 1, 2, 3, 4, 5])
a.reverse()
assert a[1] == 4
assert to_list(a) == [5, 4, 3, 2, 1, 0]
a[1] = 9
assert to_list(a) == [5, 9, 3, 2, 1, 0]
if __name__ == '__main__':
tests() | {
"domain": "codereview.stackexchange",
"id": 43832,
"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, algorithm, classes",
"url": null
} |
c++, performance, hash-map, k-sum
Title: Hashtable solution to 2 sum
Question: public:
vector<int> twoSum(vector<int>& nums, int target) {
int size = nums.size();
vector<int> toRet;
unordered_map<int,pair<int,int>> myMap;
for(int i = 0; i < size; ++i){
myMap.emplace(nums[i],make_pair(nums[i],i));
}
for(int i = 0; i < size; ++i){
int toFind = target - nums[i];
if(myMap[toFind].first == toFind && myMap[toFind].second != i){
toRet.push_back(i);
toRet.push_back(myMap[toFind].second);
return toRet;
}
}
return toRet;
}
};
How do I make this run faster? I can't think of anything. Right now, it is slower than 47% of submissions. Could you please provide some hints?
Answer: It's possible to solve this in a single pass:
Use a map<int, int> to store values you've seen so far, and their first index, let's call it seen
For each value, let's call it current:
Is target - current in seen?
If yes, return the pair of the index in the map and the current index
If not, and current is not yet in seen, then put current into seen and the current index
If you reached the end of the collection without returning, then there is no such pair that sum to target.
This algorithm should be faster than the posted code,
because:
it works in a single pass
uses less memory (unordered_map<int,pair<int,int>> replaced with unordered_map<int, int>)
uses fewer conditions | {
"domain": "codereview.stackexchange",
"id": 43833,
"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, hash-map, k-sum",
"url": null
} |
python, python-3.x, algorithm, object-oriented, dynamic-programming
Title: Segmentation of list to minimize the largest sum
Question: I have written the following code for diving a list 'seq' into 'k' segments such that the maximum sum of each segment is minimized. I have used dynamic programming to solve this problem. But my class "Segmentation" seems a little overwhelmed with too many redundant functions. Can anybody give me a few suggestions on how can I improve this code? I am even using separate functions for returning boolean values and calculating the average. Also using raise SystemExit because I do not want to add new library only for this line. Please provide your valuable feedback on the below code.
"""
Calculate the optimal k-segmentation of a sequence using dynamic programming
Author: Jahid Chowdhury Choton (choton@ksu.edu)
The sub-problems for dynamic programming are given below:
Base case: Opt(i,j,M) = cost(S[:i]-M) if j==1
Recursion: Opt(i,j,M) = min( max( Opt(l,j-1, M), cost(S[l:i])-M) for l=1,2,...,i)
"""
class Segmentation:
def __init__(self, seq, k):
self.seq = seq
self.k = k
self.n = len(seq)
self.M = self.avg() # Parameter M is taken to be the average of the sequence
self.opt_val, self.opt_segments = self.opt() # Calculate optimal values and segmentation
def avg(self): # To calculate average of sequence seq
return sum(self.seq) / self.n
def is_odd(self, val): # To return a boolean value 0 or 1
return val % 2 | {
"domain": "codereview.stackexchange",
"id": 43834,
"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, algorithm, object-oriented, dynamic-programming",
"url": null
} |
python, python-3.x, algorithm, object-oriented, dynamic-programming
def is_odd(self, val): # To return a boolean value 0 or 1
return val % 2
def initialize_cost_and_dp(self): # To initialize cost array, DP array and traceback array
cost_sum = [0] * (self.n + 1) # Initialize cost array with zeros
dp = [[-1.0 for _ in range(self.n+1)] for _ in range(2)] # Tabulation array for DP
tb = [[[] for _ in range(self.n+1)] for _ in range(2)] # Traceback array for optimal segmentation
for i in range(0, self.n): # O(n)
# Add the elements of the sequence seq into cost array
cost_sum[i + 1] = self.seq[i] + cost_sum[i]
# Initialize DP array with infinity values
dp[0][i+1] = float('inf')
dp[1][i+1] = float('inf')
# print(cost_sum, dp, tb)
return cost_sum, dp, tb
def generate_segmentation(self, traceback): # To generate k-segmentation of sequence seq using traceback array
# Separate the traceback array into two parts starts and ends
starts = traceback[self.is_odd(self.k)][self.n]
ends = starts[1:] + [self.n]
# print(starts, ends)
k_segments = [self.seq[s:e] for s, e in zip(starts, ends)] # Concatenate the two parts for optimal segments
return k_segments | {
"domain": "codereview.stackexchange",
"id": 43834,
"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, algorithm, object-oriented, dynamic-programming",
"url": null
} |
python, python-3.x, algorithm, object-oriented, dynamic-programming
def opt(self): # To calculate the optimal value and segmentation using dp
if self.n < self.k:
print("Not enough cells for k-segmentation, now exiting the program...")
raise SystemExit # Program will terminate if k is less than the segmented cells
costSum, dp, tb = self.initialize_cost_and_dp() # Get the initial values of cost array, DP array and TB array
for i in range(1, self.k + 1): # O(k)
for j in range(1, self.n + 1): # O(n)
for l in range(i - 1, j): # O(n-k)
curr_val = max(dp[self.is_odd(i - 1)][l],
abs((costSum[j] - costSum[l]) - self.M)) # Check the current max value
prev_val = dp[self.is_odd(i)][j] # Check the previous value
if curr_val < prev_val: # Check the min value and update it in DP and traceback array
dp[self.is_odd(i)][j] = curr_val # Update the min value in dp array
tb[i % 2][j] = tb[self.is_odd(i - 1)][l] + [l] # Update the breakpoint in traceback array
optimal_value = dp[self.is_odd(self.k)][self.n] # Calculate the optimal value
optimal_segments = self.generate_segmentation(tb) # Generate the optimal segments
return optimal_value, optimal_segments
# Driver Code
def main():
# S = [3, 7, 7, 33]
# S = [3, 4, 2, 2, 6, 7, 43, 100000, 4, 3, 11]
# S = [3, 4, 2, 2, 6, 7, 43, 50, 43, 3, 11]
# S = [3, 4, 2, 2, 6, 7, 13, 10, 43, 50, 5]
# S = [1,1,1,5,5,5]
S = [3,8,7,1,11]
k = 3
# Call the class Segmentation
k_segmentation = Segmentation(S, k)
# Get the optimal value and segmentation
optimal_values = k_segmentation.opt_val
optimal_segmentation = k_segmentation.opt_segments
# Print the optimal value and segmentation
print("Optimal value =", optimal_values)
print("Optimal k-segmentation = ", optimal_segmentation) | {
"domain": "codereview.stackexchange",
"id": 43834,
"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, algorithm, object-oriented, dynamic-programming",
"url": null
} |
python, python-3.x, algorithm, object-oriented, dynamic-programming
if __name__ == '__main__':
main()
Answer: One could approach this from the goal:
What is the business of a Segmentation instance, what are its business methods? You tagged object-oriented: What is the value added by having a Segmentation(sequence, k) instance over an opt(sequence, k) function?
In your main(), you don't (syntactically) call any method of k_segmentation.
A first improvement would be to take the call to opt() out of the constructor, rendering "the opt_… attributes" obsolete.
While I can "see" the segmentation part opt() returns, what is that optimal_value?
Document both in a docstring for opt()!
To get some advantage from a Segmentation instance, have it keep information useful for more than one access.
If you construct it with just the sequence and pass the number of parts as a parameter to opt(k), you can look for information independent of k - M is, cost_sum looks a candidate.
The methods are commented for what they do. Not bad.
Docstrings would be even better, starting with help(Segmentation.opt).
With opt(), a description of how it works would add value.
Naming
• is_odd() is named for how it works - I'd prefer current(i) and previous(i).
(There is one instance of i % 2 not substituted.)
• costSum isn't snake_case (nor is M).
• internal methods like initialize_cost_and_dp maybe should start with an underscore.
• Method/function names with an and are a code smell.
From Python 3.10, generate_segmentation() could use itertools.pairwise.
I think all that indexing with [self.is_odd(i)] for current (i - 1 for previous) reduces readability - if you want to keep the mechanism, you can use descriptors -
I'd likely go for named attributes & an explicit swap at the end of the outer loop. | {
"domain": "codereview.stackexchange",
"id": 43834,
"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, algorithm, object-oriented, dynamic-programming",
"url": null
} |
java, rest
Title: Adaptive REST api rate limiter
Question: I'm building a java client interacting with a server that returns responses with rate limit info in the headers:
rate limit per period (for instance 10 per second)
remaining limit left until next period
start of next period (epoch time in seconds)
So I built a rate limiter that doesn't follow a fixed rate, but adapts to the info from the responses. The code looks as follows:
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.ws.rs.core.Response;
public final class BolRateLimiter {
private static final String HEADER_KEY_LIMIT = "X-RateLimit-Limit"; //$NON-NLS-1$
private static final String HEADER_KEY_REMAINING = "X-RateLimit-Remaining"; //$NON-NLS-1$
private static final String HEADER_KEY_RESET = "X-RateLimit-Reset"; //$NON-NLS-1$
private final Semaphore limiter = new Semaphore(1, true);
private final AtomicBoolean init = new AtomicBoolean(true);
private final AtomicBoolean resetting = new AtomicBoolean(false);
public void limit() {
try {
limiter.acquire();
} catch (final InterruptedException e) {
Thread.currentThread().interrupt();
}
}
public void read(final Response r) {
if (init.compareAndSet(true, false)) {
final String remainstr = r.getHeaderString(HEADER_KEY_REMAINING);
final int remain = parseInt(remainstr);
limiter.release(remain);
}
if (resetting.compareAndSet(false, true)) {
final String limitstr = r.getHeaderString(HEADER_KEY_LIMIT);
final String resetstr = r.getHeaderString(HEADER_KEY_RESET);
final int limit = parseInt(limitstr);
final long reset = SECONDS.toMillis(parseLong(resetstr));
new Thread(() -> {
try {
final long now = currentTimeMillis();
final long delta = reset - now + 100l;
MILLISECONDS.sleep(delta);
limiter.drainPermits();
limiter.release(limit);
resetting.set(false); | {
"domain": "codereview.stackexchange",
"id": 43835,
"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, rest",
"url": null
} |
java, rest
} catch (final InterruptedException e) {
currentThread().interrupt();
}
}).start();
}
}
}
And it's used in for instance the following context:
@Override
public BolProcess checkProcess(final String processid) {
--> limiter1.limit(); //
final Invocation request = endpoints //
.path("process-status") //$NON-NLS-1$
.path(processid) //
.request() //
.header(AUTHORIZATION, tokenprov.getToken()) //
.header(ACCEPT, HeaderAcceptValueJson) //
.buildGet(); //
try (final Response response = request.invoke()) {
--> limiter1.read(response);
if (response.getStatusInfo().getFamily().equals(Response.Status.Family.SUCCESSFUL))
return response.readEntity(BolProcess.class);
throw response.readEntity(BolEndpointException.class);
}
}
The semaphore starts with 1 permit, so the client can initially send just 1 message before the rate limiter blocks. When the rate limiter reads its first response, the semaphore is instructed to release more permits.
Besides that, the limiter reads from the response header the rate limit as well as the time to reset. It then starts a thread that will reset the semaphore permits once the time to reset passed. The rate limiter then ignores rate limit info from subsequent responses, until thread reset the semaphore.
I need this rate limiter to work in a parallel/concurrent context, like parallel streams. In that context it does not work to read the remaining limit left from a response (except from the first). By the time the rate limiter would read a response and the remaining limit left, that limit is already outdated.
So am I overlooking anything here? I'd be happy to get your feedback. Thanks in advance!
Answer: There are a few holes that I see: | {
"domain": "codereview.stackexchange",
"id": 43835,
"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, rest",
"url": null
} |
java, rest
Answer: There are a few holes that I see:
The first thread can get into the init.compareAndSet() block and then stall out, causing later threads to not progress until the first thread makes it to the release line. If the first request fails for any reason, no other requests will ever be sent out.
Any thread can stall out while in the resetting.compareAndSet() block. If it sleeps past a time limit boundary, threads will be blocked until it wakes back up.
Responses can come back out of order, so the response that goes into the resetting.compareAndSet() block may not have the correct number of permitted calls remaining.
If a thread acquires a permit and then sleeps until the semaphore is resized, it may cause you to unexpectedly hit the rate limit.
There is always a way you can unexpectedly get a rate limit failure. A thread acquire a valid semaphore permit, then sleep until after all the quota has been used for the cycle after the current one, and then the thread wakes up and sends its request during that cycle. There is no way to protect against this that I am aware of. | {
"domain": "codereview.stackexchange",
"id": 43835,
"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, rest",
"url": null
} |
java, rest
It is reasonable for the implementation to attempt to respect the rate limit by not sending extraneous requests, but the implementation should be able to handle rate limiting failures more cleanly than throwing the same exception as any other error response. Requests that hit the rate limit should be retried. There should also be monitoring to ensure you aren't backing up on your end because you're generating more requests than the service API can handle over time. That may be in the code, but would probably be better in tooling.
Other:
I don't know what a "BolRateLimiter" is. Avoid acronyms where possible to enhance readability.
Strive for maximally readable code. response would read more cleanly than r.
When indicating a numeric value is a long, prefer L to l for readability reasons.
Random musing:
You may consider extending Semaphore into DrainingSemaphore, which would give you access to reduce permits(). You could then try something like the code below (100% untested):
private final DrainingSemaphore semaphore = new DrainingSemaphore(Integer.MAX_VALUE, true);
private final Lock lock = new ReentrantLock();
private long startOfNextPeriod = 0;
public void read(final Response response) {
long responseStartOfNextPeriod = ..;
int responseRequestsRemaining = ..;
try {
// can't let multiple responses update the semaphore
lock.lockInterruptibly();
// first request of a new period
if (responseStartOfNextPeriod > startOfNextPeriod) {
startOfNextPeriod = responseStartOfNextPeriod;
semaphore.drainPermits();
semaphore.release(responseRequestsRemaining);
return;
} | {
"domain": "codereview.stackexchange",
"id": 43835,
"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, rest",
"url": null
} |
java, rest
// request from the current period
if (responseStartOfNextPeriod == startOfNextPeriod) {
// case: permit from prior period, call happens this period
// drain semaphore permits down to the correct value
semaphore.drainToSize(responseRequestsRemaining);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} finally {
lock.unlock();
}
// Requests from a prior period can be ignored
} | {
"domain": "codereview.stackexchange",
"id": 43835,
"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, rest",
"url": null
} |
recursion, swift, depth-first-search, trie, backtracking
Title: Exceeded time limit on Trie search with Backtracking using Swift
Question: I have been trying to solve Trie related problems over at leet code and came across this interesting problem 211. Design Add and Search Words Data Structure
Here is the question for convenience:
211. Design Add and Search Words Data Structure
Design a data structure that supports adding new words and finding if a string matches any previously added string.
Implement the WordDictionary class:
WordDictionary() Initializes the object.
void addWord(word) Adds word to the data structure, it can be matched later.
bool search(word) Returns true if there is any string in the data structure that matches word or false otherwise. word may contain dots '.' where dots can be matched with any letter.
Example:
Input
["WordDictionary","addWord","addWord","addWord","search","search","search","search"]
[[],["bad"],["dad"],["mad"],["pad"],["bad"],[".ad"],["b.."]] Output
[null,null,null,null,false,true,true,true]
Explanation
WordDictionary wordDictionary = new WordDictionary();
wordDictionary.addWord("bad"); wordDictionary.addWord("dad");
wordDictionary.addWord("mad"); wordDictionary.search("pad"); // return
False wordDictionary.search("bad"); // return True
wordDictionary.search(".ad"); // return True
wordDictionary.search("b.."); // return True
Constraints:
1 <= word.length <= 25
word in addWord consists of lowercase English letters.
word in search consist of '.' or lowercase English letters.
There will be at most 3 dots in word for search queries.
At most 104 calls will be made to addWord and search. | {
"domain": "codereview.stackexchange",
"id": 43836,
"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": "recursion, swift, depth-first-search, trie, backtracking",
"url": null
} |
recursion, swift, depth-first-search, trie, backtracking
I got some help yesterday with a similar question on how to optimize my Trie implementation and tried my best to incorporate those into my solution to this question.
I got a solution to work with Trie and backtracking, however, I once again ran into the Time Limit exceeded conundrum.
I came across this Python solution on Youtube and tried to implement it using Swift, however that did not help.
Here is the search function:
private class WordDictionary {
var root: TrieNode
class TrieNode {
var next = [Character: TrieNode]()
var isWordEnd = false
}
init() {
root = TrieNode()
}
func addWord(_ word: String) {
var node = root
for char in word {
node = addInternal(char, at: node)
}
node.isWordEnd = true
}
func addInternal(_ char: Character, at node: TrieNode) -> TrieNode {
if let nextNode = node.next[char] {
return nextNode
}
let nextNode = TrieNode()
node.next[char] = nextNode
return nextNode
}
func search(_ word: String) -> Bool {
func dfs(index: String.Index, at node: TrieNode) -> Bool {
var currentNode = node
var currentIndex = index
while currentIndex < word.endIndex {
let currentChar = word[currentIndex]
if currentChar == "." {
if let nextNodes = Array(currentNode.next.values) as? [TrieNode] {
for nextNode in nextNodes {
var nextIndex = currentIndex
word.formIndex(after: &nextIndex)
if dfs(index: nextIndex, at: nextNode) {
return true
}
}
} | {
"domain": "codereview.stackexchange",
"id": 43836,
"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": "recursion, swift, depth-first-search, trie, backtracking",
"url": null
} |
recursion, swift, depth-first-search, trie, backtracking
}
}
}
return false
}
if let nextNode = currentNode.next[currentChar] {
currentNode = nextNode
word.formIndex(after: ¤tIndex)
continue
}
return false
}
return currentNode.isWordEnd
}
return dfs(index: word.startIndex, at: root)
}
} | {
"domain": "codereview.stackexchange",
"id": 43836,
"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": "recursion, swift, depth-first-search, trie, backtracking",
"url": null
} |
recursion, swift, depth-first-search, trie, backtracking
This seems to be working correctly on these test cases:
private func test1() {
let wordDictionary = WordDictionary()
wordDictionary.addWord("baad")
wordDictionary.addWord("dad")
wordDictionary.addWord("mad")
print(wordDictionary.search("baa")) // return False
print(wordDictionary.search("bad")) // return False
print(wordDictionary.search("baad")) // return True
print(wordDictionary.search(".ad")) // return True
print(wordDictionary.search("b..d")) // return True
print(wordDictionary.search("pad")) // return False
print(wordDictionary.search("bad")) // return False
print(wordDictionary.search("b.ad")) // return True
print(wordDictionary.search("mad")) // return True
print(wordDictionary.search("bam")) // return False
}
private func test2() {
let wordDictionary = WordDictionary()
wordDictionary.addWord("a")
wordDictionary.addWord("a")
print(wordDictionary.search(".")) // return True
print(wordDictionary.search("a")) // return True
print(wordDictionary.search("aa")) // return False
print(wordDictionary.search("a")) // return True
print(wordDictionary.search(".a")) // return False
print(wordDictionary.search("a.")) // return False
}
However, I get a time limit exceeded exception on this test case
I am not sure where the bottle neck and as at first glance, I cannot see any opportunity for memoization to improve the performance.
I am sure there might be other / more optimal solutions besides using a Trie, however, I am trying to get an optimal solution using a Trie since I am currently trying to improve my understanding of this topic. | {
"domain": "codereview.stackexchange",
"id": 43836,
"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": "recursion, swift, depth-first-search, trie, backtracking",
"url": null
} |
recursion, swift, depth-first-search, trie, backtracking
Answer: Good job in incorporating the feedback from your previous question to improve the Trie implementation.
The dfs() function can be improved a bit: Creating an array of all successor nodes (in the case of a wildcard character)
if let nextNodes = Array(currentNode.next.values) as? [TrieNode] {
for nextNode in nextNodes {
// ...
}
}
is not necessary, one can iterate over the values directly:
for nextNode in currentNode.next.values {
// ...
}
The variable
var nextIndex = currentIndex
word.formIndex(after: &nextIndex)
can be made a constant with
let nextIndex = word.index(currentIndex, offsetBy: 1)
Also
if let nextNode = currentNode.next[currentChar] {
currentNode = nextNode
word.formIndex(after: ¤tIndex)
continue
}
return false
is in my opinion better written with an else block instead of continue:
if let nextNode = currentNode.next[currentChar] {
currentNode = nextNode
word.formIndex(after: ¤tIndex)
} else {
return false
}
Caching the results
In the test case that fails with a timeout error, the same string “ghkdnjmmgcddganjkigmabbho” is searched 5000 times. So caching does help. It can be easily added to the search function. Note that the cache must be invalidated if a new word is added to the dictionary:
class WordDictionary {
var root: TrieNode
var cache: [String: Bool] = [:]
// ...
func addWord(_ word: String) {
// ...
cache.removeAll()
}
// ...
func search(_ word: String) -> Bool {
if let result = cache[word] {
return result
}
func dfs(index: String.Index, at node: TrieNode) -> Bool {
// ...
}
let result = dfs(index: word.startIndex, at: root)
cache[word] = result
return result
}
}
This can be optimized further: | {
"domain": "codereview.stackexchange",
"id": 43836,
"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": "recursion, swift, depth-first-search, trie, backtracking",
"url": null
} |
recursion, swift, depth-first-search, trie, backtracking
This can be optimized further:
Repeated calls to cache.removeAll() can be avoided. Instead of emptying the cash in addWord(), set an “invalid” flag and empty the cache in the search() method if that flag is set.
true entries in the cache remain valid if a new word is added to the dictionary. So instead of completely emptying the cache if a new word has been added, remove only the false entries. | {
"domain": "codereview.stackexchange",
"id": 43836,
"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": "recursion, swift, depth-first-search, trie, backtracking",
"url": null
} |
recursion, swift, depth-first-search, trie, backtracking
The code then looks like this:
class WordDictionary {
var root: TrieNode
var cache: [String: Bool] = [:]
var cacheValid = true
class TrieNode {
var next = [Character: TrieNode]()
var isWordEnd = false
}
init() {
root = TrieNode()
}
func addWord(_ word: String) {
var node = root
for char in word {
node = addInternal(char, at: node)
}
node.isWordEnd = true
cacheValid = false
}
func addInternal(_ char: Character, at node: TrieNode) -> TrieNode {
if let nextNode = node.next[char] {
return nextNode
}
let nextNode = TrieNode()
node.next[char] = nextNode
return nextNode
}
func search(_ word: String) -> Bool {
if (!cacheValid) {
let falseKeys = cache.compactMap { $0.value == false ? $0.key : nil }
for key in falseKeys {
cache[key] = nil
}
cacheValid = true
} else if let result = cache[word] {
return result
}
func dfs(index: String.Index, at node: TrieNode) -> Bool {
var currentNode = node
var currentIndex = index
while currentIndex < word.endIndex {
let currentChar = word[currentIndex]
if currentChar == "." {
for nextNode in currentNode.next.values {
let nextIndex = word.index(currentIndex, offsetBy: 1)
if dfs(index: nextIndex, at: nextNode) {
return true
}
}
return false
}
if let nextNode = currentNode.next[currentChar] {
currentNode = nextNode
word.formIndex(after: ¤tIndex) | {
"domain": "codereview.stackexchange",
"id": 43836,
"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": "recursion, swift, depth-first-search, trie, backtracking",
"url": null
} |
recursion, swift, depth-first-search, trie, backtracking
currentNode = nextNode
word.formIndex(after: ¤tIndex)
} else {
return false
}
}
return currentNode.isWordEnd
}
let result = dfs(index: word.startIndex, at: root)
cache[word] = result
return result
}
} | {
"domain": "codereview.stackexchange",
"id": 43836,
"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": "recursion, swift, depth-first-search, trie, backtracking",
"url": null
} |
python, asynchronous, callback
Title: Wait for a callback and then using the result
Question: I'm using Frida to run a script on a process, and I want to wait for it to send the result back to me, as a callback.
My current code looks like this:
def check(target):
global msg
script_to_run = '''
(omitted for brevity)
'''
# callback to handle the output of the script
def on_message(message, data):
global msg
if message['type'] == 'send':
msg = message['payload']
session = device.attach(target.pid)
script = session.create_script(script_to_run)
script.on('message', on_message)
script.load()
# Wait for the script to send us a message
while msg == None:
pass
return msg == 'true'
The while loop in particular looks a bit unoptimized, and I'm also worried about how I used that global variable... it will pollute the global scope.
EDIT: As it turns out, I was approaching this in the wrong direction. See my answer below for details.
Answer: So, as it turns out, I was approaching this problem in the wrong direction.
Instead of trying to wait on an asynchronous message, I discovered that Frida has an RPC API.
Here's how I re-wrote my code:
import frida
# --snip--
def check(target):
session = frida.attach(target.pid)
script = session.create_script('''
rpc.exports = {
check: function () {
// --snip--
return true;
}
};
''')
script.load()
return script.exports.check()
Much more succinct, doesn't use globals, and doesn't use a while loop to block. | {
"domain": "codereview.stackexchange",
"id": 43837,
"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, asynchronous, callback",
"url": null
} |
python, python-3.x, parsing
Title: Processing lines of a file with various space-separated fields of strings, hex addresses, and integer addresses
Question: I have a plain text file which contains lines with fields below:
<str_addr_a> <hex_int_addr>
<str_addr_a> <hex_int_addr> <dec_int_addr>
<str_addr_a> <str_addr_b>
<str_addr_a> <str_addr_b> <hex_int_addr>
<str_addr_a> <str_addr_b> <hex_int_addr> <dec_int_addr>
For example, the content of the file could be following:
# <str_addr_a> <hex_int_addr>
dkfi A18A
# <str_addr_a> <str_addr_b>
kloe uuep
# <str_addr_a> <str_addr_b> <hex_int_addr> <dec_int_addr>
ctff yaaq BBF2 19
# <str_addr_a> <str_addr_b> <hex_int_addr>
fkii hhyf E118
# <str_addr_a> <str_addr_b> <hex_int_addr> <dec_int_addr>
ctkj yuuq BBF0 12
I'm reading the file with function below:
def read_data(file):
with open(file, 'r', encoding='utf-8') as f:
addresses = []
for line_nr, line in enumerate(f, start=1):
line = line.strip()
if line and not line.startswith('#'):
str_addr_a = str_addr_b = hex_int_addr = dec_int_addr = None
try:
# '<str_addr_a> <hex_int_addr>'
str_addr_a, hex_int_addr = line.split()
if not is_valid_str_addr(str_addr_a):
raise ValueError from None
hex_int_addr = hex_addr(hex_int_addr).compress
except ValueError:
try:
# '<str_addr_a> <hex_int_addr> <dec_int_addr>'
str_addr_a = hex_int_addr = None
str_addr_a, hex_int_addr, dec_int_addr = line.split()
if not is_valid_str_addr(str_addr_a):
raise ValueError from None
hex_int_addr = hex_addr(hex_int_addr).compress
dec_int_addr = int(dec_int_addr) | {
"domain": "codereview.stackexchange",
"id": 43838,
"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, parsing",
"url": null
} |
python, python-3.x, parsing
except ValueError:
try:
# '<str_addr_a> <str_addr_b>'
str_addr_a = hex_int_addr = dec_int_addr = None
str_addr_a, str_addr_b = line.split()
if not is_valid_str_addr(str_addr_a):
raise ValueError from None
if not is_valid_str_addr(str_addr_b):
raise ValueError from None
except ValueError:
try:
# '<str_addr_a> <str_addr_b> <hex_int_addr>'
str_addr_a = str_addr_b = None
str_addr_a, str_addr_b, hex_int_addr = line.split()
if not is_valid_str_addr(str_addr_a):
raise ValueError from None
if not is_valid_str_addr(str_addr_b):
raise ValueError from None
hex_int_addr = hex_addr(hex_int_addr).compress
except ValueError:
try:
# '<str_addr_a> <str_addr_b> <hex_int_addr>
# <dec_int_addr>'
str_addr_a = str_addr_b = hex_int_addr = None
str_addr_a, str_addr_b, hex_int_addr, \
dec_int_addr = line.split()
if not is_valid_str_addr(str_addr_a):
raise ValueError from None
if not is_valid_str_addr(str_addr_b):
raise ValueError from None
hex_int_addr = hex_addr(hex_int_addr).compress | {
"domain": "codereview.stackexchange",
"id": 43838,
"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, parsing",
"url": null
} |
python, python-3.x, parsing
hex_int_addr = hex_addr(hex_int_addr).compress
dec_int_addr = int(dec_int_addr)
except ValueError:
logging.error(f'{file}: error on line number {line_nr}')
continue
addresses.append((str_addr_a, str_addr_b, hex_int_addr, dec_int_addr))
return(addresses)
As seen above, each try/except block tests one of the possible line formats. Such code introduces quite a lot of branches and isn't very flat. Is there a more elegant way to process such data file? Or perhaps the way I'm doing this is fine?
Answer: I think you would benefit from re-interpreting this input as having "only one format", with one mandatory field and three other optional fields. A regex can capture this better than your nested try blocks.
You need to separate individual record line parsing from parsing of the file.
Add unit tests.
Suggested
File and # handling not shown.
import re
from typing import NamedTuple, Optional
RECORD_PAT = re.compile(
r'''(?x)
^
(?P<str_addr_a>
[a-z]{4}
)
(?:
\s+
(?P<str_addr_b>
[a-z]{4}
)
)?
(?:
\s+
(?P<hex_int_addr>
[A-F0-9]{4}
)
)?
(?:
\s+
(?P<dec_int_addr>
\d+
)
)?
$
'''
)
class Record(NamedTuple):
str_addr_a: str
str_addr_b: Optional[str]
hex_int_addr: Optional[str]
dec_int_addr: Optional[int]
@classmethod
def from_line(cls, line: str) -> 'Record':
*first, dec_int_addr = RECORD_PAT.match(line).groups()
if dec_int_addr is not None:
dec_int_addr = int(dec_int_addr)
return cls(*first, dec_int_addr) | {
"domain": "codereview.stackexchange",
"id": 43838,
"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, parsing",
"url": null
} |
python, python-3.x, parsing
def test() -> None:
r = Record.from_line('dkfi A18A')
assert r.str_addr_a == 'dkfi'
assert r.str_addr_b is None
assert r.hex_int_addr == 'A18A'
assert r.dec_int_addr is None
r = Record.from_line('kloe uuep')
assert r.str_addr_a == 'kloe'
assert r.str_addr_b == 'uuep'
assert r.hex_int_addr is None
assert r.dec_int_addr is None
r = Record.from_line('ctff yaaq BBF2 19')
assert r.str_addr_a == 'ctff'
assert r.str_addr_b == 'yaaq'
assert r.hex_int_addr == 'BBF2'
assert r.dec_int_addr == 19
r = Record.from_line('fkii hhyf E118')
assert r.str_addr_a == 'fkii'
assert r.str_addr_b == 'hhyf'
assert r.hex_int_addr == 'E118'
assert r.dec_int_addr is None
r = Record.from_line('ctkj yuuq BBF0 12')
assert r.str_addr_a == 'ctkj'
assert r.str_addr_b == 'yuuq'
assert r.hex_int_addr == 'BBF0'
assert r.dec_int_addr == 12
if __name__ == '__main__':
test() | {
"domain": "codereview.stackexchange",
"id": 43838,
"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, parsing",
"url": null
} |
c++, algorithm, strings
Title: Finding first unique character in string
Question: Below is a solution I came up with (in C++) for an algorithm that is supposed to find the first character in a string that only appears once in the input string (the input string is guaranteed to be made up of only lower case characters from English alphabet). The catch is that the algorithm must return the index of that character from the original string, or negative one (-1) if there is no such character.
The solution below is O(n) in time and O(1) in space (const space because the list and the map can never have more than 26 entries).
I'm not convinced that my use of data structures is precise/clean.
I'm not sure if the code is very readable as is. Would it be more effective to write small functions that say what they do to replace things like: map_char_to_tracking[s[i]].char_count_in_string == 1 [so the reader can read at a higher level of abstraction without having to know the details of the data structures]?
Any improvements would be much appreciated.
#include <iostream>
#include <list>
#include <unordered_map>
typedef struct
{
int char_index_in_original_string;
std::list<char>::iterator char_position_in_list_itr;
int char_count_in_string;
}
Tracking; | {
"domain": "codereview.stackexchange",
"id": 43839,
"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++, algorithm, strings",
"url": null
} |
c++, algorithm, strings
// O(n) time | O(1) space, where n is the number of characters in the input string.
int FirstOccurrenceOfUniqueChar(const std::string& s)
{
std::list<char> unique_chars;
std::unordered_map<char, Tracking> map_char_to_tracking;
for (int i = 0; i < s.size(); ++i)
{
if (map_char_to_tracking[s[i]].char_count_in_string == 1)
{
// char has appeared once in string already, so remove it from unique chars list
++map_char_to_tracking[s[i]].char_count_in_string;
unique_chars.erase(map_char_to_tracking[s[i]].char_position_in_list_itr);
}
else if (map_char_to_tracking[s[i]].char_count_in_string == 0)
{
// char hasn't appeared in string yet, so add it to unique chars list and map.
unique_chars.push_back(s[i]);
map_char_to_tracking[s[i]] = Tracking{ i, --unique_chars.end(), 1 };
}
}
if (unique_chars.empty())
{
return -1;
}
return map_char_to_tracking[unique_chars.front()].char_index_in_original_string;
}
int main()
{
std::string s1{ "abcdeabcd" };
std::string s2{ "v" };
std::string s3{ "" };
std::string s4{ "aabbcc" };
std::cout << FirstOccurrenceOfUniqueChar(s1) << std::endl; // expect 4
std::cout << FirstOccurrenceOfUniqueChar(s2) << std::endl; // expect 0
std::cout << FirstOccurrenceOfUniqueChar(s3) << std::endl; // expect -1
std::cout << FirstOccurrenceOfUniqueChar(s4) << std::endl; // expect -1
return 0;
}
Answer: As already mentioned, you can do this in a one-pass algorithm. You only need to keep track of whether you have seen a character before, and what the position of its first occurence is. Here is a possible implementation:
#include <algorithm>
#include <array>
#include <climits>
#include <cstdint>
#include <string> | {
"domain": "codereview.stackexchange",
"id": 43839,
"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++, algorithm, strings",
"url": null
} |
c++, algorithm, strings
std::size_t FirstOccurrenceOfUniqueChar(const std::string& s) {
std::array<bool, 1 << CHAR_BIT> seen{};
std::array<std::size_t, 1 << CHAR_BIT> pos;
pos.fill(s.npos);
for (std::size_t i = 0; i < s.size(); ++i) {
auto ch = static_cast<unsigned char>(s[i]);
pos[ch] = seen[ch] ? s.npos : i;
seen[ch] = true;
}
return *std::min_element(pos.begin(), pos.end());
}
Note that in the above code, only two std::arrays are used; since there are only a fixed number of characters, you can use a fixed-size container instead of the slower std::list and std::unordered_map.
Also note that this version returns a std::size_t; this is necessary to support strings longer than an int can represent. Also, std::string::npos is used to indicate that there is no unique character. It's the largest possible value of std::size_t, which is very convenient here.
Also, if you cast std::string::npos to an int, it will become -1. | {
"domain": "codereview.stackexchange",
"id": 43839,
"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++, algorithm, strings",
"url": null
} |
c++, interview-questions, c++20
Title: Goat racing up a hill (C++ hiring take-home)
Question: This is an interview take-home challenge that has been translated to avoid compromising the company's question.
Problem statement
You are a goat that needs to race up a hill. Designated waypoint rocks on the hill must each be visited in sequence or skipped and a score penalty incurred. For the goat to get its balance, it must pause ten seconds on each rock. Travel between rocks occurs on a straight line at two metres per second.
Coordinates and penalties per rock are all integral and exist in the open interval (0, 100). Rock designations are spatially unique. The start rock at (0, 0) and the finish rock at (100, 100) are implied and not included in input.
Minimise the total cost of the goat's chosen path, calculated as the sum of all time spent and all penalties incurred.
Input is specified on stdin as one or more races followed by a final 0. Each race is specified by an integer n on one line - the number of rocks (excluding the start and finish) - followed by n lines, each an integer triple x y p, the coordinates of the rock and the penalty incurred if it is skipped.
Output on stdout is a single line per race, the path cost to three digits after the decimal.
Test cases
Input (sample_input_small.txt):
1
50 50 20
3
30 30 90
60 60 80
10 90 100
3
30 30 90
60 60 80
10 90 10
0
Output (sample_output_small.txt):
90.711
156.858
110.711
Implementation
I have a long-winded explainer that I might not paste here, but suffice to say that the implementation is amortised O(n). I used C++ because I need to catch up on best practices for versions 11+. The current compiler invocation looks like
g++ -O3 -s -march=native -fomit-frame-pointer --std=c++20 -Wall -Wextra -pedantic | {
"domain": "codereview.stackexchange",
"id": 43840,
"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++, interview-questions, c++20",
"url": null
} |
c++, interview-questions, c++20
It's pretty fast - for the biggest well-formed input of 9801 rocks, it executes in less than 10ms.
Review
Any feedback welcome, but I'm particularly interested in idiomatic use of modern C++ and associated data structures, and performance.
Code
#include <algorithm>
#include <cassert>
#include <cmath>
#include <exception>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <limits>
#include <set>
#include <sstream>
#include <string>
#include <vector>
namespace {
constexpr int
delay = 10,
speed = 2;
constexpr double
dist_min = 1,
dist_max = 100*M_SQRT2,
time_min = dist_min / speed,
time_max = dist_max / speed;
class Waypoint {
public:
const int x, y, penalty = 0;
Waypoint(int x, int y) : x(x), y(y) { }
Waypoint(int x, int y, int penalty) : x(x), y(y), penalty(penalty) { }
static Waypoint read(std::istream &in) {
int x, y, penalty;
in >> x >> y >> penalty;
return Waypoint(x, y, penalty);
}
double time_to(const Waypoint &other) const {
int dx = x - other.x, dy = y - other.y;
double distance = sqrt(dx*dx + dy*dy);
return distance / speed;
}
};
class OptimisedWaypoint {
public:
const Waypoint &waypoint;
const double best_cost = 0;
const int penalty = 0;
OptimisedWaypoint(const Waypoint &visited): waypoint(visited) { }
OptimisedWaypoint(const Waypoint &visited, double best_cost, int penalty):
waypoint(visited), best_cost(best_cost), penalty(penalty) { }
double cost_for(const Waypoint &visited) const {
double time = visited.time_to(waypoint);
return time + best_cost - penalty + delay;
}
double invariant_cost() const {
return best_cost - penalty;
} | {
"domain": "codereview.stackexchange",
"id": 43840,
"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++, interview-questions, c++20",
"url": null
} |
c++, interview-questions, c++20
double invariant_cost() const {
return best_cost - penalty;
}
bool operator<(const OptimisedWaypoint &other) const {
return invariant_cost() < other.invariant_cost();
}
};
void prune(std::multiset<OptimisedWaypoint> &opt_waypoints) {
double to_exceed = opt_waypoints.cbegin()->invariant_cost() + time_max - time_min;
for (auto w = opt_waypoints.crbegin(); w != opt_waypoints.crend(); w++) {
if (w->invariant_cost() < to_exceed) {
opt_waypoints.erase(w.base(), opt_waypoints.end());
break;
}
}
}
double get_best_cost(
const Waypoint &visited,
const std::multiset<OptimisedWaypoint> &opt_waypoints
) {
double best_cost = std::numeric_limits<double>::max();
for (const OptimisedWaypoint &skipto: opt_waypoints) {
double cost = skipto.cost_for(visited);
if (best_cost > cost) best_cost = cost;
}
return best_cost;
}
double solve(const std::vector<Waypoint> &waypoints) {
std::multiset<OptimisedWaypoint> opt_waypoints;
opt_waypoints.emplace(waypoints.back());
const auto end = std::prev(waypoints.crend());
int total_penalty = 0;
for (auto visited = std::next(waypoints.crbegin());; visited++) {
total_penalty += visited->penalty;
double best_cost = get_best_cost(*visited, opt_waypoints);
if (visited == end)
return best_cost + total_penalty;
opt_waypoints.emplace(*visited, best_cost, visited->penalty);
prune(opt_waypoints);
}
}
void process_streams(std::istream &in, std::ostream &out) {
constexpr std::ios::iostate mask = std::ios::failbit | std::ios::badbit;
in.exceptions(mask);
out.exceptions(mask);
for (;;) {
int n;
in >> n;
if (n == 0) break; | {
"domain": "codereview.stackexchange",
"id": 43840,
"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++, interview-questions, c++20",
"url": null
} |
c++, interview-questions, c++20
for (;;) {
int n;
in >> n;
if (n == 0) break;
std::vector<Waypoint> waypoints;
waypoints.reserve(n+2);
waypoints.emplace_back(0, 0);
for (int i = 0; i < n; i++)
waypoints.push_back(Waypoint::read(in));
waypoints.emplace_back(100, 100);
out << std::fixed << std::setprecision(3) << solve(waypoints) << std::endl;
}
}
void compare(std::istream &out_exp, std::istream &out_act) {
for (;;) {
std::string time_exp, time_act;
if (!std::getline(out_exp, time_exp)) {
if (out_exp.eof()) break;
throw std::ios::failure("getline");
}
out_act >> time_act;
std::cout << time_exp << " == " << time_act << std::endl;
assert(time_exp == time_act);
}
}
void test() {
constexpr const char *cases[] = {"small", "medium", "large"};
for (const char *const case_name: cases) {
std::stringstream out_act;
{
std::ostringstream fnin;
fnin << "sample_input_" << case_name << ".txt";
std::ifstream in;
in.open(fnin.str());
process_streams(in, out_act);
}
std::ostringstream fnout;
fnout << "sample_output_" << case_name << ".txt";
std::ifstream out_exp;
out_exp.exceptions(std::ios::badbit);
out_exp.open(fnout.str());
out_act.seekp(0);
compare(out_exp, out_act);
}
}
void main() {
process_streams(std::cin, std::cout);
}
}
int main(int argc, const char **argv) {
try {
if (argc > 1 && std::string(argv[1]) == "-t")
test();
else main();
} catch (const std::exception &ex) {
std::cerr << ex.what() << std::endl;
return 1;
}
return 0;
} | {
"domain": "codereview.stackexchange",
"id": 43840,
"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++, interview-questions, c++20",
"url": null
} |
c++, interview-questions, c++20
Answer: M_SQRT2 is not part of the standard library
and does not exist on all conforming implementations.
The portable C++20 version is
#include <numbers>
constexpr double dist_max = 100 * std::numbers::sqrt2;
Before C++20, you may consider supplying your own definition of the constant
since std::sqrt is not constexpr.
The spacing style T& x is much more common than T &x in C++.
I don't think it is useful to put everything (other than main)
in an anonymous namespace for a one-file script.
Since the conversion factor \$\sqrt{2}\$ is unavoidable,
you might as well store everything in double to save type conversions.
const data members are generally a mistake (outside rare use cases) —
usually, a const object is intended instead.
Also, it is more idiomatic to define simple data structures like Waypoint as aggregates:
struct Waypoint {
int x, y, penalty = 0;
// no user-defined constructors
} | {
"domain": "codereview.stackexchange",
"id": 43840,
"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++, interview-questions, c++20",
"url": null
} |
c++, interview-questions, c++20
// no user-defined constructors
}
so that it can be constructed like Waypoint { x, y, penalty }.
The same goes for OptimizedWaypoint.
Prefer std::hypot(dx, dy) over std::sqrt(dx * dx, dy * dy).. As Reinderien pointed out in comments, the extra precision guaranteed by hypot may cause performance degradation. If performance is the concern, we might consider creating a handmade even faster version if we don’t need the extra precision (since we are dealing with integers anyway).
Prefer ++w over w++ (especially) when w is an iterator,
unless you need the return value of w++.
In prune, I believe you are looking for lower_bound.
In that case, you probably need to refactor the code a bit, though.
(In fact, I feel that the whole OptimizedWaypoint design
should be replaced by something like std::multimap<double, Waypoint>.)
Similarly, in get_best_cost, use std::min_element.
The effect of std::setprecision(3) remains until the precision is changed again,
so you do not need to do it every time you print a number.
Instead of creating a default-initialized stream and then calling open,
simply pass the file as an argument when creating the stream.
Finally, std::string(argv[1]) == "-t"
can be simplified to argv[1] == "-t"sv
if you have using namespace std::string_view_literals;. | {
"domain": "codereview.stackexchange",
"id": 43840,
"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++, interview-questions, c++20",
"url": null
} |
javascript, beginner
Title: Create a Grid From User Input and Change Square Color on Mouse Over - The Odin Project: Etch-a-Sketch
Question: I'm working my way through the Foundations course on The Odin Project and just finished the Etch-a-Sketch assignment.
The program receives a number from 1 - 100 from the user through a prompt and then creates a grid from the square of the number. Then, on mouse over, one square of the grid will be assigned a random number and will have its opacity increased by 0.10. When the user wishes to create a new grid, they click a button that eliminates the current grid and then reruns in the same way as before.
I am so new at programming and I really hope to learn "best practices" and how to code without the need for too many comments. I also had a hard time selecting a child node of the container and applying style changes to the node on mouse over.
To me, any feed back is invaluable. Thank you for any considerations.
function removeAllChildNodes(parent){
while (parent.firstChild) {
parent.removeChild(parent.firstChild);
}
}
function getInput() {
let promptInput = prompt('Enter a whole number between 1 and 100', '');
return promptInput;
}
function createArray(promptInput){
const square = [];
for(i = 0; i < promptInput; i++) {
square[i] += `${i}`;
}
return square;
}
let uniqueClass = 0;
function createUniqueClass(){
uniqueClass += 1;
return uniqueClass;
}
function addOpacity(element) {
let numElement = +(element.style.opacity);
if (numElement === 1){
return numElement;
}
numElement += 0.10;
return numElement;
} | {
"domain": "codereview.stackexchange",
"id": 43841,
"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, beginner",
"url": null
} |
javascript, beginner
function addColor(div){
div.addEventListener('mouseover', (event) => {
const element = document.getElementsByClassName(event.target.classList);
console.log(event.target);
element[0].style.background = `#${(Math.floor(Math.random()*16777215).toString(16))}`
element[0].style.opacity = `${addOpacity(element[0])}`;
});
}
const container = document.querySelector('#container');
container.setAttribute('style', 'display: flex; flex: 1 1 0; height: 960px; width: 960px; margin: auto; border: solid black 1px; flex-wrap: wrap;');
function createGrid(grid){
grid.forEach(() => {
const div = document.createElement('div');
div.setAttribute('style', 'box-sizing: border-box; border: 1px solid black;');
/*div.style.boxSizing = 'border-box'; // div.setAttribute would not accept boxSizing property
div.style.border = '1px solid black';*/
div.classList.add(`box${createUniqueClass()}`); // Create a unique class name for each div child of container
container.appendChild(div);
div.style.height = `${960 / promptInput + 0.01}px`; // Add 0.01px for column doesn't fill in container completely
div.style.width = `${960 / promptInput}px`;
addColor(div);
});
}
let promptInput = '';
let array = [''];
const button = document.querySelector('button');
button.addEventListener('click', () => {
removeAllChildNodes(container);
promptInput = getInput();
grid = createArray(promptInput * promptInput);
createGrid(grid);
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="java-script.js" defer></script>
<link rel="stylesheet" href="style.css">
</head>
<body>
<button>Generate New Grid</button>
<div id="container"></div>
</body>
</html> | {
"domain": "codereview.stackexchange",
"id": 43841,
"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, beginner",
"url": null
} |
javascript, beginner
<body>
<button>Generate New Grid</button>
<div id="container"></div>
</body>
</html>
Answer: Use prettier and eslint
Code auto-formatters are awesome. Try one at https://prettier.io/playground and look into adding it to your build which will make your code easier for other developers to read.
Linters automatically tell you about many problems in your code. A good portion of code reviews on this site are pretty much repeating linter output. Try eslint at https://eslint.org/play/.
Use const rather than let
In general, never use let unless you really need to mutate something, like a loop counter. Otherwise, use const. const guarantees the variable will never be reassigned, making the code easier to read (one less possible state change to reason about) and avoids a whole class of potential bugs. A codebase chock-full of lets is a sure sign of other problems.
Avoid pointless intermediate variables
Minor point, but
function getInput() {
let promptInput = prompt('Enter a whole number between 1 and 100', '');
return promptInput;
}
could be
const getInput() => prompt('Enter a whole number between 1 and 100');
Even so, prompt is generally considered to provide a poor UX, so I'd use an <input type="number" min="1" max="100"> element.
I prefer arrow functions but the classic function syntax with return is acceptable too. What I like about the const/arrow function version:
Guarantees no reassignments
Guarantees the function is only visible below its definition like a normal variable; no magic hoisting
Makes it obvious that when you do use function, it's because you want to avoid automatic this binding
No need to use return much of the time, encouraging short functions
Less typing; cleaner-looking, modern functional style that is more aesthetically pleasing to me. | {
"domain": "codereview.stackexchange",
"id": 43841,
"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, beginner",
"url": null
} |
javascript, beginner
I don't think you need to specify the second default value argument to prompt if it's just an empty string.
Perform input conversions
prompt() always returns a string, and JS is "smart" enough to parse strings to integers when using the * operator, but it's best to make that conversion by hand and create a number as soon as possible after receving the input. This separates presentation and logic, making refactoring and debugging easier and helps mitigate surprising type bugs, which JS is especially prone to. Implicit conversion is generally seen as a flaw in JS' design rather than a feature. Hence TypeScript.
Validate input
UX: if the user enters invalid input, nothing happens. I suggest re-prompting the user when they enter something invalid.
It's also not entirely clear to what the number the user is entering represents exactly, based on the prompt. Maybe explain that it's the grid side length.
Remove debugging logs and commented-out code
console.log(event.target); spams the console when I run your snippet. These logs slow down the app and are unsightly.
Similarly, commented-out code shouldn't be committed or pushed to production.
Use high-level JS array functions
Avoid counter-based for loops in code. There's almost always more idiomatic way.
function createArray(promptInput){
const square = [];
for(i = 0; i < promptInput; i++) {
square[i] += `${i}`;
}
return square;
}
could be
const createArray = n => [...Array(n)].map((_, i) => `${i}`); | {
"domain": "codereview.stackexchange",
"id": 43841,
"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, beginner",
"url": null
} |
javascript, beginner
could be
const createArray = n => [...Array(n)].map((_, i) => `${i}`);
There's a deeper reason for doing this other than aesthetics--your loop counter i creates a global variable attached to the window which could easily interfere with code elsewhere. Always "use strict"; at the top of your scripts to help avoid such errors. With traditional for loops, it's all too easy to mess up the index or .length and introduce bugs. A classic bug is typoing .lenght.
Also, traditional for loops don't self-document the code--it's hard to tell whether they're acting as filters, mappers, reducers, searchers, existence checks or initializers at a glance.
Notice that the function name, createArray, sounds pretty generic, but it then has a confusing promptInput parameter that doesn't make much sense taken out of context and implicitly couples it to the code around it. I'd just call this parameter n. Also, it doesn't just create any old array, it creates an array of string numbers from 0..n. Perhaps createAscendingNumberArray is a more precise name.
Don't generate dynamic classes or ids
div.classList.add(`box${createUniqueClass()}`) and the createUniqueClass are antipatterns. Rather than using dynamic classes, just add a single .box class and select the n-th item of elements matching that class if you need to. But when you're creating dynamic elements, you can just track them in an in-memory data structure so you don't have to select them. This helps reduce two-way data flow in the program.
Event delegation is a useful way to figure out which element in a grid of children had the event triggered on it.
Separate CSS and JS
Your code leaks too much CSS into the JS logic.
For example,
container.setAttribute('style', 'display: flex; flex: 1 1 0; height: 960px; width: 960px; margin: auto; border: solid black 1px; flex-wrap: wrap;'); | {
"domain": "codereview.stackexchange",
"id": 43841,
"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, beginner",
"url": null
} |
javascript, beginner
Imagine needing to adjust this style. It'd be easy to find and modify in a CSS file organized by its class, but baked into JS as a string risks burying it in the codebase. Try to limit your JS to adding, removing and toggling CSS classes and minimize touching element.style.
Separation of structure (HTML), presentation (CSS) and behavior (JS) makes front-end codebases easier to maintain. For larger apps, use a component-based system as most SPA frameworks and libraries do these days. If you do use CSS-in-JS, use a template literal string and keep it to one CSS property per line.
Watch out for floating-point weirdness
The code below stores a two-way bound property in the DOM, then re-parses it back into memory per call:
function addOpacity(element) {
let numElement = +(element.style.opacity);
if (numElement === 1){
return numElement;
}
numElement += 0.10;
return numElement;
}
Concerning is numElement === 1 after incrementing += 0.1 per click. It's probably fine in JS, but in other languages, comparing 1.0 and 1.0 is often not going to work. Safer to use >= 1 or an epsilon comparison.
addOpacity also in moves half of its logic to the caller:
element[0].style.opacity = `${addOpacity(element[0])}`; | {
"domain": "codereview.stackexchange",
"id": 43841,
"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, beginner",
"url": null
} |
javascript, beginner
Why not complete the abstraction and do that assignment in the addOpacity function? Also, the template literal is unnecessary--the string conversion is already done under the hood.
Similarly, addColor has a confusing contract. It really adds an event listener that adds color only later when and if the user mouses over rather than immediately as the name suggests. I'd call it changeColorOnMouseover or something like that.
Don't query the DOM unnecessarily
Also, the addColor mouseover listener re-queries all elements with a class name when there's supposedly only one. document.querySelector would probably be easier: return the one and only, skipping the [0]. Or drop the query entirely and use event.target which is the hovered element.
Even better, just use the element you're adding the listener to!
Create the right abstractions
Your criteria for when to break out logic seems arbitrary. For example, why was getInput broken out into its own function, but not the code to produce a random color, #${(Math.floor(Math.random()*16777215).toString(16))}? The former is a one-liner with no general value that's only called from a single place, whereas the latter is ugly to look at in-line and could easily be a general-purpose library function in an npm package.
Be careful of creating functions without good reason to. When you do, it should be to clean up the logic in the caller by breaking out sub-steps, to enable code reuse and maintainability and to generalize repeated code.
Suggested rewrite
I left prompt in and kept reading opacity from the DOM, but if the app were any larger I'd consider creating objects for each cell to keep track of opacity and other properties in memory, then reflect these properties to the DOM in one direction as described above.
"use strict";
const randomHexColor = () =>
`#${Math.floor(Math.random() * 16777215).toString(16)}`;
const removeAllChildNodes = parent => {
while (parent.firstChild) {
parent.removeChild(parent.firstChild);
}
}; | {
"domain": "codereview.stackexchange",
"id": 43841,
"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, beginner",
"url": null
} |
javascript, beginner
const increaseOpacity = (el, by = 0.1) => {
el.style.opacity = Math.min(1, +el.style.opacity + by);
};
const makeGridCell = size => {
const div = document.createElement("div");
div.style.width = div.style.height = `${size}px`;
div.classList.add("grid-cell");
return div;
};
const addGridMouseoverListener = () => {
const grid = document.querySelector(".grid-container");
grid.addEventListener("mouseover", event => {
const cell = event.target.closest("div");
if (
cell &&
cell.classList.contains("grid-cell") &&
grid.contains(cell)
) {
increaseOpacity(cell);
cell.style.background = randomHexColor();
}
});
};
const addNewGridButtonListener = () => {
const grid = document.querySelector(".grid-container");
const button = document.querySelector(".new-grid");
button.addEventListener("click", () => {
removeAllChildNodes(grid);
const message = "Enter a whole number between 1 and 100";
const sideLen = +prompt(message);
const w = parseInt(getComputedStyle(grid).width);
for (let i = 0; i < sideLen * sideLen; i++) {
grid.appendChild(makeGridCell(w / sideLen));
}
});
};
addGridMouseoverListener();
addNewGridButtonListener();
.grid-container {
display: flex;
flex: 1 1 0;
flex-wrap: wrap;
height: 960px;
width: 960px;
margin: auto;
border: solid black 1px;
}
.grid-cell {
box-sizing: border-box;
border: 1px solid black;
}
<button class="new-grid">Generate New Grid</button>
<div class="grid-container"></div> | {
"domain": "codereview.stackexchange",
"id": 43841,
"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, beginner",
"url": null
} |
c++, c++11, tree, constructor
Title: A binary tree , its copy constructor and assignment operator
Question: I implemented a binary tree in the following code. Its node's copy constructor and assignment operator should copy itself and all its descendents. Similarity a node's destructor should delete itself and all nodes descended from it.The print function just prints each node in a new line. How can I pretty-print it? Please point to errors(if any) and suggestions.
#include <iostream>
struct Node
{
Node(int);
Node(const Node&);
Node& operator=(const Node&);
~Node();
Node* left;
Node* right;
int value;
};
Node::Node(int v)
:left(nullptr),
right(nullptr),
value(v)
{}
Node::Node(const Node& other)
:left(nullptr),
right(nullptr),
value(other.value)
{
if (other.left != nullptr )
{
left = new Node(*other.left);
}
if (other.right != nullptr)
{
right = new Node(*other.right);
}
}
Node& Node::operator=(const Node& other)
{
value = other.value;
Node * left_orig = left;
left = new Node(*other.left);
delete left_orig;
Node * right_orig = right;
right = new Node(*other.right);
delete right_orig;
return *this;
}
Node::~Node()
{
if (left != nullptr )
{
delete left;
}
if (right != nullptr)
{
delete right;
}
}
Node* make_copy(Node* other)
{
Node * new_node = new Node(*other); // copy constructor invoked
return new_node;
}
void print(Node* n)
{
if (n == nullptr)
{
return;
}
std::cout << n << std::endl;
print(n->left);
print(n->right);
}
int main()
{
Node* n = new Node(1);
n->left = new Node(2);
n->right = new Node(3);
n->left->left = new Node(4);
n->left->right = new Node(5);
n->right->left = new Node(6);
n->right->right = new Node(7);
print(n);
auto nc = make_copy(n);
print(nc);
} | {
"domain": "codereview.stackexchange",
"id": 43842,
"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, tree, constructor",
"url": null
} |
c++, c++11, tree, constructor
print(n);
auto nc = make_copy(n);
print(nc);
}
Answer: Assignment operator.
The assignment operator is not 100% exception safe.
You should not modify the current object while you have not yet finished making the copy.
Node& Node::operator=(const Node& other)
{
value = other.value;
Node * left_orig = left;
left = new Node(*other.left);
delete left_orig;
// You have modified the left side.
// If while making the copy of the right side
// it throws an exception (that is caught), then you
// have an object that is half one thing (new stuff)
// and half the other (old stuff on the right).
Node * right_orig = right;
right = new Node(*other.right);
delete right_orig;
return *this;
}
It should look more like this:
Node& Node::operator=(const Node& other)
{
Note* newleft = nullptr;
Node* newright = nullptr;
// Do the dangerous stuff in isolation.
// without changing the chaging the current object.
try {
newleft = new Node(*other.left);
newright = new Node(*other.right);
}
catch(...) {
// If there was a problem
// clean up any temporary objects.
delete newleft;
delete newright;
// Then re-throw
throw;
}
// Now perform the exception safe change of state.
// None of these operations are allowed to throw.
value = other.value;
std::swap(left, newLeft);
std::swap(right, newRight);
// Now that the object is in a consistent state.
// we can delete the old data.
// Do this last (in other types where the data is not in
// this can potentially throw).
delete newLeft;
delete newRight;
return *this;
} | {
"domain": "codereview.stackexchange",
"id": 43842,
"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, tree, constructor",
"url": null
} |
c++, c++11, tree, constructor
return *this;
}
Now that looks like a lot of hard work.
There is an easier way to achieve exactly the same effect. You can use the copy and swap idiom.
Node& Node::operator=(Node other) // Pass by value to generate a copy.
{
other.swap(*this); // Swap the state of this and the
// copy we created in `other`
return *this;
} // destructor of other now
// does the tidy up.
Destructor
Calling delete on a null pointer is valid and does nothing.
Node::~Node()
{
if (left != nullptr )
{
delete left;
}
if (right != nullptr)
{
delete right;
}
}
So we can simplify this too.
Node::~Node()
{
delete left;
delete right;
}
Why do you need a make_copy?
Node* make_copy(Node* other)
{
Node * new_node = new Node(*other); // copy constructor invoked
return new_node;
}
It is quite normal to call the copy constructor directly.
Print statement
You can make the print function a method. Also to make it more versatile you should pass a stream to which you want to print (so it can also print to file). If you want a no-argument version just make the stream parameter default to std::cout.
void Node::print(std::ostream& str = std::cout)
{
str << value << std::endl;
if (left) {
left->print(str);
}
if (right) {
right->print(str);
}
}
This makes it easy to define the output operator for your class.
std::ostream& operator<<(std::ostream& str, Node& data)
{
data.print(str);
return *this;
} | {
"domain": "codereview.stackexchange",
"id": 43842,
"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, tree, constructor",
"url": null
} |
c#, asp.net-core
Title: Looking to interact with a DbContext entity through a different service
Question: I have 2 Data Models let's call them Lecture/Teacher that have a one-to-many relationship, in a service method I need to get a teacherId given a certain condition and add it to the Lecture model instance.
Below is the definition of the different Models.
namespace Example.Core.Data;
public class Lecture
{
public int Id { get; set; } = null!;
public string TeacherId { get; set; } = null!;
public string Name { get; set; } = null!;
public int duration { get; set; }
public virtual Teacher Teacher { get; set; } = null!;
}
public class LectureInput
{
public string Name { get; set; } = null!;
public string TeacherField { get; set; } = null!;
public int Duration { get; set; } = null!;
}
Teacher Model:
public partial class Teacher
{
public Teacher()
{
Lectures = new HashSet<Lecture>();
}
public int Id { get; set; } = null!;
public int Age { get; set; }
public string Name { get; set; } = null!;
public string Field { get; set; } = null!;
public string Department { get; set; } = null!;
[JsonIgnore] public virtual ICollection<Lecture> Lectures { get; set; }
}
As I have access to the DbContext in the LectureService at first I thought I could use it to directly get the teacherId, like so:
using Example.Core.Data;
using Microsoft.EntityFrameworkCore;
public class LectureService
{
private readonly DbContext _context;
public LectureService(DbContext context)
{
_context = context;
} | {
"domain": "codereview.stackexchange",
"id": 43843,
"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#, asp.net-core",
"url": null
} |
c#, asp.net-core
public LectureService(DbContext context)
{
_context = context;
}
public int Create(LectureInfo input)
{
var lecture = new Lecture
{
Name = input.Name,
teacherId = _context.Teachers //here
.AsNoTracking()
.Where(t => t.Field == input.TeacherField)
.OrderByDescending(t => t.Name)
.FirstOrDefault().Id,
duration = input.Duration
}
_context.Lectures.Add(lecture);
_context.SaveChanges();
return lecture.Id;
}
But later I figured we do need to use that same logic in another place and had to add it to the TeacherService, so I thought if it was okay to use dependency injection and call the method from the TeacherService inside LectureService, like this:
using Example.Core.Data;
using Microsoft.EntityFrameworkCore;
public class TeacherService
{
private readonly DbContext _context;
public TeacherService(DbContext context)
{
_context = context;
}
public int GetTeacherIdByField(string field)
{
return context.Teachers
.AsNoTracking()
.Where(t => t.Field == field)
.OrderByDescending(t => t.Name)
.FirstOrDefault().Id
}
}
And then just call the method in the LectureService, like this:
using ContractManager.Core.Data;
using Microsoft.EntityFrameworkCore;
public class LectureService
{
private readonly DbContext _context;
private readonly TeacherService _teacherService;
public LectureService(DbContext context, TeacherService teacherService)
{
_context = context;
_teacherService = teacherService;
} | {
"domain": "codereview.stackexchange",
"id": 43843,
"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#, asp.net-core",
"url": null
} |
c#, asp.net-core
public int Create(LectureInfo input)
{
var lecture = new Lecture
{
Name = input.Name,
teacherId = teacherService.GetTeacherIdByField(input.TeacherField),
duration = input.Duration
}
_context.Lectures.Add(lecture);
_context.SaveChanges();
return lecture.Id;
}
Is it viable to use the second option or should I stick to using the DbContext directly in the LectureService ?
Answer: Some quick remarks:
What does "Field" on "Teacher" represent? Moreover, why wouldn't you get the teacher's ID from the user input? Presumably the user selects from a list, what is stopping you from presenting them with a list of names which translates to an ID when transmitting to the API?
.FirstOrDefault().Id will break when the result is NULL. If you think the result can be NULL, then you must anticipate this. If the result cannot be NULL, then there's no point in using "OrDefault".
Also, why .FirstOrDefault()? If you expect multiple results to be possible, why would the first one be the correct one?
Why is TeacherId a string when Id is an int on Teacher?
Why is duration lowercase?
public int Age { get; set; } Are you going to update this field once a year?
public string Department { get; set; } This should be an ID linking to a separate table, since I presume a department can have multiple teachers. See database normalization.
If you're calling a method inside the TeacherService, there's no need to use the words "Teacher" in the method name (IMHO), e.g. GetTeacherIdByField.
Now, when it comes to your question of using one service inside another: I wouldn't do it like that. I'd instead opt to have a separate class, e.g. TeacherRetriever, which contains the logic inside GetTeacherIdByField and then use this retriever in both services. | {
"domain": "codereview.stackexchange",
"id": 43843,
"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#, asp.net-core",
"url": null
} |
python, database, sqlalchemy
Title: High traffic website that shows users subscription status
Question: I was in two minds as whether to post this question on stackoverflow or dba stackexchange but because I am asking for review, I thought of posting here.
I am new to Python and looking for feedback on whether the below code will work for a high website traffic, especially from database perspective and suggestions to make code more clean.
Use case here is as follows:
We are sending mass email to all customers, irrespective of their email subscription status.
Email says click this button to check your subscription status.
Once customer clicks the button, user_helper.is_user_subscribed_to_emails is called with email of customer and show the return value to customer on web page.
Table where user's subscription status is supposed to contain is not complete. It has rows for very few users and the intent behind this whole exercise is to fill the table with information about all users. Because of this, if 100 users are clicking on the button at a same time, whose info doesn't exist in table, it should successfully insert their info in database without any issues.
database/database_util.py:
from sqlalchemy import create_engine
from sqlalchemy.exc import SQLAlchemyError
db_uri = "sqlite:///temp.db"
try:
engine = create_engine(db_uri, echo=False, future=True)
except SQLAlchemyError as e:
print("There was an error in creating the engine")
database/models.py:
from sqlalchemy import Column
from sqlalchemy import String
from sqlalchemy import Boolean
from sqlalchemy.orm import declarative_base
from .database_util import engine
from sqlalchemy.exc import SQLAlchemyError
Base = declarative_base() | {
"domain": "codereview.stackexchange",
"id": 43844,
"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, database, sqlalchemy",
"url": null
} |
python, database, sqlalchemy
Base = declarative_base()
class User(Base):
__tablename__ = "user"
# user ids are alphanumeric, so we are going with String.
email = Column(String, primary_key=True)
subscribed_to_emails = Column(Boolean, default=False)
def __repr__(self):
return f"User(id={self.email!r}, subscribed_to_emails={self.subscribed_to_emails!r}"
try:
Base.metadata.create_all(engine)
except SQLAlchemyError as e:
print("Failed to initialize database metadata")
user_helper.py:
from sqlalchemy.orm import Session
from database.database_util import engine
from database.models import User
from sqlalchemy import select
def is_user_subscribed_to_emails(user_email):
with Session(engine) as session:
stmt = select(User).where(User.email == user_email)
for row in session.execute(stmt).scalars():
if row.subscribed_to_emails == False:
return True
else:
return False
# We didn't find the user in table and that means, user is subscribed. Create a user and return true.
session.add(User(email=user_email, subscribed_to_emails = False))
session.commit()
return True
Answer: Architecture
Regarding this concern:
Table where user's subscription status is supposed to contain is not complete. It has rows for very few users and the intent behind this whole exercise is to fill the table with information about all users. Because of this, if 100 users are clicking on the button at a same time, whose info doesn't exist in table, it should successfully insert their info in database without any issues. | {
"domain": "codereview.stackexchange",
"id": 43844,
"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, database, sqlalchemy",
"url": null
} |
python, database, sqlalchemy
There's usually a way around it. You could use some distributed task queue such as Celery. That simplifies the management of task distribution and processing and can be used as a mechanism to distribute work across threads or machines. A task queue’s input is a unit of work called a task. Dedicated worker processes constantly monitor task queues for new work to perform.
Celery communicates via messages, usually using a broker to mediate between clients and workers. To initiate a task, the client adds a message to the queue, and the broker then delivers that message to a worker. RabbitMQ is one of the brokers transports completely supported by Celery.
Am not sure from your question if the app is built on top of FastAPI or Flask but from my experience I've been able to easily integrate RabbitMQ and Celery within my FastAPI projects (FastAPI also comes with async by default).
To create a better picture, here's how that would work:
The client sends a request to your FastAPI/Flask application (that would be your user clicking on the button).
FastAPI/Flask app sends the task message to the message broker.
Celery workers consume the messages from the message broker. After the task finishes, it saves the result to the Result Backend and updates the task status.
After sending the task to the message broker, the FastAPI/Flask app can also monitor the status of the task from the Result Backend.
For a simple implementation have a look here
Code
try:
Base.metadata.create_all(engine)
except SQLAlchemyError as e:
print("Failed to initialize database metadata")
It's bad practice to only print such critical issues. You should be raising an error and add logging beforehand.
if row.subscribed_to_emails == False:
return True
else:
return False
Can be rewritten as:
if row.subscribed_to_emails == False:
return True
return False
There might be cases when this:
select(User).where(User.email == user_email) | {
"domain": "codereview.stackexchange",
"id": 43844,
"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, database, sqlalchemy",
"url": null
} |
python, database, sqlalchemy
There might be cases when this:
select(User).where(User.email == user_email)
could raise exceptions (something bad happened to that table / db connection etc) so I would advise you wrap that within a try/except block. | {
"domain": "codereview.stackexchange",
"id": 43844,
"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, database, sqlalchemy",
"url": null
} |
python, python-3.x, memory-optimization, bitset
Title: Python classes which can be used as arrays with any number of bits per index | {
"domain": "codereview.stackexchange",
"id": 43845,
"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, memory-optimization, bitset",
"url": null
} |
python, python-3.x, memory-optimization, bitset
Question: https://github.com/speedrun-program/small_array/blob/main/small_array.py
As a personal project, I wanted to try to make Snake Game in pygame where the grid can be arbitrarily large. I made these classes so I could make larger grids before running out of memory.
class nbitndarray:
"a class which lets you use a byte array as if it was an arbitrarily deeply nested "
"array with each index being any number of bits wide"
def __init__(self, dimensions, bits_per_index):
self.bits_per_index = bits_per_index
self.dimensions = tuple(dimensions)
if any(d <= 0 for d in dimensions):
raise ValueError("all dimensions must be greater than 0")
elif bits_per_index <= 0:
raise ValueError("bits_per_index must be greater than 0")
elif not dimensions:
raise ValueError("no dimensions given")
total_bits = bits_per_index
for d in dimensions:
total_bits *= d
total_bytes = (total_bits // 8) + (total_bits % 8 != 0)
self._array = bytearray(total_bytes)
def _index_generator(self, position):
for depth, (pos, dimension_length) in enumerate(zip(position, self.dimensions)):
actual_position = pos if pos >= 0 else dimension_length + pos
if not 0 <= actual_position < dimension_length:
raise IndexError(f"attempted to access index {pos} of dimension {depth}, which is length {dimension_length}")
yield actual_position
def _get_actual_position(self, position): # returns (start_byte, start_bit)
if (len(position) != len(self.dimensions)):
raise ValueError(
f"position argument had {len(position)} dimensions, "
f"but self.dimensions has {len(self.dimensions)} dimensions"
)
index_generator = self._index_generator(position) | {
"domain": "codereview.stackexchange",
"id": 43845,
"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, memory-optimization, bitset",
"url": null
} |
python, python-3.x, memory-optimization, bitset
)
index_generator = self._index_generator(position)
which_bit = next(index_generator)
for i, pos in enumerate(index_generator, 1):
which_bit = (which_bit * self.dimensions[i]) + pos
which_bit *= self.bits_per_index
return divmod(which_bit, 8)
def zero_bytes(self):
self._array.__init__(len(self._array))
def get(self, position):
which_byte, byte_start_position = self._get_actual_position(position)
bits_left_to_read = self.bits_per_index
current_bit_position = min(8 - byte_start_position, bits_left_to_read)
# reading first byte
value = (self._array[which_byte] >> byte_start_position) & ((1 << current_bit_position) - 1)
bits_left_to_read -= current_bit_position
which_byte += 1
# reading middle byte(s)
while bits_left_to_read >= 8:
value += self._array[which_byte] << current_bit_position
bits_left_to_read -= 8
current_bit_position += 8
which_byte += 1
#reading last byte
if bits_left_to_read > 0:
value += (self._array[which_byte] & ((1 << bits_left_to_read) - 1)) << current_bit_position
return value
def set(self, position, new_value):
if new_value > ((1 << self.bits_per_index) - 1) or new_value < 0:
raise ValueError(f"value must be in range(0, {((1 << self.bits_per_index) - 1)})")
which_byte, byte_start_position = self._get_actual_position(position)
bits_left_to_set = self.bits_per_index
# setting first byte
bits_left_in_first_byte = min(8 - byte_start_position, bits_left_to_set)
first_byte_start_bits = self._array[which_byte] & ((1 << byte_start_position) - 1)
current_value_to_write = new_value & ((1 << bits_left_in_first_byte) - 1) | {
"domain": "codereview.stackexchange",
"id": 43845,
"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, memory-optimization, bitset",
"url": null
} |
python, python-3.x, memory-optimization, bitset
current_value_to_write = new_value & ((1 << bits_left_in_first_byte) - 1)
self._array[which_byte] >>= byte_start_position + bits_left_in_first_byte
self._array[which_byte] <<= bits_left_in_first_byte
self._array[which_byte] += current_value_to_write
self._array[which_byte] <<= byte_start_position
self._array[which_byte] += first_byte_start_bits
new_value >>= bits_left_in_first_byte
bits_left_to_set -= bits_left_in_first_byte
which_byte += 1
# setting middle byte(s)
while bits_left_to_set >= 8:
current_value_to_write = new_value & 0b11111111
self._array[which_byte] = new_value
new_value >>= 8
bits_left_to_set -= 8
which_byte += 1
# setting last bit
if bits_left_to_set > 0:
self._array[which_byte] >>= bits_left_to_set
self._array[which_byte] <<= bits_left_to_set
self._array[which_byte] += new_value | {
"domain": "codereview.stackexchange",
"id": 43845,
"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, memory-optimization, bitset",
"url": null
} |
python, python-3.x, memory-optimization, bitset
class nbitarray(nbitndarray):
"a class which lets you use a byte array as if it was an "
"array with each index being any number of bits wide"
def __init__(self, bits_per_index, initial_length=0):
if bits_per_index <= 0:
raise ValueError("bits_per_index must be greater than 0")
elif initial_length < 0:
raise ValueError("initial_length must be greater than or equal to 0")
self.bits_per_index = bits_per_index
self.length = initial_length
total_bits = bits_per_index * initial_length
total_bytes = (total_bits // 8) + (total_bits % 8 != 0)
self._array = bytearray(total_bytes)
def _get_actual_position(self, idx):
non_negative_idx = idx if idx >= 0 else self.length + idx
if not 0 <= non_negative_idx < self.length:
raise IndexError(f"attempted to access index {idx} of nbitarray, which is length {self.length}")
return divmod(non_negative_idx * self.bits_per_index, 8)
def append(self, new_value):
# allocating more space if necessary
total_bits = self.bits_per_index * (self.length + 1)
total_bytes = (total_bits // 8) + (total_bits % 8 != 0)
while len(self._array) < total_bytes:
self._array.append(0)
self.length += 1
self.set(-1, new_value)
Answer: PEP-8
Your code does not conform to PEP 8: The Style Guide for Python Code
In particular, CapitalizedWords should be used for ClassNames. This means class nbitndarray should be (perhaps) class NBitNDArray.
Doc Strings
Your doc-strings are not created properly.
class nbitndarray:
"a class which lets you use a byte array as if it was an arbitrarily deeply nested "
"array with each index being any number of bits wide"
...
If you type help(nbitndarray) in an interactive shell, you'll get:
>>> help(nbitndarray)
Help on class nbitndarray in module __main__: | {
"domain": "codereview.stackexchange",
"id": 43845,
"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, memory-optimization, bitset",
"url": null
} |
python, python-3.x, memory-optimization, bitset
class nbitndarray(builtins.object)
| a class which lets you use a byte array as if it was an arbitrarily deeply nested
|
| Data descriptors defined here:
| ...
Notice that the description ends abruptly at "deeply nested". The remainder of the the intended docstring, "array with each index being any number of bits wide" is missing.
The docstring must be created as a single string. For multi-line docstrings (or simply, for every docstring), use a triple-quoted """...""" string:
class nbitndarray:
"""a class which lets you use a byte array as if it was an arbitrarily deeply nested
array with each index being any number of bits wide"""
...
Inheritance
Nowhere are you calling the constructor for your parent class:
class nbitarray(nbitndarray):
def __init__(self, bits_per_index, initial_length=0):
...
super().__init__(dimensions, bits_per_index) # <--- MISSING
...
This must be done for proper subclassing.
Bit packing
You are trying to pack a (multi-dimensional) array into consecutive bits of a bytearray.
It would be simpler to pack the array into a bitarray, and leave the bitarray responsible for the splitting consecutive bits across byte boundaries.
First, install the bitarray module: pip install --upgrade bitarray
Once the bitarray module has been installed, it is easily used for packing & unpacking integers into the bitarray. For example, a packed 2x3 array of 5-bit values could be represented by a 30 bit bitarray:
>>> import bitarray, bitarray.util
>>> ba = bitarray.bitarray([0]*2*3*5)
>>> for i in range(6):
ba[5*i:5*i+5] = bitarray.util.int2ba(i*2, 5)
>>> ba
bitarray('000000001000100001100100001010')
>>> for i in range(6):
print(bitarray.util.ba2int(ba[5*i:5*i+5]))
0
2
4
6
8
10 | {
"domain": "codereview.stackexchange",
"id": 43845,
"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, memory-optimization, bitset",
"url": null
} |
python, python-3.x, memory-optimization, bitset
Your multi-dimensional array could convert the dimensions into a 1-dimensional index, and the the 1-dimensional index could then index into the bitarray.
In terms of inheritance, I would reverse your class structure. The 1-d array should be the base class, and the multiple dimension array would be the subclass.
class NBitArray:
def __init__(self, bits, length):
self._bits = bitarray.bitarray(bits * length)
self._bits.setall(0)
...
...
class NBitNDArray(NBitArray):
def __init__(self, bits, dimensions):
length = ...
super().__init__(bits, length)
...
... | {
"domain": "codereview.stackexchange",
"id": 43845,
"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, memory-optimization, bitset",
"url": null
} |
python, python-3.x
Title: Find match words based on a list of words
Question: I have written a script where I have a mocked data of couple of words in a list. The point is that I as a user will be able to input a text e.g. hello there world! and with this function I have written it should check if I have anything that matches and if it does it should print out that it matches else not.
import re
# mocked database
from collections import Iterable
get_keyword = [
"shorts",
"red banan",
"hello world",
"t-shorts",
"boxers",
]
find_words = re.compile(r'\w+').findall
words = {word.lower() for word in find_words('hello test worldd')}
single_negative: set[str] = set()
multi_negative: list[set[str]] = []
for db_keyword in get_keyword:
if " " in db_keyword:
multi_negative.append(set(db_keyword.split()))
else:
single_negative.add(db_keyword)
def matches(single: set[str], multi: Iterable[set[str]]) -> bool:
return (not words.isdisjoint(single)) or any(multi_word <= words for multi_word in multi)
if matches(single_negative, tuple(multi_negative)):
# Did find any match
print('Match found!')
else:
# Did not find matches
print('Match NOT found!')
There is some scenarios to keep in mind is that e.g.
If we have "hello world" in our list and the word we want to match is "hello there world" -> that should be print out as match as we can find both word hello and world inside "hello there world"
If we have "hello world" in our list and we have the world "hello there" -> that should print out not matched as we need to find both word "hello" and "world" inside "hello there"
If we have "hello" in our list and we have the world "Master, hello there!" -> that should be print out match found as we just want to see if the word hello is inside "Master, hello there!"
Hope anyone have some spare time to see if I could improve anything :D
Answer: Commenting
This is a bad comment.
# mocked database
from collections import Iterable | {
"domain": "codereview.stackexchange",
"id": 43846,
"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
Answer: Commenting
This is a bad comment.
# mocked database
from collections import Iterable
Iterable is not the database mock. The comment is clearly in the wrong place, which makes it useless.
Bad import
from collections import Iterable
There is no such identifier in collections.
Poor naming
get_keyword = [
"shorts",
"red banan",
"hello world",
"t-shorts",
"boxers",
]
The name get_keyword doesn't make sense. This is not a get_xxx function. Nor are the values a keyword. It is a list of words or phrases that you want to detect. Based on the response in the comments, BAD_WORDS might be a suitable name (in CAP_WORDS because it is a global constant).
You should also come up with better names for single_negative and multi_negative.
Bug?
find_words = re.compile(r'\w+').findall
We've just seen "t-shorts" in the list of bad words you're looking for, but since you are using \w+ to split the input sentences into words, if t-shorts appears in the input sentence, it will be split into two "words": "t" and "shorts". Although "t-shorts" will exist in single_negative, it can never be matched. It is only because you are also watching for "shorts" that a sentence containing t-shorts will be flagged. The presence of hyphenated words in your database is misleading, and will likely confuse the user of this code, since they are not matchable.
If you are intending on allowing hyphenated words, you must allow for hyphens in your find_words splitting. While you are at it, you probably should also allow for apostrophes.
find_words = re.compile(r"[-\w']+").findall | {
"domain": "codereview.stackexchange",
"id": 43846,
"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
Caseless matching
Do not use .lower() for caseless string matching. Python has a special purpose function for this: .casefold(). It is more aggressive, removing all case distinctions in a string
Code organization
Use functions! Right now, your code is unusable. If I wanted to test a different sentence, I have to edit the source code. It is not even obvious where the sentence text should go, for there isn't a sentence = "..." variable. If I want to test two different sentences, I can't; the program as written will only operate on one string.
Reworked code
import re
from typing import Iterable
BAD_WORDS: set[str] = set()
BAD_WORD_COMBOS: list[set[str]] = []
def _load_badwords(bad_words_collection: Iterable[str]) -> None:
for bad_words in bad_words_collection:
if ' ' in bad_words:
BAD_WORD_COMBOS.append(set(bad_words.split()))
else:
BAD_WORDS.add(bad_words)
def load_badword_db(*args, **kwargs) -> None:
bad_words_list: list[str] = []
raise NotImplementedError() # TODO: replace with your database loading
_load_badwords(bad_words_list)
def contains_bad_words(sentence: str) -> bool:
words = set(re.findall(r"[-'\w]+", sentence.casefold()))
if not words.isdisjoint(BAD_WORDS):
return True
if any(bad_word_combo <= words for bad_word_combo in BAD_WORD_COMBOS):
return True
return False
if __name__ == '__main__':
def test_badwords_expected(sentence: str):
found = contains_bad_words(sentence)
if found:
print(f"{sentence}: Match found.")
else:
assert f"{sentence}: Match NOT found!"
def test_no_badwords_expected(sentence: str):
found = contains_bad_words(sentence)
if found:
assert f"{sentence}: Match FOUND!"
else:
print(f"{sentence}: Match not found.") | {
"domain": "codereview.stackexchange",
"id": 43846,
"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
# Mock database
_load_badwords([
"shorts",
"red banan",
"hello world",
"t-shorts",
"boxers",
])
test_badwords_expected('Hello test world')
test_badwords_expected('What are t-shorts, anyway?')
test_no_badwords_expected('Hello test worldd')
See test, or unittest, or other unit testing libraries for information on how to write proper unit tests. | {
"domain": "codereview.stackexchange",
"id": 43846,
"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
} |
javascript, error-handling
Title: error tracking in api endpoint
Question: I have built a simple Nuxt 3 app and have some custom api endpoints.
I am currently tracking the user query and response statuses to have some insight when something goes wrong and that the app is working as expected.
Running steps
User will call the endpoint api/search with query parameters
Endpoint will set up the process
Call a third-party api from the server
If the response is ok, the data will be transformed and returned.
in case of error, an error message (and status code) will be returned to the user
Tracking of the user's status code and search query.
Code (simplified)
// api/search.js
const URL = '...'
const buildDataset = items => items.map(...) | {
"domain": "codereview.stackexchange",
"id": 43847,
"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, error-handling",
"url": null
} |
javascript, error-handling
Code (simplified)
// api/search.js
const URL = '...'
const buildDataset = items => items.map(...)
// STEP 1: client calls endpoint
export default defineEventHandler(async (event) => {
// STEP 2: setup
const param = useQuery(event)
const query = param.query
const URL = '...'
const res = {
items: [],
status: null,
msg: ''
}
// STEP 3: get data
try {
const response = await fetch(URL, {
headers: {
mode: 'cors',
'Access-Control-Allow-Origin': '*',
'Content-Type': 'application/json'
}
})
if (!response.ok) {
// will this be executed if anything goes wrong? is step 5 here?
res.status = response.status
res.msg = response.statusText
return res
}
// STEP 4: transform and return data
const results = await response.json()
res.status = response.status
res.items = buildDataset(results.collection)
return res
// STEP 5: handle error
} catch (err) {
// res.status = err.response.status // do I got a validate status code here?
res.msg = 'An error occurred'
return res
// STEP 6: track status code and user search query
} finally {
const data = { query, status: res.status }
fetch(SUPABASE_URL, {
method: 'POST',
headers: {
'apikey': SUPABASE_KEY,
'Authorization': 'Bearer ' + SUPABASE_KEY,
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
})
}
})
Questions
Am I mixing some concepts with my !response.ok? I feel like the line don't get triggered if there is an error getting the data.
Will my data be returned to the client immediately when the data arrives, and will my finally be executed at the end? or will this block the return of the data?
Where can I set the error status in my code to notify the user and my tracking to get insight on what went wrong.
Is there anything else I'm missing? | {
"domain": "codereview.stackexchange",
"id": 43847,
"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, error-handling",
"url": null
} |
javascript, error-handling
Answer: Understanding the Fetch API
The MDN documentation on using the Fetch API answers most of your questions,
it's nicely written with many example use cases,
I recommend to read it well from top to bottom.
Checking that the fetch was successful
Given this code:
const response = await fetch(URL, ...)
if (!response.ok) {
// ...
}
The if statement will not be reached if fetch throws an exception,
which can happen for example when the URL is garbage,
or the server does not respond, or other kind of network errors.
The documentation has a dedicated section on error handling,
and recommends to use this pattern:
fetch('flowers.jpg')
.then((response) => {
if (!response.ok) {
throw new Error('Network response was not OK');
}
return response.blob();
})
.then((myBlob) => {
myImage.src = URL.createObjectURL(myBlob);
})
.catch((error) => {
console.error('There has been a problem with your fetch operation:', error);
});
Behavior of finally and the return statement
The MDN documentation on Promises explains this nicely.
The block of code in finally will always be executed, whether the return statement is reached or an exception is thrown.
For example:
const result = await new Promise(resolve => resolve("success"))
.finally(() => console.log("finally in case of success"))
console.log("result =", result)
await new Promise((resolve, reject) => reject(new Error("failure")))
.catch(err => console.log("failure happened"))
.finally(() => console.log("finally in case of failure"))
await new Promise((resolve, reject) => reject(new Error("failure")))
.finally(() => console.log("finally in case of failure without catching"))
The output of the above code will be: | {
"domain": "codereview.stackexchange",
"id": 43847,
"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, error-handling",
"url": null
} |
javascript, error-handling
The output of the above code will be:
finally in case of success
result = success
failure happened
finally in case of failure
finally in case of failure without catching
file:///path/to/example.js:50
await new Promise((resolve, reject) => reject(new Error("failure")))
^
Error: failure
at file:///path/to/example.js:50:47
at new Promise (<anonymous>)
at file:///path/to/example.js:50:7
at processTicksAndRejections (node:internal/process/task_queues:94:5)
Setting error status, notifying the user
Where can I set the error status in my code to notify the user and my tracking to get insight on what went wrong.
Follow the example in the MDN docs:
Chain the fetch to a .then(...), which checks the response.ok flag and returns response.json() if ok,
Chain another .then(...), which will receive the json from the previous one, handle it, and notify the user of success.
Chain a .catch(...) to handle exceptions that the previous calls may have thrown, for example about network errors, or when response.ok was not true. Notify the user of failure.
Chain a .finally(...) to do cleanup that must always be performed, regardless of successful processing of the response or failures. | {
"domain": "codereview.stackexchange",
"id": 43847,
"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, error-handling",
"url": null
} |
beginner, c, formatting, io
Title: K&R Exercise 1.22 - "fold" long input lines
Question: Until recently, I decided to go back to Chapter 1 of the K&R Book, Edition 2, to try to "improve" the code I've already done. I have also made some changes since I was limited to just using what they taught in each section of Chapter 1. Especially the following exercise:
Exercise 1-22. Write a program to "fold" long input lines into two or
more shorter lines after the last non-blank character that occurs
before the n-th column of input. Make sure your program does something
intelligent with very long lines, and if there are no blanks or tabs
before the specified column.
Here is my solution to the exercise above:
#include <stdio.h>
#include <string.h>
#define DEFLINEWIDTH 80 /* DEFAULT LINE WIDTH */
#define BUFSIZE 1024
inline int isblank(int c);
/* fold long input lines */
int
main(void)
{
char buf[BUFSIZE];
int i, indx;
int width, space;
int ch;
width = DEFLINEWIDTH;
indx = 0;
while ((ch = getchar()) != EOF) {
if (ch == '\n') {
printf("%.*s\n", indx, buf);
indx = 0;
}
for (i = indx; i >= 0 && !isblank(buf[i]); i--)
;
space = i;
if (space >= width && space != -1) {
printf("%.*s\n", space, buf);
memmove(buf, buf + space, indx - space);
indx -= space;
}
buf[indx++] = ch;
}
return 0;
}
inline int
isblank(int c)
{
return c == ' ' || c == '\t';
}
Which I would like to know how to improve it, even if it's just a little bit.
Sample Input | {
"domain": "codereview.stackexchange",
"id": 43848,
"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": "beginner, c, formatting, io",
"url": null
} |
beginner, c, formatting, io
Which I would like to know how to improve it, even if it's just a little bit.
Sample Input
Lorem Ipsum is simply dummy text of the printing and typesetting
industry. Lorem Ipsum has been the industry's standard dummy text ever
since the 1500s, when an unknown printer took a galley of type and
scrambled it to make a type specimen book. It has survived not only
five centuries, but also the leap into electronic typesetting,
remaining essentially unchanged. It was popularised in the 1960s with
the release of Letraset sheets containing Lorem Ipsum passages, and
more recently with desktop publishing software like Aldus PageMaker
including versions of Lorem Ipsum.
Sample Input
Contrary to popular belief, Lorem Ipsum is not simply random text. It
has roots in a piece of classical Latin literature from 45 BC, making
it over 2000 years old. Richard McClintock, a Latin professor at
Hampden-Sydney College in Virginia, looked up one of the more obscure
Latin words, consectetur, from a Lorem Ipsum passage, and going
through the cites of the word in classical literature, discovered the
undoubtable source. Lorem Ipsum comes from sections 1.10.32 and
1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the
theory of ethics, very popular during the Renaissance. The first line
of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in
section 1.10.32.
Sample Input | {
"domain": "codereview.stackexchange",
"id": 43848,
"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": "beginner, c, formatting, io",
"url": null
} |
beginner, c, formatting, io
Sample Input
There are many variations of passages of Lorem Ipsum available, but
the majority have suffered alteration in some form, by injected
humour, or randomised words which don't look even slightly believable.
If you are going to use a passage of Lorem Ipsum, you need to be sure
there isn't anything embarrassing hidden in the middle of text. All
the Lorem Ipsum generators on the Internet tend to repeat predefined
chunks as necessary, making this the first true generator on the
Internet. It uses a dictionary of over 200 Latin words, combined with
a handful of model sentence structures, to generate Lorem Ipsum which
looks reasonable. The generated Lorem Ipsum is therefore always free
from repetition, injected humour, or non-characteristic words etc.
Sample Input
Write a program to "fold" long input lines in two or more shorter
lines after the non-last blank character that occurs before the n-th
columns of input. Make sure your program does something intelligent
with very long lines, and if there are no blanks or tabs before the
specified column.
Here are the outputs.
Note: I intended the results to be somewhat similar to the "fold" command. (though unfortunately, I couldn't get them to be exact).
By the way, I tried to show the differences between both results using "vimdiff". The ones on the right are the results of the program I wrote. | {
"domain": "codereview.stackexchange",
"id": 43848,
"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": "beginner, c, formatting, io",
"url": null
} |
beginner, c, formatting, io
Answer: I didn't get the expected output - some words were split by newlines, and extra newlines are added after the newlines present in the input:
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem
Ipsum has been the industry's standard dummy text ever since the 1500s, when an
unknown printer took a galley of type and scrambled it to make a type specimen
book. It has survived not only five centuries, but also the leap into electronic
typesetting, remaining essentially unchanged. It was popularised in the 1960s w
ith the release of Letraset sheets containing Lorem Ipsum passages, and more rec
ently with desktop publishing software like Aldus PageMaker including versions o
f Lorem Ipsum.
Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots
in a piece of classical Latin literature from 45 BC, making it over 2000 years
old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia
, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum
passage, and going through the cites of the word in classical literature, disco
vered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.3
3 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero,
written in 45 BC. This book is a treatise on the theory of ethics, very popular
during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit am
et..", comes from a line in section 1.10.32. | {
"domain": "codereview.stackexchange",
"id": 43848,
"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": "beginner, c, formatting, io",
"url": null
} |
beginner, c, formatting, io
There are many variations of passages of Lorem Ipsum available, but the majorit
y have suffered alteration in some form, by injected humour, or randomised words
which don't look even slightly believable. If you are going to use a passage of
Lorem Ipsum, you need to be sure there isn't anything embarrassing hidden in th
e middle of text. All the Lorem Ipsum generators on the Internet tend to repeat
predefined chunks as necessary, making this the first true generator on the Inte
rnet. It uses a dictionary of over 200 Latin words, combined with a handful of m
odel sentence structures, to generate Lorem Ipsum which looks reasonable. The ge
nerated Lorem Ipsum is therefore always free from repetition, injected humour, o
r non-characteristic words etc.
We can easily fix the extra blank lines - that's caused by printing the input line and a newline. Just don't add a newline of our own:
if (ch == '\n') {
printf("%.*s", indx, buf); | {
"domain": "codereview.stackexchange",
"id": 43848,
"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": "beginner, c, formatting, io",
"url": null
} |
beginner, c, formatting, io
Fixing the broken words is more effort, and involves re-thinking the logic.
The function name isblank() is risky, because all names beginning is and followed by a letter are reserved for future use by <ctype.h>. We're allowed to begin with is_, so is_blank() is a sensible replacement.
If we define it before main() we can avoid having to forward-declare it. And don't bother writing inline - compilers all make better decisions than programmers, and will ignore that keyword.
In the days when K&R 2nd Ed was written, variables had to all be declared before the first statement in a block. Using a modern C standard, we're not so constrained, so we can define variables at first use. That helps us avoid a common class of bug (though good compilers will do flow analysis, and as part of that, complain about use before assignment).
We should return non-zero (I recommend the EXIT_FAILURE value from <stdlib.h>) if we encounter any input or output error. That allows other programs to invoke this one and know whether it was successful.
There's no need for i here, because we could work on space directly:
for (i = indx; i >= 0 && !isblank(buf[i]); i--)
;
space = i;
I don't think we want to be conducting this search every single time we read a character. Instead, we should be able to simply make a note of when we last saw a space.
Modified code
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define DEFLINEWIDTH 80 /* DEFAULT LINE WIDTH */
#define BUFSIZE 1024
int
is_blank(int c)
{
return c == ' ' || c == '\t';
}
/* fold long input lines */
int
main(void)
{
char buf[BUFSIZE];
unsigned int i = 0;
unsigned int const width = DEFLINEWIDTH;
unsigned int space = width; /* if we see no space, we'll break the word as necessary */
int ch;
while ((ch = getchar()) != EOF) { | {
"domain": "codereview.stackexchange",
"id": 43848,
"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": "beginner, c, formatting, io",
"url": null
} |
beginner, c, formatting, io
while ((ch = getchar()) != EOF) {
if (ch == '\n') {
if (printf("%.*s", i, buf) < 0) {
perror("output");
return EXIT_FAILURE;
}
i = 0;
space = width;
}
if (is_blank(ch)) {
space = i;
}
buf[i++] = (char)ch;
if (i >= width) {
/* We need to break the line - replace whitespace with newline */
if (printf("%.*s\n", space, buf) < 0) {
perror("output");
return EXIT_FAILURE;
}
if (space != width) {
/* advance to skip spaces */
while (is_blank(buf[++space])) {
/* pass */
}
}
memmove(buf, buf + space, i - space);
i -= space;
space = width;
}
}
if (ferror(stdin)) {
perror("input");
return EXIT_FAILURE;
}
} | {
"domain": "codereview.stackexchange",
"id": 43848,
"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": "beginner, c, formatting, io",
"url": null
} |
python, python-3.x, homework
Title: Function that returns a sequence of numbers [x: sqrt(x_(n-1)^3)] given a start value and a max value
Question: I'd love to get a review of my code, which I've already submitted as homework. I'd like some guidance as to how to write it more DRY-ly: I wrote the whole round, sqrt and exponentiation twice — how could I write it only once? Ideally I'd want to do it within the same function, it'd be a little ugly to write a function like cube_then_sqrt_then_round_to_2dp(number)
P.S. The variables are intentionally camelCase, I'm aware this is against the recommendations of PEP8
# Created Date: 2022-09-6 17:18:00+08:00
# version ='1.0.0'
import math
# generate_sequences function is used to print a sequence of values rounded to two decimal places starting from the
# start value till it's less than or equal to the maxValue. The sequence is value_n = sqrt(value_(n-1) ^ 3)
# Inputs
# start (int) - the starting value of the sequence
# maxValue (int) - the largest value that can be included in the sequence
# Return
# sequence (list) - a list containing the values of the sequence
def generate_sequence(start, maxValue):
if type(start) != int or type(maxValue) != int or (not (1 <= start <= 20)) or (not (100000 <= maxValue <= 6000000)):
return None
precision = 2
exponent = 3
sequence = [round(math.sqrt(start ** exponent), precision)]
while (currentValue := round(math.sqrt(sequence[-1] ** exponent), precision)) <= maxValue:
sequence.append(currentValue)
return sequence
# Test code
print(generate_sequence(2, 6000000)) # Replace value as required for testing
Expected output:
[2.83, 4.76, 10.39, 33.49, 193.81, 2698.14, 140151.17]
Answer: Instead of using comments to describe the function, use a doc string. This can then be used by tools, unlike comments.
def generate_sequence(start, maxValue):
'''
Return a sequence of values by cubing the previous value, taking the
square root and rounding to 2 decimal places. | {
"domain": "codereview.stackexchange",
"id": 43849,
"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, homework",
"url": null
} |
python, python-3.x, homework
start - the starting value of the sequence
maxValue - the largest value that can be included in the sequence
'''
Don't test argument types like this:
if type(start) != int or type(maxValue) != int or (not (1 <= start <= 20)) or (not (100000 <= maxValue <= 6000000)):
return None
Instead, we can use type annotations on the function:
def generate_sequence(start: int, maxValue: int):
However, in this case, I see no reason to insist that the inputs have to be integers - surely any numeric type should be acceptable?
The range tests look unhelpful, too - why should a start value greater than 20 result in empty output? If there's a meaningful limit imposed by the problem space, then throw an exception, rather than returning an empty set:
if start <= 1:
raise ValueError("start value must be greater than 1")
Instead of separately cubing and taking square root, we can combine them into a single exponentiation, because √x³ ≡ x ** 1.5.
We can avoid the repetition of the calculation by including the start value in our sequence, but removing it when we return:
precision = 2
exponent = 1.5
sequence = [start]
while (currentValue := round((sequence[-1] ** exponent), precision)) <= maxValue:
sequence.append(currentValue)
return sequence[1:]
As a more advanced step, consider writing an infinite generator of the sequence, and a separate step to truncate it when it reaches the limit value. This allows us to transform the result in other ways, e.g. taking the first N values (making starts of 0 and 1 useful again).
Improved code
This also shows how to add a set of tests, instead of modifying the program for each test. Sorry the function names aren't great - I have writer's block today!
import itertools
def infinite_sequence(value):
'''
Generate a sequence of values by cubing the previous value, taking the
square root and rounding to 2 decimal places.
value - the starting value of the sequence
''' | {
"domain": "codereview.stackexchange",
"id": 43849,
"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, homework",
"url": null
} |
python, python-3.x, homework
value - the starting value of the sequence
'''
if value < 0:
raise ValueError("start value must be positive")
precision = 2
exponent = 1.5
while True:
value = round(value ** exponent, precision)
yield value
def generate_sequence(start, max_value):
'''
Return a list of values by cubing the previous value, taking the
square root and rounding to 2 decimal places.
start - the starting value of the sequence
maxValue - the largest value that can be included in the sequence
Examples:
>>> generate_sequence(2, 6000000)
[2.83, 4.76, 10.39, 33.49, 193.81, 2698.14, 140151.17]
>>> generate_sequence(2, 2)
[]
>>> generate_sequence(-2, 0)
Traceback (innermost last):
ValueError: start value must be positive
>>> generate_sequence(0, 6)
Traceback (innermost last):
ValueError: start value would result in infinite list
>>> generate_sequence(1, 6)
Traceback (innermost last):
ValueError: start value would result in infinite list
'''
if 0 <= start <= 1:
raise ValueError("start value would result in infinite list")
return list(itertools.takewhile(lambda x: x <= max_value,
infinite_sequence(start)))
if __name__ == '__main__':
import doctest
doctest.testmod() | {
"domain": "codereview.stackexchange",
"id": 43849,
"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, homework",
"url": null
} |
c++, algorithm, primes, sieve-of-eratosthenes
Title: Next level Improved Sieve of Eratosthenes
Question: This is the next development for the Sieve of Eratosthenes algorithm, where all the multiples of 2,3 and 5 are eliminated, which will not take any memory or time.
As my last question Improved Sieve of Eratosthenes I will follow your instructions and study it deeply as soon as I finish my exams.
I wanted to know if there are any specific improvements for this one!
This algorithm generates prime numbers up to a given limit N where it skips the first 10 primes when N>530.
N.B: I can make an infinite number of these developments, as I go higher it gets more and more complicated.
#include <iostream>
int D3SOE(unsigned int n1_m) {
unsigned int n1 = 0, g = 0, z = 0, f1 = 0, f2 = 0, f3 = 0, f4 = 0, f5 = 0, f6 = 0, f7 = 0, f8 = 0, f9 = 0, l = 0, f10 = 0;
int p = 0;
unsigned char* prmLst = new unsigned char[n1_m + 1];
// Initialising the D3SOE array with false values
for (int i = 0; i < n1_m; i++)
prmLst[i] = false; | {
"domain": "codereview.stackexchange",
"id": 43850,
"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++, algorithm, primes, sieve-of-eratosthenes",
"url": null
} |
c++, algorithm, primes, sieve-of-eratosthenes
// The main elimination theorem
for (n1 = 1; n1 <= ceil((8 * (ceil((9 * ceil((2 * (sqrt(((2 * (floor((3 * floor((10 * floor((9 * (n1_m)+1) / 8.0) + 8) / 9.0) + 1) / 2.0)) + 1) / 4.0)) - 0.5) - 1) / 3) - 8) / 10.0)) - 1) / 9); n1++)
{
if (prmLst[n1] != 0)
continue;
z = floor(((3 * floor((10 * floor((9 * (n1)+1) / 8.0) + 8) / 9.0) + 1) / 2.0));
p = ((2 * floor(((3 * floor((10 * floor((9 * (n1)+1) / 8.0) + 8) / 9.0) + 1) / 2.0))) + 1);
f1 = ceil((8 * (ceil((9 * ceil((p - 2) / 3.0) - 8) / 10.0)) - 1) / 9);
f2 = ceil((8 * (ceil((9 * ceil(((7 * p) - 2) / 3.0) - 8) / 10.0)) - 1) / 9);
f3 = ceil((8 * (ceil((9 * ceil(((11 * p) - 2) / 3.0) - 8) / 10.0)) - 1) / 9);
f4 = ceil((8 * (ceil((9 * ceil(((13 * p) - 2) / 3.0) - 8) / 10.0)) - 1) / 9);
f5 = ceil((8 * (ceil((9 * ceil(((17 * p) - 2) / 3.0) - 8) / 10.0)) - 1) / 9);
f6 = ceil((8 * (ceil((9 * ceil(((19 * p) - 2) / 3.0) - 8) / 10.0)) - 1) / 9);
f7 = ceil((8 * (ceil((9 * ceil(((23 * p) - 2) / 3.0) - 8) / 10.0)) - 1) / 9);
f8 = ceil((8 * (ceil((9 * ceil(((29 * p) - 2) / 3.0) - 8) / 10.0)) - 1) / 9);
f9 = ceil((8 * (ceil((9 * ceil(((31 * p) - 2) / 3.0) - 8) / 10.0)) - 1) / 9.0); | {
"domain": "codereview.stackexchange",
"id": 43850,
"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++, algorithm, primes, sieve-of-eratosthenes",
"url": null
} |
c++, algorithm, primes, sieve-of-eratosthenes
l = ceil((8 * (ceil((9 * ceil(((4 * ((z * z) + z)) - 1) / 3.0) - 8) / 10.0)) - 1) / 9);
for (g = l; g < n1_m; g += (f9 - f1))
{
prmLst[g] = true;
}
if ((p - 1) % 30 == 0)
{
for (g = l + (f2 - f1); g < n1_m; g += (f9 - f1))
{
prmLst[g] = true;
}
for (g = l + (f3 - f1); g < n1_m; g += (f9 - f1))
{
prmLst[g] = true;
}
for (g = l + (f4 - f1); g < n1_m; g += (f9 - f1))
{
prmLst[g] = true;
}
for (g = l + (f5 - f1); g < n1_m; g += (f9 - f1))
{
prmLst[g] = true;
}
for (g = l + (f6 - f1); g < n1_m; g += (f9 - f1))
{
prmLst[g] = true;
}
for (g = l + (f7 - f1); g < n1_m; g += (f9 - f1))
{
prmLst[g] = true;
}
for (g = l + (f8 - f1); g < n1_m; g += (f9 - f1))
{
prmLst[g] = true;
}
}
else if ((p - 7) % 30 == 0)
{
for (g = l - (f2 - f1); g < n1_m; g += (f9 - f1))
{
prmLst[g] = true;
}
for (g = l + (f3 - f2); g < n1_m; g += (f9 - f1))
{
prmLst[g] = true;
}
for (g = l + (f4 - f2); g < n1_m; g += (f9 - f1))
{
prmLst[g] = true;
}
for (g = l + (f5 - f2); g < n1_m; g += (f9 - f1))
{
prmLst[g] = true;
}
for (g = l + (f6 - f2); g < n1_m; g += (f9 - f1))
{
prmLst[g] = true;
}
for (g = l + (f7 - f2); g < n1_m; g += (f9 - f1))
{
prmLst[g] = true;
}
for (g = l + (f8 - f2); g < n1_m; g += (f9 - f1))
{ | {
"domain": "codereview.stackexchange",
"id": 43850,
"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++, algorithm, primes, sieve-of-eratosthenes",
"url": null
} |
c++, algorithm, primes, sieve-of-eratosthenes
}
for (g = l + (f8 - f2); g < n1_m; g += (f9 - f1))
{
prmLst[g] = true;
}
}
else if ((p - 11) % 30 == 0)
{
for (g = l - (f3 - f1); g < n1_m; g += (f9 - f1))
{
prmLst[g] = true;
}
for (g = l - (f3 - f2); g < n1_m; g += (f9 - f1))
{
prmLst[g] = true;
}
for (g = l + (f4 - f3); g < n1_m; g += (f9 - f1))
{
prmLst[g] = true;
}
for (g = l + (f5 - f3); g < n1_m; g += (f9 - f1))
{
prmLst[g] = true;
}
for (g = l + (f6 - f3); g < n1_m; g += (f9 - f1))
{
prmLst[g] = true;
}
for (g = l + (f7 - f3); g < n1_m; g += (f9 - f1))
{
prmLst[g] = true;
}
for (g = l + (f8 - f3); g < n1_m; g += (f9 - f1))
{
prmLst[g] = true;
}
}
else if ((p - 13) % 30 == 0)
{
for (g = l - (f4 - f1); g < n1_m; g += (f9 - f1))
{
prmLst[g] = true;
}
for (g = l - (f4 - f2); g < n1_m; g += (f9 - f1))
{
prmLst[g] = true;
}
for (g = l - (f4 - f3); g < n1_m; g += (f9 - f1))
{
prmLst[g] = true;
}
for (g = l + (f5 - f4); g < n1_m; g += (f9 - f1))
{
prmLst[g] = true;
}
for (g = l + (f6 - f4); g < n1_m; g += (f9 - f1))
{
prmLst[g] = true;
}
for (g = l + (f7 - f4); g < n1_m; g += (f9 - f1))
{
prmLst[g] = true;
}
for (g = l + (f8 - f4); g < n1_m; g += (f9 - f1))
{
prmLst[g] = true;
}
} | {
"domain": "codereview.stackexchange",
"id": 43850,
"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++, algorithm, primes, sieve-of-eratosthenes",
"url": null
} |
c++, algorithm, primes, sieve-of-eratosthenes
{
prmLst[g] = true;
}
}
else if ((p - 17) % 30 == 0)
{
for (g = l - (f5 - f1); g < n1_m; g += (f9 - f1))
{
prmLst[g] = true;
}
for (g = l - (f5 - f2); g < n1_m; g += (f9 - f1))
{
prmLst[g] = true;
}
for (g = l - (f5 - f3); g < n1_m; g += (f9 - f1))
{
prmLst[g] = true;
}
for (g = l - (f5 - f4); g < n1_m; g += (f9 - f1))
{
prmLst[g] = true;
}
for (g = l + (f6 - f5); g < n1_m; g += (f9 - f1))
{
prmLst[g] = true;
}
for (g = l + (f7 - f5); g < n1_m; g += (f9 - f1))
{
prmLst[g] = true;
}
for (g = l + (f8 - f5); g < n1_m; g += (f9 - f1))
{
prmLst[g] = true;
}
}
else if ((p - 19) % 30 == 0)
{
for (g = l - (f6 - f1); g < n1_m; g += (f9 - f1))
{
prmLst[g] = true;
}
for (g = l - (f6 - f2); g < n1_m; g += (f9 - f1))
{
prmLst[g] = true;
}
for (g = l - (f6 - f3); g < n1_m; g += (f9 - f1))
{
prmLst[g] = true;
}
for (g = l - (f6 - f4); g < n1_m; g += (f9 - f1))
{
prmLst[g] = true;
}
for (g = l - (f6 - f5); g < n1_m; g += (f9 - f1))
{
prmLst[g] = true;
}
for (g = l + (f7 - f6); g < n1_m; g += (f9 - f1))
{
prmLst[g] = true;
}
for (g = l + (f8 - f6); g < n1_m; g += (f9 - f1))
{
prmLst[g] = true;
}
}
else if ((p - 23) % 30 == 0)
{ | {
"domain": "codereview.stackexchange",
"id": 43850,
"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++, algorithm, primes, sieve-of-eratosthenes",
"url": null
} |
c++, algorithm, primes, sieve-of-eratosthenes
}
}
else if ((p - 23) % 30 == 0)
{
for (g = l - (f7 - f1); g < n1_m; g += (f9 - f1))
{
prmLst[g] = true;
}
for (g = l - (f7 - f2); g < n1_m; g += (f9 - f1))
{
prmLst[g] = true;
}
for (g = l - (f7 - f3); g < n1_m; g += (f9 - f1))
{
prmLst[g] = true;
}
for (g = l - (f7 - f4); g < n1_m; g += (f9 - f1))
{
prmLst[g] = true;
}
for (g = l - (f7 - f5); g < n1_m; g += (f9 - f1))
{
prmLst[g] = true;
}
for (g = l - (f7 - f6); g < n1_m; g += (f9 - f1))
{
prmLst[g] = true;
}
for (g = l + (f8 - f7); g < n1_m; g += (f9 - f1))
{
prmLst[g] = true;
}
}
else if ((p - 29) % 30 == 0)
{
for (g = l - (f8 - f1); g < n1_m; g += (f9 - f1))
{
prmLst[g] = true;
}
for (g = l - (f8 - f2); g < n1_m; g += (f9 - f1))
{
prmLst[g] = true;
}
for (g = l - (f8 - f3); g < n1_m; g += (f9 - f1))
{
prmLst[g] = true;
}
for (g = l - (f8 - f4); g < n1_m; g += (f9 - f1))
{
prmLst[g] = true;
}
for (g = l - (f8 - f5); g < n1_m; g += (f9 - f1))
{
prmLst[g] = true;
}
for (g = l - (f8 - f6); g < n1_m; g += (f9 - f1))
{
prmLst[g] = true;
}
for (g = l - (f8 - f7); g < n1_m; g += (f9 - f1))
{
prmLst[g] = true;
}
}
} | {
"domain": "codereview.stackexchange",
"id": 43850,
"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++, algorithm, primes, sieve-of-eratosthenes",
"url": null
} |
c++, algorithm, primes, sieve-of-eratosthenes
// printing for loop
for (int n1 = 1; n1 < n1_m; n1++)
if (!prmLst[n1]) {
z = (2 * floor(((3 * floor((10 * floor((9 * (n1)+1) / 8.0) + 8) / 9.0) + 1) / 2.0)) + 1);
std :: cout << z << " ";
}
return 0;
}
// derivation function
int main() {
unsigned int n1_m, N = 0;
std::cout << "\n Enter limit : ";
std::cin >> N;
n1_m = ceil((8 * (ceil((9 * ceil(((N)-2) / 3.0) - 8) / 10.0)) - 1) / 9);
D3SOE(n1_m);
return 0;
}
Answer: Naming things
Your code is hard to read, in a large part because your function and variable names don't convey any meaning. What does D3SOE mean? Why is the parameter of that function named n1_m? Try to use concise but meaningful names.
The function should be named after what it does. How it does it is less important. So instead of sieve_of_eratosthenes(), call it print_primes(). The parameter is the highest number to check, so call it highest_number, although max_n or n_max are fine as well and more concise, as n is a very commonly used abbreviation for number.
Don't abbreviate unnecessarily. Instead of prmLst, write primeList or primes.
There are lots of complex-looking expressions, like ceil((8 * (ceil((9 * ceil(((N)-2) / 3.0) - 8) / 10.0)) - 1) / 9). You can give those expressions a name by creating a new function. This makes the code more readable and more self-documenting.
Don't repeat yourself
There is a lot of repetition in your code. Apart from being more work to write, it also increases the likelihood of errors being introduced. Try to find some ways to avoid code duplication.
Consider the variables f1...f9 (f10 is declared but never used). You could make an array f[] instead, and intialize them like so:
static const int multipliers[9] = {1, 7, 11, 13, 17, 19, 23, 29, 31};
...
int f[9];
for (std::size_t i = 0; i < 9; ++i)
{
f[i] = ceil((8 * (ceil((9 * ceil(((multipliers[i] * p) - 2) / 3.0) - 8) / 10.0)) - 1) / 9);
} | {
"domain": "codereview.stackexchange",
"id": 43850,
"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++, algorithm, primes, sieve-of-eratosthenes",
"url": null
} |
c++, algorithm, primes, sieve-of-eratosthenes
Once you have an array of fs, you can also get rid of the duplicated for-loops, for example:
if ((p - 1) % 30 == 0)
{
for (std::size_t i = 1; i < 8; ++i)
{
for (g = l + (f[i] - f[i - 1]); g < n1_m; g += f[8] - f[0])
{
prmLst[g] = true;
}
}
}
But even the chain of if-else-statements can be avoided, by adding another loop that checks if (p - multipliers[i]) % 30 == 0, and calculates which values in f the inner loop should subtract from each other.
The above code still hardcodes the number of fs to 9, it would be even better to make it so generic that if you wanted to add another multiplier to check, you only would have to add another prime to multipliers[], and the rest of the code can be left unchanged.
Memory leak
You allocate memory for prmLst[], but you never delete[] it. This means your program has a memory leak. Maybe it's not important here, but in larger projects these things quickly become problematic. Either make sure you clean up memory properly, or avoid having to do manual memory allocations in the first place by using STL containers, such as std::vector:
std::vector<bool> prmLst(n1_m + 1);
Missing #includes and namespace issues
If you call math functions like ceil() and sqrt(), you should #include <cmath>. In C++, the functions in the standard library are all declared inside the namespace std, and there is no guarantee that the math functions will also be available in the global namespace. So you should write std::ceil(), std::sqrt() and so on.
Return value
Since D3SOE() doesn't return any useful value, just make it return void. Alternatively, instead of having D3SOE() both generate and print the primes, have it only generate a list of primes, and return it. This allows the caller to decide what to do with those primes. This reduces the responsibilities of D3SOE(), thus simplifying that function, while at the same time making it more versatile. | {
"domain": "codereview.stackexchange",
"id": 43850,
"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++, algorithm, primes, sieve-of-eratosthenes",
"url": null
} |
python, performance, random, io
Title: generate lottery numbers to store in a text file
Question: I scripted a program in python to generate lottery numbers for user. There are two playing methods:
Lotto6aus49: User can choose any 6 numbers out of 49.
Eurojackpot: User can choose 5 numbers out of 50 and 2 numbers out of 12.
The script will generate some random numbers with above condition and generate a text file. Since I am new to python, I am not pretty sure, if my source code is efficient and python friendly. Are there any improvements I can do to my source code? Or are there any possibilities, where the source code can be minimized?
Sourcecode:
import random
from datetime import datetime
date = datetime.now()
date_format = str(date.strftime('%d-%m-%Y %H:%M:%S'))
main_numbers = range(1, 50 + 1)
super_numbers = range(1, 12 + 1)
main_numbers_lotto = range(1, 49 + 1)
file_name = f'Lottozahlen generiert am '
lotto_name = f'Lotto 6aus49: '
euro_name_1 = f'Eurojackpot Zahlen: '
euro_name_2 = f'Eurojackpot Eurozahlen: '
coder = 'by mr.enso'
generated_time = f'generiert am: ' + date_format + ' '
coder_date_time = generated_time + coder
success_message = 'Die Text Datei wurde erfolgreich erstellt.'
def euro_number_generator():
random_main_numbers = str(sorted(random.sample(main_numbers, 5)))
random_super_numbers = str(sorted(random.sample(super_numbers, 2)))
return random_main_numbers, random_super_numbers
# Assign individual variables to function euro_number_generator-output
main_numbers_output, super_numbers_output = euro_number_generator()
def lotto_number_generator():
random_main_numbers_lotto = str(sorted(random.sample(main_numbers, 6)))
return random_main_numbers_lotto
# Formatting output-numbers
final_lotto = lotto_name + lotto_number_generator().replace('[', '').replace(']', '')
final_euro_numbers1 = euro_name_1 + main_numbers_output.replace('[', '').replace(']', '')
final_euro_numbers2 = euro_name_2 + super_numbers_output.replace('[', '').replace(']', '') | {
"domain": "codereview.stackexchange",
"id": 43851,
"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, random, io",
"url": null
} |
python, performance, random, io
def generate_textfile():
f = open(file_name + date_format + f'.txt', f'w+')
f.write(final_lotto + f'\n\n' + final_euro_numbers1 + f'\n' + final_euro_numbers2 + f'\n\n' + coder_date_time)
f.close()
def print_to_terminal():
print(f'\n' + final_lotto + f'\n' + final_euro_numbers1 + f'\n' + final_euro_numbers2 + f'\n\n' + coder_date_time)
def print_success_message():
print(f'\n' + success_message + f'\n')
print_to_terminal()
generate_textfile()
print_success_message()
Answer: Layout
You are mixing functions and variables in your code, in general the structure of a file might look like:
Imports
Constants
Functions
Main Guard
Also, according to PEP-8, your constants should be in UPPER_SNAKE case.
It is also common practice to make function names verbs, i.e.
euro_number_generator
lotto_number_generator
become
generate_euros_numbers
generate_lotto_numbers
(Also, "generator" has a very specific meaning in Python which you will learn about later)
Compartmentalise
You declare a lot of variables at top-level which are only used within your functions. These should be kept local to where they're used:
main_numbers = range(1, 50 + 1)
Could be declared inside euro_number_generator, likewise for the other ranges (though main_numbers_lotto is unused), success_message (honestly should be just inside the print function inside a main guard, as it's always the same), etc.
Rather than having the functions generate_textfile and print_to_terminal we could have a function which returns the string used by both of these allowing them to simply be printed or written as needed.
Using Python Functions
Rather than constructing your strings by casting to string and replacing the brackets, it would be better to use Python's str.join() functions.
Instead of (effectively)
final_lotto = lotto_name + str(sorted(random.sample(main_numbers, 6))).replace('[', '').replace(']', '') | {
"domain": "codereview.stackexchange",
"id": 43851,
"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, random, io",
"url": null
} |
python, performance, random, io
we can do:
lotto_nums = sorted(random.sample(main_numbers, 6))
final_lotto = f"{lotto name}: {", ".join(map(str, lotto_nums))}" # Join takes lists of strings, so convert each to string with map
Also date.strftime returns a string, so we don't need to cast it.
F-strings
You are making your strings f-strings, but not using them as they are intended. F-strings substitute in-place for variables so that you don't have to concatenate strings together or use disjointed formats.
Thus:
generated_time = f'generiert am: ' + date_format + ' '
becomes
generated_time = f'generiert am: {date_format} '
or
f.write(final_lotto + f'\n\n' + final_euro_numbers1 + f'\n' + final_euro_numbers2 + f'\n\n' + coder_date_time)
becomes
f.write(f"{final_lotto}\n\n{final_euro_numbers1}\n{final_euro_numbers2}\n\n{coder_date_time}")
Although personally, given these are on different lines, I would split it into multiple writes (despite this being less efficient, efficiency here is not really a concern)
You also don't need to declare f-strings where you are not making such a substitution.
Arguments
You are not passing any arguments into your functions, which makes them a lot less flexible. At this point, they may as well be in-line statements. For example, in generate_textfile you take variables from the higher level to generate your filename, a better way might be:
def generate_textfile(filename, numbers):
with open(filename, 'w') as out_file: # Use `with` to auto close your files in case of e.g. errors
out_file.write('\n'.join(numbers))
out_file.write(f'\n\n{coder_date_time}')
generate_textfile(f'{file_name}{date_format}.txt', (final_lotto, final_euro_numbers1, final_euro_numbers2)) | {
"domain": "codereview.stackexchange",
"id": 43851,
"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, random, io",
"url": null
} |
python, performance, random, io
Purpose
As well as adding the main guard, one of the things we might want to do is make it so that the program generates only one as specified by the user.
Inside our main guard, we could, for example, check against any arguments passed in:
if __name__ == '__main__':
import sys
if not sys.argv:
# generate_both
else:
for arg in sys.argv:
arg = arg.lower()
if arg == 'lotto':
# Generate lotto
elif arg == 'euro':
# Generate euro
else:
raise ValueError(f'Unrecognised option {arg}, must be "lotto" or "euro".')
print('Die Text Datei wurde erfolgreich erstellt.')
So that if the program is run as:
python my_lotto.py euro
The code will just generate euro lotto, if run as:
python my_lotto.py
Will generate both, etc.
Other arguments might be used to specify the filename to write to or other features, if they start getting complex, however, it may be useful to use tools such as argparse or click.
Summary
Just to give a rough idea of what it might look like keeping some of your structure and sketching out a few of the ideas:
"""
Generate lotto or euro lottery numbers and write to a file.
Call as:
$ python lotto.py
Generate both sets of numbers and print to screen
$ python lotto.py my_file
Generate both sets of numbers and write to 'my_file'
$ python lotto.py euro
Just generate euro numbers and print to screen
$ python lotto.py my_file lotto
Just generate lotto numbers and write to 'my_file'
$ python lotto.py lotto euro
Equivalent to no args
"""
import random
from datetime import datetime
def generate_euro_numbers():
""" Generate numbers fitting the euro lottery draw """
main_numbers = range(1, 50 + 1)
super_numbers = range(1, 12 + 1)
random_main_numbers = sorted(random.sample(main_numbers, 5))
random_super_numbers = sorted(random.sample(super_numbers, 2))
return random_main_numbers, random_super_numbers | {
"domain": "codereview.stackexchange",
"id": 43851,
"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, random, io",
"url": null
} |
python, performance, random, io
def generate_lotto_numbers():
""" Generate numbers fitting the 6aus49 lottery draw """
main_numbers = range(1, 49 + 1)
random_main_numbers_lotto = sorted(random.sample(main_numbers, 6))
return random_main_numbers_lotto
def generate_lotto_string(lotto=None, euro=None):
""" Constructs standard string form for lotto and euro numbers
lotto: List of lotto numbers
euro: Tuple of two lists of euro and super numbers
"""
if not lotto and not euro:
return ''
lotto_name = 'Lotto 6aus49'
euro_name_1 = 'Eurojackpot Zahlen'
euro_name_2 = 'Eurojackpot Eurozahlen'
date = datetime.now()
date_format = date.strftime('%d-%m-%Y %H:%M:%S')
coder = 'mr.enso'
def to_str_list(arg):
"""
Convert list to comma separated string
"""
return ", ".join(map(str, arg))
out_string = ''
if lotto:
out_string += f'{lotto_name}: {to_str_list(lotto)}\n'
if euro:
out_string += f'{euro_name_1}: {to_str_list(euro[0])}\n'
out_string += f'{euro_name_2}: {to_str_list(euro[1])}\n'
out_string += f'\nGeneriert am: {date_format} by {coder}'
return out_string
def output_numbers(filename=None, lotto=None, euro=None):
"""
Output lotto and euro numbers either to screen (if no filename) or to filename if provided
"""
if not filename:
print(generate_lotto_string(lotto, euro))
else:
with open(filename, 'w+') as out_file:
out_file.writelines(generate_lotto_string(lotto, euro))
if __name__ == '__main__':
import sys
LOTTO, EURO = None, None
# Default to printing to screen
OUT_FILE = None
# Naively assume arg 1 is filename (arg[0] is the filename)
if len(sys.argv) > 1 and sys.argv[1] not in ('lotto', 'euro'):
OUT_FILE = sys.argv.pop(1) # Set OUT_FILE to user filename and remove from argument list | {
"domain": "codereview.stackexchange",
"id": 43851,
"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, random, io",
"url": null
} |
python, performance, random, io
if len(sys.argv) == 1: # Called without other arguments
LOTTO = generate_lotto_numbers()
EURO = generate_euro_numbers()
else:
for arg in sys.argv[1:]:
arg = arg.lower()
if arg == 'lotto':
LOTTO = generate_lotto_numbers()
elif arg == 'euro':
EURO = generate_euro_numbers()
else:
raise ValueError(f'Unrecognised option {arg}, must be "lotto" or "euro".')
output_numbers(OUT_FILE, lotto=LOTTO, euro=EURO)
print('\nDie Text Datei wurde erfolgreich erstellt.') | {
"domain": "codereview.stackexchange",
"id": 43851,
"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, random, io",
"url": null
} |
python, python-3.x, csv
Title: Transform dict of lists to CSV
Question: I want to transform this dict to CSV:
{
"California": ["San Fransisco", "Los Angeles","Oakland"],
"Texas": ["Dallas", "Houston", "Austin"],
"Florida": ["Miami", "Tampa"],
...
}
I want the following output:
California,San Fransisco
California,Los Angeles
California,Oakland
Texas,Dallas
Texas,Houston
Texas,Austin
Florida,Miami
Florida,Tampa
I wrote this code. This works well, but I wonder if there is a more pythonic way to do the same.
import csv
d = {
"California": ["San Fransisco", "Los Angeles","Oakland"],
"Texas": ["Dallas", "Houston", "Austin"],
"Florida": ["Miami", "Tampa"]
}
with open("./out.csv", "w") as f:
header = ["state", "city"]
writer = csv.writer(f)
writer.writerow(header)
for i in d.keys():
for j in d[i]:
writer.writerow([i,j])
Answer: As per PEP 8, the standard indentation for Python code is 4 spaces. Since whitespace is significant in Python, this is a pretty strong convention that you should follow.
The code itself isn't bad, but you could make it a bit more elegant using itertools.product() and csvwriter.writerows(). You can also use more meaningful variable names than i and j.
import itertools
with open("./out.csv", "w") as f:
writer = csv.writer(f)
writer.writerow(["state", "city"])
for state, cities in d.items():
writer.writerows(itertools.product([state], cities)) | {
"domain": "codereview.stackexchange",
"id": 43852,
"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, csv",
"url": null
} |
python, pandas
Title: Cleaning Float Column of Longitude
Question: I am cleaning a dataset where columns lat and long are presenting some values multiplied by 10. Not only 10, but changing 10^n. I wrote the code below. I am not sure if it is the best way, but is working. May you help me?
I will put this code inside a function, so do not bother you creating a function at all. I just need other opinions on how to deal with this task.
import pandas as pd
import numpy as np
accidents = pd.DataFrame([0, -5197, -5114758, np.NaN, -512281, -51.116024, -51.213559, -51.227893], columns=['longitude'])
def clean_geo(df_raw: pd.DataFrame, col: str, coord: int) -> pd.Series:
"""This function will fill values that a geopoint
with NaN and transform the remaning. It is designer to
coordenates with 2 digits before dot."""
temp = df_raw[col].copy()
mask = temp.astype("str").str[0:2] != str(coord)[:2] # Picking number outside the coordenate
temp[mask] = np.NaN
temp2 = temp[~mask].astype("str").str[:3] + "." + temp[~mask].astype("str").str[4:-2]
temp[~mask] = temp2.astype("float")
return temp
accidents["longitude"] = clean_geo(accidents, "longitude", -51)
accidents["longitude"].describe()
I tried to write something with apply and lambda, but I failed and I am not sure if it is good choice, considering that on my way I use the vectoring/forecasting power of pandas/numpy.
Answer: The doc-comment doesn't really tell me what this function is doing. Some of that is grammar and spelling, but it's absolutely unclear what kind of "transform" it's doing. And while we can guess what the first two arguments mean from their names, the last is utterly opaque.
I think this is what the code does:
"""
Return a copy of column COL from DF_RAW modified as follows:
For each value, if it can be divided by an exact power of
ten to make it fall between COORD and COORD+1, then do so,
else replace with NaN.
""" | {
"domain": "codereview.stackexchange",
"id": 43853,
"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, pandas",
"url": null
} |
python, pandas
That already exposes one problem with the approach: it won't work for regions which straddle a 1-degree meridian line. We'll have to invoke the function twice (or more) for such areas. (Actually, we'll have to combine the two results, rather than just applying the function sequentially.)
I think the approach is flawed: instead of working with strings, we should be looking at the numeric values, and provide a range of longitudes considered valid.
Sticking with the string approach for the moment, we have some assumptions built in. When I tried passing -5.122, I got an exception. That's because the test != str(coord)[:2] is inconsistent with the assumption made in the rest of the function that coord has three characters. We should be measuring its actual length and using that.
With the code shown, I got corruption of the transformed values:
original cleaned
0 0.0 NaN
1 -5197.0 -51.7
2 -5114758.0 -51.4758
3 nan NaN
4 -512281.0 -51.281
5 -51.116024 -51.1160
6 -51.213559 -51.2135
7 -51.227893 -51.2278
8 -5.122 NaN
Notice the missing 9 in row 1, and the missing 1 in row 2, etc. We're replacing a digit with ., instead of inserting.
We should be using a main-guard for the code outside of the function, to make this importable as a module.
The describe() result is unused, so we should either print it or remove it.
Modified code
import pandas as pd
import numpy as np
accidents = pd.DataFrame([0, -5197, -5114758, np.NaN, -512281,
-51.116024, -51.213559, -51.227893, -5.122],
columns=['longitude'])
def clean_geo(series: pd.Series, coord: int) -> pd.Series:
"""
Return a copy of SERIES with each element modified by inserting a
decimal point if necessary to make its integer part be COORD, or
replaced with NaN if that is not possible.
"""
longitudes = series.copy()
i_len = len(str(coord)) # length of integer part | {
"domain": "codereview.stackexchange",
"id": 43853,
"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, pandas",
"url": null
} |
python, pandas
i_len = len(str(coord)) # length of integer part
mask = longitudes.astype("str").str[:i_len] != str(coord)
longitudes[mask] = np.NaN
strings = longitudes[~mask].astype("str")
strings = (strings.str[:i_len] + "." +
strings.str[i_len:].str.replace('.', '', regex=False))
longitudes[~mask] = strings.astype("float")
return longitudes
if __name__ == '__main__':
accidents["longitude"] = clean_geo(accidents["longitude"], -51)
print(accidents)
print(accidents["longitude"].describe()) | {
"domain": "codereview.stackexchange",
"id": 43853,
"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, pandas",
"url": null
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.