text stringlengths 1 2.12k | source dict |
|---|---|
javascript, authentication, promise, firebase, react-native
export const setNavigator = (nav) => {
navigator = nav;
};
export const navigate = (routeName, params) => {
navigator.dispatch(
CommonActions.navigate({
name: routeName,
params,
})
);
};
Answer: Review
Overall the code looks decent. It seems the code is separated into components well, and indentation is consistent. It makes good usage of hooks, and const for values that are never re-assigned. There is at least one place where let is used and const could be used instead - that is in src/context/createDataContext.js the for loop within the Provider definition.
Most of the functions are succinct though there are a couple that are a bit on the long side - e.g. in src/context/DataContext.js the function signin occupies 30 lines, signup is 38 lines, etc. Some of those have repeated code - e.g. in the catch callbacks so abstracting common code to a separate function would help make those shorter and also eliminate the number of places code needs to be updated if something happens to change (e.g. in a dependent library).
Suggestions
Documentation
Documenting the code
While most of the code is self-documenting, it might help anyone reading the code (including your future self) to have comments above each function - e.g. documenting the parameters, return values, any possible exceptions that may be thrown, etc.
A common convention is to include a Readme file in markdown format in the root of the project. This can include information about installation/setup, testing, etc. While initializeApp is documented on the firebase Docs it would be helpful to know which configuration options are required, optional, etc. For example - I saw the following in /firebase/firebaseConfig.js:
const firebaseConfig = {
// Removed code
}; | {
"domain": "codereview.stackexchange",
"id": 43051,
"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, authentication, promise, firebase, react-native",
"url": null
} |
javascript, authentication, promise, firebase, react-native
const firebaseConfig = {
// Removed code
};
and I had to figure out what was needed instead of Removed code.
Use a linter
Unless you are already using a linter, I suggesting finding one like ESLint. I have it enabled in my IDE (i.e. PHPStorm) and it can typically be added as an extension in many other popular IDEs. There is also a Demo available on the website where code can be pasted to see what types of suggestions are offered. Some of the suggestions below came from ESLint messages.
Unused variables
Perhaps this is leftover boiler-plate code in many cases, but some variables are assigned but never used after that. For example:
const styles = StyleSheet.create({});
This appears five times within the code pasted above. There is no need to assign those variables if they aren't used, and perhaps there may be no need to create an empty stylehseet object.
Eliminating single use variables
In src/screens/LoginScreen.js there is a variable unsubscribe declared within the callback to useEffect within LoginScren, which is returned immediately after it is assigned.
useEffect(() => {
const unsubscribe = navigation.addListener("focus", () => {
clearErrorMessage();
});
return unsubscribe;
}, [navigation]);
There is little point in assigning this variable. It can be simplified to simply returning the return value from the call to addListener.
useEffect(() => {
return navigation.addListener("focus", () => {
clearErrorMessage();
});
}, [navigation]);
The same is true in src/screens/SignupScreen.js.
In src/context/DataContext.js object destructuring could be used to eliminate single-use variables - e.g. in the first promise callback following signInWithEmailAndPassword()
.then((userCredential) => {
// Signed in
const user = userCredential.user;
dispatch({ type: "signin", payload: user });
navigate("Index");
}) | {
"domain": "codereview.stackexchange",
"id": 43051,
"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, authentication, promise, firebase, react-native",
"url": null
} |
javascript, authentication, promise, firebase, react-native
The parameter userCredential could be destructured like this to eliminate const user = userCredential.user;:
.then(({ user }) => {
// Signed in
dispatch({ type: "signin", payload: user });
navigate("Index");
})
Similarly in the catch callback
.catch((error) => {
const errorCode = error.code;
console.log(errorCode);
if (errorCode === "auth/wrong-password") {
dispatch({
type: "add_error",
payload: "Incorrect Password",
});
} else if (errorCode === "auth/invalid-email") {
dispatch({
type: "add_error",
payload: "Invalid Email",
});
} else {
dispatch({
type: "add_error",
payload: error.code,
});
}
The object returned to the call to dispatch() could be pulled out since the only thing that changes is the payload:
.catch(({ code. }) => {
let payload = code;
if (code === "auth/wrong-password") {
payload = "Incorrect Password";
} else if (code === "auth/invalid-email") {
payload = "Invalid email";
}
dispatch({
type: "add_error",
payload,
});
}
Simplifying promises
Also in In src/context/DataContext.js the signup function uses traditional promise format, yet the callback to createUserWithEmailAndPassword() uses async / await. While it isn't really the case that it is an example of callbackhell not use async / await to simplify the code? For example, the signup method could be simplified from:
const signup =
(dispatch) =>
({ email, password }) => {
createUserWithEmailAndPassword(auth, email, password)
.then(async (userCredential) => {
// Signed in
const user = userCredential.user;
await addDoc(collection(db, "users"), {
worked: true,
}); | {
"domain": "codereview.stackexchange",
"id": 43051,
"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, authentication, promise, firebase, react-native",
"url": null
} |
javascript, authentication, promise, firebase, react-native
await addDoc(collection(db, "users"), {
worked: true,
});
dispatch({ type: "signup", payload: user });
})
.catch((error) => {
const code = error.code;
if (code === "auth/email-already-in-use") {
dispatch({
type: "add_error",
payload: "Email already in use",
});
} else if (code === "auth/invalid-email") {
dispatch({
type: "add_error",
payload: "Invalid email",
});
} else if (code === "auth/weak-password") {
dispatch({
type: "add_error",
payload: "Weak password",
});
} else {
dispatch({
type: "add_error",
payload: error.code,
});
}
});
};
To the following, using try .. catch (as well as simplifying the catch callback with suggestions from above:
const signup =
(dispatch) =>
async ({ email, password }) => {
console.log('signing up ', email);
try {
const userCredential = await createUserWithEmailAndPassword(auth, email, password)
// Signed in
const user = userCredential.user;
await addDoc(collection(db, "users"), {
worked: true,
});
dispatch({ type: "signup", payload: user });
}
catch({ code }) {
let payload = code;
if (code === "auth/email-already-in-use") {
payload = "Email already in use";
} else if (code === "auth/invalid-email") {
payload = "Invalid email";
} else if (code === "auth/weak-password") {
payload = "Weak password";
}
dispatch({
type: "add_error",
payload,
});
}
};
Looping with for...in
In src/context/createDataContext.js the Provider definition has a for...in loop.
const boundActions = {};
for (let key in actions) {
boundActions[key] = actions[key](dispatch);
} | {
"domain": "codereview.stackexchange",
"id": 43051,
"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, authentication, promise, firebase, react-native",
"url": null
} |
javascript, authentication, promise, firebase, react-native
const boundActions = {};
for (let key in actions) {
boundActions[key] = actions[key](dispatch);
}
While it works, MDN considers for...in deprecated and recommends using for...of instead. The method Object.entries() could be used in conjunction with a for...of loop:
const boundActions = {};
for (const [key, action] of Object.entries(actions)) {
boundActions[key] = action(dispatch);
}
Avoid excess wrapper functions
There are a couple places where a listener is bound to the focus event, and a callback simply calls clearErrorMessage().
const unsubscribe = navigation.addListener("focus", () => {
clearErrorMessage();
});
As long as the callback isn't passed arguments that the function is not expecting, then the extra lambda/anonymous function can be removed:
const unsubscribe = navigation.addListener("focus", clearErrorMessage); | {
"domain": "codereview.stackexchange",
"id": 43051,
"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, authentication, promise, firebase, react-native",
"url": null
} |
python, python-3.x, algorithm, programming-challenge, linked-list
Title: LFU Cache implementation in Python 3
Question: Need some feedback on this implementation of LFU cache in python3.
Original problem : https://leetcode.com/problems/lfu-cache/
Would really appreciate some feedback on readability, understandability and areas of improvement.
""" ListNode class to create new nodes objects
@variables: key - Key from key,value pair stored by node
value - Value from key,value pair stored by node
next - Link to next ListNode object of doubly linked list
prev - Link to previous ListNode object of doubly linked list
frequency - Holds the number of times this node was accessed
in LFUCache.get() and LFUCache.put() methods.
Default is 1 at node creation on LFUCache.put() call
"""
class ListNode:
def __init__(self, key=0, val=0, next=None, prev=None):
self.key = key
self.val = val
self.next = next
self.prev = prev
self.frequency = 1
""" Main class to create LFU cache.
The idea is to maintain cache linked list in order of frequency and LRU within same frequency
A hash map (self.hash_map) will hold node key as key and pointer to node as value. Another hash map
will hold distinct node frequencies as key and pointer to head node for the frequency. | {
"domain": "codereview.stackexchange",
"id": 43052,
"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, programming-challenge, linked-list",
"url": null
} |
python, python-3.x, algorithm, programming-challenge, linked-list
______ ______ ______ ______ ______
| | | | | |
hash_map | 23 | 56 | 14 | 6 | 19 |
|______|______|______|______|______|
| | | | |
_____________| ____| | |_____ |_______________
/ / | \ \
_______ ___V___ ____V__ __V____ _V_____ ___V___ _______
| | <--- | | <--- | | <--- | | <--- | | <--- | | <--- | |
LFUCache | Head | | 23(5) | | 56(3) | | 14(2) | | 6(2) | | 19(1) | | Tail |
|_______| ---> |_______| ---> |_______| ---> |_______| ---> |_______| ---> |_______| ---> |_______|
^ ^ ^ ^
\ \______ | /
\______________ \ | _____________________/
_\___ __\__ __|__ __/__
| | | | |
freq_map | 5 | 3 | 2 | 1 |
|_____|_____|_____|_____|
"""
class LFUCache: | {
"domain": "codereview.stackexchange",
"id": 43052,
"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, programming-challenge, linked-list",
"url": null
} |
python, python-3.x, algorithm, programming-challenge, linked-list
def __init__(self, capacity: int):
self.capacity = capacity
self.hash_map = {} # Hash map to hold cache keys as key and link to node as value
self.freq_map = {} # Hash map to hold frequency as key and link to head node for that frequency
# Dummy head and tail cache nodes to make opertions on edge cases(one node and two node cache) simple
self.head = ListNode(0,0)
self.tail = ListNode(0,0)
# Initially set tail (dummy node) as head node for frequency 1
# so that first cache node is added before tail node
self.freq_map[1] = self.tail
# Link head cache node and tail cache nodes together
self.head.next,self.tail.prev = self.tail,self.head
""" This method will get the value of key (input) if it exists
in the LFU cache else returns -1. If key exists then this method
will call self._move() to move the node to front of it's new
frequency queue
"""
def get(self, key: int) -> int:
if self.hash_map.get(key):
# Key exists, get link to node from hash map
node = self.hash_map.get(key)
# Since frequency changed, move this node to
# front of new frequency queue
self._move(node)
return node.val
else:
return -1 | {
"domain": "codereview.stackexchange",
"id": 43052,
"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, programming-challenge, linked-list",
"url": null
} |
python, python-3.x, algorithm, programming-challenge, linked-list
""" This method will update the value of key (input) if it exists
in the LFU cache else inserts new node into the appropriate position
on LFU cache
"""
def put(self, key: int, value: int) -> None:
# Handle edge case when capacity is 0
if self.capacity == 0:
return
if self.hash_map.get(key):
# Key exists, get link to node from hash map
self.hash_map.get(key).val = value
# Move this node to front of new frequency queue
self._move(self.hash_map.get(key))
else:
# Key does not exist, need to create a new node. Check if capcaity is full
if len(self.hash_map) == self.capacity:
# If node to be removed is the head node for it's frequency then remove it from frequency map
# If frequency of node to be removed is 1 then we need to reset head node for frequency 1 to tail node
if self.freq_map.get(self.tail.prev.frequency) == self.tail.prev and self.tail.prev.frequency == 1:
self.freq_map[1] = self.tail
elif self.freq_map.get(self.tail.prev.frequency) == self.tail.prev:
self.freq_map.pop(self.tail.prev.frequency)
# Remove last node (tail.prev) from the cache list
self._remove(self.tail.prev)
# Create new node and
# - Add it to cache list
# - Set it as head node for frequency 1
node = ListNode(key,value)
head = self.freq_map.get(1)
self.freq_map[1] = node
self._add(node, head)
""" This method will add a new node(input) before the head(input) node
on LFU cache
"""
def _add(self, node :ListNode, head :ListNode) -> None:
# When adding in the middle of cache we don't have dummy head node
# so we set head.prev to play as dummy head node | {
"domain": "codereview.stackexchange",
"id": 43052,
"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, programming-challenge, linked-list",
"url": null
} |
python, python-3.x, algorithm, programming-challenge, linked-list
# so we set head.prev to play as dummy head node
if head != self.head:
head = head.prev
# Add node operation
node.next = head.next
head.next.prev = node
head.next = node
node.prev = head
self.hash_map[node.key] = node | {
"domain": "codereview.stackexchange",
"id": 43052,
"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, programming-challenge, linked-list",
"url": null
} |
python, python-3.x, algorithm, programming-challenge, linked-list
""" This method will remove a node(input) from LFU cache and hash_map
"""
def _remove(self, node :ListNode) -> None:
node.prev.next = node.next
node.next.prev = node.prev
node.next = None
node.prev = None
self.hash_map.pop(node.key)
def _move(self, node :ListNode) -> None:
new_frequency = node.frequency + 1
# We need to find head node, before which we need to place the input node
# If new frequency already exists in the cache list then get the head node for that frequency
# else if new frequency does not exist then node will remain at same place in cache so set head as node.next
# else get the head node for current frequency of input node
if self.freq_map.get(new_frequency):
head = self.freq_map.get(new_frequency)
elif self.freq_map.get(node.frequency) == node:
head = node.next
else:
head = self.freq_map.get(node.frequency)
# Set new head nodes for current frequency of input node
if self.freq_map.get(node.frequency) == node and node.frequency == node.next.frequency:
self.freq_map[node.frequency] = node.next
elif self.freq_map.get(node.frequency) == node:
self.freq_map.pop(node.frequency)
self._remove(node)
self._add(node,head)
node.frequency = new_frequency
# Set this node as head node for new frequency (current frequency + 1)
self.freq_map[new_frequency] = node | {
"domain": "codereview.stackexchange",
"id": 43052,
"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, programming-challenge, linked-list",
"url": null
} |
python, python-3.x, algorithm, programming-challenge, linked-list
Answer: PEP8 compliance
Whitespace
Use spaces after commas in parameter lists on function calls:
ListNode(0, 0) vs. ListNode(0,0)
Also colons in type hints should have a space after them, but not before:
node: ListNode vs. node :ListNode.
But the real issue here is your inconsistency of placing whitespace, since you do it according to PEP8 in other places: self._add(node, head), key: int.
Docstrings
Docstrings belong right below the definition they are intended to document:
class Foo:
"""Docstring documenting class Foo."""
...
def bar(self):
"""Docstring documenting method bar."""
...
vs.
"""Not a docstring."""
class Foo:
...
"""Not a docstring either."""
def bar(self):
...
Use return-early and inverted-testing
Consider this:
def get(self, key: int) -> int:
if not self.hash_map.get(key):
return -1
node = self.hash_map.get(key)
self._move(node)
return node.val
vs. this:
def get(self, key: int) -> int:
if self.hash_map.get(key):
# Key exists, get link to node from hash map
node = self.hash_map.get(key)
# Since frequency changed, move this node to
# front of new frequency queue
self._move(node)
return node.val
else:
return -1
This may even be a good use case for the walrus operator:
def get(self, key: int) -> int:
if not (node := self.hash_map.get(key)):
return -1
self._move(node)
return node.val
Divide an conquer
Currently some of your class' methods are rather long. You should try to split them into smaller methods, each dealing with a particular part of a problem. An example would be put():
def put(self, key: int, value: int) -> None:
# Handle edge case when capacity is 0
if self.capacity == 0:
return
if not self.hash_map.get(key):
return self._put_new(key, value)
self.hash_map.get(key).val = value
self._move(self.hash_map.get(key)) | {
"domain": "codereview.stackexchange",
"id": 43052,
"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, programming-challenge, linked-list",
"url": null
} |
python, python-3.x, algorithm, programming-challenge, linked-list
def _put_new(self, key: int, value: int) -> None:
"""Add a non-existant key to the map."""
if len(self.hash_map) == self.capacity:
# If node to be removed is the head node for it's frequency then remove it from frequency map
# If frequency of node to be removed is 1 then we need to reset head node for frequency 1 to tail node
if self.freq_map.get(self.tail.prev.frequency) == self.tail.prev and self.tail.prev.frequency == 1:
self.freq_map[1] = self.tail
elif self.freq_map.get(self.tail.prev.frequency) == self.tail.prev:
self.freq_map.pop(self.tail.prev.frequency)
# Remove last node (tail.prev) from the cache list
self._remove(self.tail.prev)
# Create new node and
# - Add it to cache list
# - Set it as head node for frequency 1
node = ListNode(key,value)
head = self.freq_map.get(1)
self.freq_map[1] = node
self._add(node, head) | {
"domain": "codereview.stackexchange",
"id": 43052,
"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, programming-challenge, linked-list",
"url": null
} |
c#, beginner, console
Title: Calculate the average score of students
Question: Problem :
Imagine you are a developer and get a job in which you need to create a program for a teacher. He needs a program written in c# that calculates the average score of his students. So he wants to be able to enter each score individually and then get the final average score once he enters -1.
So the tool should check if the entry is a number and should add that to the sum. Finally once he is done entering scores, the program should write onto the console what the average score is.
The numbers entered should only be between 0 and 20. Make sure the program doesn't crash if the teacher enters an incorrect value.
Test your program thoroughly.
My solution :
static void Main(string[] args)
{
int digit = 0,sum=0,counter=0;
string x;
try
{
for (int i = 0; i <= counter; i++)
{
Console.WriteLine("Please Enter Score");
x = Console.ReadLine();
bool isParsable = Int32.TryParse(x,out digit); | {
"domain": "codereview.stackexchange",
"id": 43053,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, beginner, console",
"url": null
} |
c#, beginner, console
if (isParsable)
{
if (digit >= 0 && digit <= 20)
{
Console.WriteLine("Valid Number");
sum += digit;
counter++;
Console.WriteLine($"Student number {counter} got {digit}");
}
else if (digit == -1)
{
Console.WriteLine($"Total sum is {sum}");
Console.WriteLine($"Total number of students is {counter}");
Console.WriteLine($"Average score of {counter} students is{sum/counter}");
break;
}
else
{
Console.WriteLine("Please enter a valid score");
}
}
Console.WriteLine("Please enter Numerical Values only");
}
}
catch (DivideByZeroException)
{
Console.WriteLine("Unable to get results");
}
}
```
Answer: General comments on your code
"Unable to get results" is a very vague message that does not meaningfully inform the user. Make the message more meaningful, e.g. "No scores entered, cannot calculate average".
Note that in the next section I get into avoiding the division-by-zero in its entirety.
for (int i = 0; i <= counter; i++) is a very confusing way to have your application end after you've printed the results. It works (because printing the results does not increment the counter, making it so i now breaks the condition), but it's not very readable.
Overall, your code is neatly readable line by line, but it lacks a bit of abstraction which makes the flow of the overall application harder to read. I address this in the next section, step by step. | {
"domain": "codereview.stackexchange",
"id": 43053,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, beginner, console",
"url": null
} |
c#, beginner, console
$"Student number {counter} got {digit}" is redundant. The user still sees the data they entered into the console, so there's no need repeating the same information on the line below it.
"Please enter a valid score" is needlessly vague. Tell the user which validation rule they failed to comply with. Otherwise it's just a guessing game.
isParsable is a technically correct name, but something like isNumeric conveys the meaning better. For readability's sake, avoid technical terms and stick to the meaning of the value rather than how you obtained it.
Pedantic niggle: digit is not the right name for your variable. A digit is to a number what a letter is to a word. The number 12 has two digits, but it represents a single numerical value. number would have been a better variable name. Or, keeping in line with the earlier advice, score would have been a contextually appropriate name here as that is what the value represents.
There's no need to declare string x; outside of the for loop. It's better to just keep it locally scoped. While the impact of doing so is tiny here, this is one of those readability straws that will eventually break a camel's back in a real life codebase. | {
"domain": "codereview.stackexchange",
"id": 43053,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, beginner, console",
"url": null
} |
c#, beginner, console
Refactoring the code
You've written your code as a single method, which is impacting its readability. If you now need to change your flow (e.g. because of changing requirements), it requires you to pull it all apart to find the thing you need to change. That may seem simple when you've just written the code and know it by heart, but this will become significantly harder for other developers, or after you've not looked at this code for a while. While this is a short snippet; this gets more difficult for real-life-size codebases.
Separate your logic into specific behaviors that you need your application to have. This is just an overview of what you expect your application to do. This helps you with separating these concerns and developing them separately.
Without delving into the specific method implementations, this already gives you a really neat top level algorithm that makes it clear at a glance what to expect from your application:
static void Main(string[] args)
{
var scores = GetScores();
var average = CalculateAverage(scores);
Print(average);
}
Some comments:
I prefer storing the numbers, not just the sum and counter. This is under the assumption of the current context: a classroom teacher will not have anywhere near an amount of scores to calculate that storing all the values will be problematic.
The benefit is that you can print the input values later on, which may be nice for UX purposes, e.g. to print a full report.
If you do need to conserve memory to that extent (if there is a concrete reason to do so), feel free to revert to the sum/counter storage mechanic (but beware of integer overflow if you're going to be dealing with such a large amount of values).
Now we can implement the missing methods, which helps us focus on keeping each method simple and bite-sized.
public const int ExitCode = -1;
public IEnumerable<int> GetScores()
{
var scores = new List<int>();
do {
var score = GetScore(); | {
"domain": "codereview.stackexchange",
"id": 43053,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, beginner, console",
"url": null
} |
c#, beginner, console
if(score == ExitCode)
return scores;
scores.Add(score);
} while(true);
}
Some comments:
I used a const ExitCode to avoid magic numbers in code. This makes it clear that the value has a predetermined meaning.
I used while(true) because the return ensures that we exit the loop when the right exit condition is met. Generally avoid while(true), but in this case it simplifies the syntax and is therefore acceptable.
public const int ScoreMinValue = 0;
public const int ScoreMaxValue = 20;
public static int GetScore()
{
do {
Console.Write("Input a score: ");
var input = Console.ReadLine();
bool inputIsNumerical = Int32.TryParse(input, out number);
if(!inputIsNumerical)
{
Console.WriteLine("Input must be numerical");
continue;
}
if(number != ExitCode && (number < ScoreMinValue || score > ScoreMaxValue))
{
Console.WriteLine($"Score must range from {ScoreMinValue} to {ScoreMaxValue}");
continue;
}
return number;
} while(true);
}
Some comments:
Similar as before, I used a while(true) here because the continue and return keywords already handle the flow. Always be aware that you're not introducing any neverending loops when resorting to while(true).
I used inputIsNumerical as an intermediary step instead of putting if(!Int32.TryParse(input, out number)). This would also work, but the extra step increases readability.
The range limits have been made into constants to avoid magic numbers, promote reuse, and increase readability.
public double CalculateAverage(IEnumerable<int> values)
{
// LINQ already has an averaging method
if(!values.Any())
return 0;
return values.Average();
// If you want to do it yourself:
int counter = 0;
double sum = 0;
foreach(var value in values)
{
counter++;
sum += value;
} | {
"domain": "codereview.stackexchange",
"id": 43053,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, beginner, console",
"url": null
} |
c#, beginner, console
foreach(var value in values)
{
counter++;
sum += value;
}
if(counter == 0)
return 0;
var average = sum / value;
return average;
}
Some comments:
If you use LINQ, there's already an averaging method. No use reinventing the wheel. However, reinventing the wheel makes sense for educational purposes, so I also added a manual way of calculating the same thing.
I avoided int division by making sum a double. This bypasses the need for explicit casting later on.
Exceptions are useful at times, but better avoided when it is possible to handle things more elegantly. In this case, I find it better to simply return 0 when trying to average a list with no values.
I leave the implementation of the Print method to you. It's really just a matter of writing to the console what you want to write. Change the input parameters as you see fit, e.g. if you also want to print all the scores that were given. | {
"domain": "codereview.stackexchange",
"id": 43053,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, beginner, console",
"url": null
} |
c#, .net
Title: Multiple if statements in a single method to enable/disable feature
Question: I am sure this is not ideal code, basically I am checking a condition at a time and exiting if any of them are true. This will then disable refund functionality.
public bool ShouldChangeBookingBeDisabled(bool isLoggedIn, bool hasRefundedBookingsAtCinema, VistaBooking booking, SitecoreCinema cinema, ODataAttribute experience)
{
if (hasRefundedBookingsAtCinema || !isLoggedIn) return true;
if (booking.Payments.Any(x => x.CardType != VALID_PAYMENT_TYPE)) return true;
if (BookingHasVouchers(booking)) return true;
if (booking.LoyaltyPointsCost != null && booking.LoyaltyPointsCost.Any(x => x.Points > 0)) return true;
if (DateTime.Now > booking.Tickets[0].SessionDateTimeOffset.AddHours(-cinema.Settings.ChangeBookingGracePeriod)) return true;
if (experience == null) return false;
bool isValidAttribute = cinema.Settings.ChangeBookingExperienceFilter.Any(x => x.VistaAttributeCode == experience.ShortName);
return !isValidAttribute;
}
Answer: Rather than having a lots of if - return statements you can separate the two.
You can define a collection of conditions:
var conditions = new Func<bool>[]
{
() => hasRefundedBookingsAtCinema || !isLoggedIn,
() => booking.Payments.Any(x => x.CardType != VALID_PAYMENT_TYPE),
() => BookingHasVouchers(booking),
() => booking.LoyaltyPointsCost != null && booking.LoyaltyPointsCost.Any(x => x.Points > 0),
() => DateTime.Now > booking.Tickets[0].SessionDateTimeOffset.AddHours(-cinema.Settings.ChangeBookingGracePeriod)
};
Since we have defined them as functions that's why they can be lazily evaluated
For example: Evaluate the first, if it false then evaluate the second and so ...
foreach (var condition in conditions)
{
if (condition()) return true;
} | {
"domain": "codereview.stackexchange",
"id": 43054,
"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#, .net",
"url": null
} |
c#, .net
foreach (var condition in conditions)
{
if (condition()) return true;
}
The last two statements of your original implementation can be combined into a single while using the conditional operator:
return experience != null ?
!cinema.Settings.ChangeBookingExperienceFilter.Any(x => x.VistaAttributeCode == experience.ShortName)
: false; | {
"domain": "codereview.stackexchange",
"id": 43054,
"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#, .net",
"url": null
} |
python, combinatorics
Title: Given a number of points, generates all paths between all points that does not overlap
Question: I wrote this code in 4 days, I want to see if I can optimize this code some more, and have some suggestion on what can I improve.
This code takes in any number of points then naming them alphabetically, when the points exceeds 26 the letters will repeat themselves AA BB CC, AAA, BBB, CCC, etc., then through combinations getting all paths between these points.
['A B', 'A C', 'A D', 'A E', 'B C', 'B D', 'B E', 'C D', 'C E', 'D E']
# This is only 5 points
The code:
class Distance:
def __init__(self):
pass
def possiblePathsGeneration(self, numOfPoints = 5):
flag = False
alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
accumulator = 0
terminateNum = 0
paths = []
points = []
temporaryStorage = ""
flag2 = 0
self.numOfPoints = numOfPoints
if self.numOfPoints > 26: # To see if it exceeds the alphabet
points = list(alphabet[:26]) # filling in the list with existing alphabet
for x in range(2, ((self.numOfPoints - 1) // 26) + 2): # How many times the letter will repeat itself (You will see in the output what i mean)
for y in alphabet[:26]: # repeats over the alphabet
if flag2 == 1: # Prevents another whole alphabet generating
break | {
"domain": "codereview.stackexchange",
"id": 43055,
"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, combinatorics",
"url": null
} |
python, combinatorics
if self.numOfPoints % 26 > 0 and (self.numOfPoints - 26) // 26 < 1: # To see if it has any spare letters that does not form a full alphabet
terminateNum = self.numOfPoints % 26 # calculates how many spare letters are left out and sets it as a termination number for later
flag = True # Sets a flag which makes one of the if statments false which allows execution of later programs
else:
terminateNum = (self.numOfPoints - 26) // 26 # Getting the times that the alphabet has to iterate through
if flag == True and self.numOfPoints % 26 > 0 & (self.numOfPoints - 26) // 26 < 1: # To see if we have a whole alphabet
break
if accumulator >= terminateNum: # Determines when to leave the loop
break
points.append(y * x) # Outputs point
accumulator += 1
if flag != True & accumulator != terminateNum | accumulator <= terminateNum: # Determines if we have more whole alphabets
continue
terminateNum = self.numOfPoints % 26 # Resets number of letters to generate
for y in alphabet[:terminateNum]: # outputs the spares
flag2 += 1
if flag2 == 1 and not(self.numOfPoints < 52): # prevents generation of extra letters
break
points.append(y * x)
else:
points = list(alphabet[:self.numOfPoints])
temporaryPoints = [x for x in points]
for x in points:
for y in temporaryPoints[1:]:
paths.append(x + " " + y)
temporaryStorage = x + " " + y
yield temporaryStorage
temporaryPoints.pop(0) | {
"domain": "codereview.stackexchange",
"id": 43055,
"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, combinatorics",
"url": null
} |
python, combinatorics
distance = Distance()
print([x for x in distance.possiblePathsGeneration()])
I have tested this code a few times, it doesn't have any bugs that I know of.
The reason I use classes is that this is a part of the actual code, and using classes is convenient for later when I want to do some calculations.
Answer:
Strings
instead of inserting strings, you should use the python library.
import string
alphabet = string.ascii_uppercase
print(alphabet)
this will reduce the likely hood of typos.
Naming
One thing I would consider is your naming objects. For instance, you name the class Distance, yet I don't see anything related to a measurement between two points. This could possibly be only part of the code, and you will have a measurement function, but then the class isn't strictly a measurement tool and also generates paths. So perhaps it should have a different name either way.
I might be overthinking it, but it will help with readability when it comes time for others to pick up your code and understand what it's supposed to do.
iteration
another python tool to look at is itertools. You can use this for better ability to iterate over lists, etc. in your case it has a combination function.
import itertools
path = []
points = ['a', 'b', 'c', 'd', 'e']
for combo in itertools.combinations(points, 2):
path.append(combo)
this also stores your end result as a list of lists. Each path is a list. I personally dislike storing anything as a string, unless absolutely necessary or if it's actually a word/sentence. | {
"domain": "codereview.stackexchange",
"id": 43055,
"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, combinatorics",
"url": null
} |
c++, algorithm, mergesort
Title: C++ merge sort implementation (looking for advice)
Question: I am trying to practice C++, so I decided to implement canonical algorithms in C++ as a way to learn best practices and idioms of the language.
I started with merge sort. How could I improve this routine?
I especially want to focus on ways of better using the features of C++. I've also included my tests, which I've written with the catch framework.
To run the test, just include the file available here https://github.com/catchorg/Catch2/releases/download/v2.13.8/catch.hpp
#define CATCH_CONFIG_MAIN
#include "catch.hpp"
std::vector<int> merge (std::vector<int> left, std::vector<int> right) {
int num_terms = left.size() + right.size();
std::vector<int> out = {};
int l = 0, r = 0;
for (int i = 0; i < num_terms; i++) {
if (left[l] > right[r]) {
out.push_back(right[r]);
r++;
} else {
out.push_back(left[l]);
l++;
}
if (l == left.size()) {
while (r < right.size()) {
out.push_back(right[r++]);
}
break;
}
if (r == right.size()) {
while (l < left.size()) {
out.push_back(left[l++]);
}
break;
}
}
return out;
}
std::vector<int> merge_sort (std::vector<int> unsorted) {
if (unsorted.size() <= 1) {
return unsorted;
}
// recursively split vector into two vectors
int middle = unsorted.size() / 2;
std::vector<int> left = { unsorted.begin(), unsorted.begin() + middle };
std::vector<int> right = { unsorted.begin() + middle, unsorted.end() };
return merge(merge_sort(left), merge_sort(right));
}
TEST_CASE( "sorts lists of numbers", "[merge_sort]" ) {
SECTION( "non-repeating") {
std::vector<int> sorted = {1, 2, 3, 4, 5};
std::vector<int> unsorted = {5, 2, 4, 3, 1 };
REQUIRE(merge_sort(unsorted) == sorted);
} | {
"domain": "codereview.stackexchange",
"id": 43056,
"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, mergesort",
"url": null
} |
c++, algorithm, mergesort
SECTION("repeating") {
std::vector<int> sorted = {1, 1, 2, 3, 4, 5, 6};
std::vector<int> unsorted = {4, 1, 2, 1, 3, 6, 5};
REQUIRE(merge_sort(unsorted) == sorted);
}
SECTION( "sorts lists with odd number of elements") {
std::vector<int> sorted = {1, 2, 3, 4, 5, 6, 7, 8, 9};
std::vector<int> unsorted = {4, 7, 5, 6, 8, 2, 9, 1, 3 };
REQUIRE(merge_sort(unsorted) == sorted);
}
SECTION("handles lists with two elements") {
std::vector<int> sorted = {2, 8};
std::vector<int> unsorted = {8, 2};
REQUIRE(merge_sort(unsorted) == sorted);
}
SECTION("handles lists with one element") {
std::vector<int> sorted = {8};
std::vector<int> unsorted = {8};
REQUIRE(merge_sort(unsorted) == sorted);
}
SECTION("handles empty lists") {
std::vector<int> sorted = {};
std::vector<int> unsorted = {};
REQUIRE(merge_sort(unsorted) == sorted);
}
}
TEST_CASE("merge merges sorted arrays", "[merge]") {
SECTION("merges sorted vectors of even length") {
std::vector<int> left = {1, 3, 5, 7};
std::vector<int> right = {2, 4, 6, 8};
std::vector<int> merged = {1, 2, 3, 4, 5, 6, 7, 8 };
REQUIRE(merge(left, right) == merged);
}
SECTION("uneven length (l > r)") {
std::vector<int> left = {1, 3, 5, 7};
std::vector<int> right = {2, 4, 6 };
std::vector<int> merged = {1, 2, 3, 4, 5, 6, 7 };
REQUIRE(merge(left, right) == merged);
}
SECTION("uneven length (r > l)") {
std::vector<int> left = {2, 5};
std::vector<int> right = {1, 3, 4};
std::vector<int> merged = {1, 2, 3, 4, 5};
REQUIRE(merge(left, right) == merged);
}
SECTION("duplicate elements") {
std::vector<int> left = {2, 2, 5};
std::vector<int> right = {1, 3, 3, 4};
std::vector<int> merged = {1, 2, 2, 3, 3, 4, 5}; | {
"domain": "codereview.stackexchange",
"id": 43056,
"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, mergesort",
"url": null
} |
c++, algorithm, mergesort
REQUIRE(merge(left, right) == merged);
}
SECTION("one half emptying first") {
std::vector<int> left = {4, 6};
std::vector<int> right = {1, 3 };
std::vector<int> merged = {1, 3, 4, 6};
REQUIRE(merge(left, right) == merged);
}
SECTION("input of two elements") {
std::vector<int> left = {8};
std::vector<int> right = {2};
std::vector<int> merged = {2, 8};
REQUIRE(merge(left, right) == merged);
}
}
Answer: Avoid unnecessary copies
Your algorithm passes vectors solely by value. That means a copy is made each time. This can be very expensive for large arrays. Consider passing vectors that are not going to modified as const references:
std::vector<int> merge(const std::vector<int>& left, const std::vector<int>& right) {
...
}
std::vector<int> merge_sort(const std::vector<int>& unsorted) {
...
} | {
"domain": "codereview.stackexchange",
"id": 43056,
"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, mergesort",
"url": null
} |
c++, algorithm, mergesort
std::vector<int> merge_sort(const std::vector<int>& unsorted) {
...
}
Note however that inside merge_sort(), you are splitting the unsorted input into left and right vectors. That is again making a copy, but what you actually only need is a view of the left and right part of the input vector. Pre C++20, you would do that by passing begin and end iterators. That means std::merge() would need to take four parameters. However, since C++20 you could use std::span or std::ranges::subrange instead.
But another issue is that merge() is returning the result by value. Perhaps you do want an out-of-place merge sort, so merge_sort() itself should return by value, but the drawback of this is that still a lot of temporary vectors are going to be allocated and destroyed before you get the final output. The conclusion you could draw from this is that you should consider implementing an in-place merge sort instead, and let the caller create a copy if so desired.
Use std::size_t instead of int for sizes and indices
Consider trying to sort a vector with \$2^{31}\$ or more entries on a typical 64-bit machine. This will fail because you are storing sizes and indices of vectors in int variables. You should use std::size_t instead, as that is guaranteed to be able to hold any valid index or size of things that can be stored in memory.
Consider making this a template
A big problem is that your merge_sort() function only works for std::vector<int>. What if you want to sort a std::vector<float>? Or what if it's not a vector but a C array or a std::deque<int>? Turning your functions into templates allows them to work on a wider variety of types, without you having to write more code.
The easiest change to make to your code is to make it sort vectors of arbitrary types:
template<typename T>
std::vector<T> merge_sort(const std::vector<T>& unsorted) {
...
} | {
"domain": "codereview.stackexchange",
"id": 43056,
"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, mergesort",
"url": null
} |
c++, algorithm, mergesort
And of course make sure every occurence of std::vector<int> in the body of your functions is replaced with std::vector<T>. But ideally, you could make it work for arbitrary containers:
template<typename Container>
Container merge_sort(const Container& unsorted) {
...
}
You replace every occurence of std::vector<int> with Container, and then it would work with things that work very much like a std::vector, like std::deque, but it wouldn't work with std::list, std::array or C arrays, since you require that the Container type has member functions like size(), and that it can be randomly indexed using []. You can make it work for more types of containers by using std::size() and iterator operations like std::advance().
Going further
Consider that you might want to sort an array not based on the natural ordering of their elements (usually defined by the comparison operators like < and >), but based on some other property. For example, maybe you want to sort ints based on their absolute value, or on their value modulo 42. For this reason, the standard library's sorting functions like std::sort() and std::ranges::sort() take an optional comparison function as a parameter. | {
"domain": "codereview.stackexchange",
"id": 43056,
"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, mergesort",
"url": null
} |
python, python-3.x, numpy, coordinate-system, geospatial
Title: Vincenty's distance Direct formulae numpy | {
"domain": "codereview.stackexchange",
"id": 43057,
"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, numpy, coordinate-system, geospatial",
"url": null
} |
python, python-3.x, numpy, coordinate-system, geospatial
Question: I've refactored a function from the pygc library used to generate the great_circle. The Vincenty's equation below can be found here.
Destination given distance & bearing from start point (direct solution)
Again, this presents Vincenty’s formulæ arranged to be close to how they are used in the script.
$$
\begin{align}
a, b =&\ \textrm{major & minor semi-axes of the ellipsoid} \\
f =&\ \textrm{flattening }(a−b)\ /\ a \\
φ_1, φ_2 =&\ \textrm{geodetic latitude} \\
L =&\ \textrm{difference in longitude} \\
s =&\ \textrm{length of the geodesic along the surface of the ellipsoid (in the same units as }a \textrm{ & } b \textrm{)} \\
α1, α2 =&\ \textrm{azimuths of the geodesic (initial/final bearing)} \\
\\
\tan U_1 =&\ (1−f) \cdot \tan φ_1 &\textrm{(U is ‘reduced latitude’)} \\
\cos U_1 =&\ 1 / \sqrt{1 + \tan^2 U_1},\qquad \sin U_1 = \tan U_1 \cdot \cos U_1 &\textrm{(trig identities; §6)} \\
\sigma_1 =&\ \arctan(\tan U_1 / \cos \alpha_1) \\
\sin α =&\ \cos U_1 \cdot \sin α_1 &(2) \\
\cos^2 α =&\ 1 − \sin^2 α &\textrm{(trig identity; §6)} \\
u^2 =&\ \cos^2 α \cdot \frac{a^2−b^2}{b^2} \\
A =&\ 1 + \frac{u^2}{16384} \cdot \left\{4096 + u^2 \cdot [−768 + u^2 · (320 − 175 \cdot u^2)]\right\} & (3) \\
B =&\ u^2/1024 \cdot \left\{256 + u^2 · [−128 + u^2 · (74 − 47 · u^2)]\right\} & (4) \\
σ =&\ \frac{s}{b \cdot A} & \textrm{(first approximation)} \\
\end{align} \\
$$
iterate until change in σ is negligible (e.g. 10-12 ≈ 0.006mm) {
$$
\begin{align}
\cos 2σ_m =&\ \cos(2σ_1 + σ) & (5) \\
Δσ =&\ B \cdot \sin σ \cdot \left\{\cos 2σ_m + B/4 · [\cos σ · (−1 + 2 \cdot \cos^2 2σ_m) \\
− B/6 \cdot \cos 2σ_m · (−3 + 4 \cdot \sin^2 σ) · (−3 + 4 · cos² 2σ_m)]\right\} & (6) \\
σʹ =&\ s / b·A + Δσ & (7) \\
\end{align}
$$
}
$$
\begin{align}
φ_2 =&\ \arctan(\sin U_1 \cdot \cos σ + \cos U_1 \cdot \sin σ \cdot \cos α_1 \\
&\ / (1−f) \cdot \sqrt{\sin^2 α + (\sin U_1 \cdot \sin σ − \cos U_1 \cdot \cos σ · \cos α_1)^2}) & (8) \\ | {
"domain": "codereview.stackexchange",
"id": 43057,
"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, numpy, coordinate-system, geospatial",
"url": null
} |
python, python-3.x, numpy, coordinate-system, geospatial
λ =&\ \arctan(\sin σ · \sin α_1 / \cos U_1 · \cos σ − \sin U_1 · \sin σ \cdot \cos α_1) & (9) \\
C =&\ f/16 \cdot \cos^2 α · [4 + f · (4 − 3 \cdot \cos^2 α)] & (10) \\
L =&\ λ − (1−C) \cdot f \cdot \sin α · \left\{σ + C \cdot \sin σ \cdot [\cos 2σ_m + C · \cos σ · (−1 + 2 \cdot \cos^2 2σ_m)]\right\} & (11) \\
λ_2 =&\ λ_1 + L \\
α_2 =&\ \arctan\left( \frac{\sin α}{−(\sin U_1 · \sin σ − \cos U_1 · \cos σ \cdot \cos α_1)}\right) & (12) \\
\end{align}
$$
Where: | {
"domain": "codereview.stackexchange",
"id": 43057,
"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, numpy, coordinate-system, geospatial",
"url": null
} |
python, python-3.x, numpy, coordinate-system, geospatial
\$φ_2, λ_2\$ is destination point
\$α_2\$ is final bearing (in direction \$p_1 \rightarrow p_2\$)
constants and imports
"""Vincenty'distance Direct formulae"""
from typing import Tuple
from numpy import (
vectorize,
arctan,
arctan2,
tan,
sin,
cos,
sqrt,
pi
)
# a: Semi-major axis = 6 378 137.0 metres
A = 6_378_137.0
# b: Semi-minor axis ≈ 6 356 752.314 245 metres
B = 6_356_752.314_245
# f = flattening (a−b)/a
F = (A - B) / A
# (a²−b²)/b² ( lat reduction )
F2 = (pow(A, 2) - pow(B, 2)) / pow(B, 2)
TWO_PI = 2.0 * pi
function
upsilon2: Callable[[float], Tuple[float, float]] = (lambda u2: (
# A = 1 + u²/16384 · {4096 + u² · [−768 + u² · (320 − 175 · u²)]}
(1 + (u2 / 16384) * (4096 + u2 * (-768 + u2 * (320 - 175 * u2)))),
# B = u²/1024 · {256 + u² · [−128 + u² · (74 − 47 · u²)]}
((u2 / 1024) * (256 + u2 * (-128 + u2 * (74 - 47 * u2))))
))
def vincenty_direct(
latitude: float,
longitude: float,
azimuth: float,
distance: float) -> Tuple[float, float]:
"""
Returns: lat and long of projected point
"""
azimuth = azimuth + TWO_PI if azimuth < 0.0 else(
azimuth - TWO_PI if azimuth > TWO_PI else azimuth
)
# tan U1 = (1−f) · tan φ1
tan_u1 = (1 - F) * tan(latitude)
# cos U1 = 1 / √1 + tan² U1, sin U1 = tan U1 · cos U1
cos_u1 = arctan(tan_u1)
# σ1 = atan(tan U1 / cos α1)
sigma1 = arctan2(tan_u1, cos(azimuth))
# sin α = cos U1 · sin α1
sin_alpha = cos(cos_u1) * sin(azimuth)
# cos² α = 1 − sin² α
cos2_alpha = 1 - pow(sin_alpha, 2)
(
# A = 1 + u²/16384 · {4096 + u² · [−768 + u² · (320 − 175 · u²)]}
alpha,
# B = u²/1024 · {256 + u² · [−128 + u² · (74 − 47 · u²)]} (4)
beta
# u² = cos² α · (a²−b²)/b²
) = upsilon2(cos2_alpha * F2) | {
"domain": "codereview.stackexchange",
"id": 43057,
"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, numpy, coordinate-system, geospatial",
"url": null
} |
python, python-3.x, numpy, coordinate-system, geospatial
def sigma_recursion(sigma_0: float) -> Tuple[float, float]:
# cos 2σm = cos(2σ1 + σ)
cos_2sigma_m: float = cos(2 * sigma1 + sigma_0)
# Δσ = B · sin σ · {cos 2σm + B/4 · [cos σ · (−1 + 2 · cos² 2σm)
# − B/6 · cos 2σm · (−3 + 4 · sin² σ) · (−3 + 4 · cos² 2σm)]}
delta_sigma: float = (
# B · sin σ ·
beta * sin(sigma_0) *
# cos 2σm + B/4 ·
(cos_2sigma_m + (beta / 4) *
# [cos σ ·
(cos(sigma_0) *
# (−1 + 2 · cos² 2σm) -
(-1 + 2 * pow(cos_2sigma_m, 2) -
# − B/6 · cos 2σm ·
(beta / 6) * cos_2sigma_m *
# (−3 + 4 · sin² σ) ·
(-3 + 4 * pow(sin(sigma_0), 2)) *
# (−3 + 4 · cos² 2σm)]
(-3 + 4 * pow(cos_2sigma_m, 2)))
)
))
# σʹ = s / b·A + Δσ
sigma = (distance / (B * alpha)) + delta_sigma
# iterate until change in σ is negligible (e.g. 10-12 ≈ 0.006mm)
if abs((sigma_0 - sigma) / sigma) > 1.0e-9:
sigma_recursion(sigma)
return sigma, cos_2sigma_m
sigma, cos_2sigma_m = sigma_recursion(
# σ = s / (b·A) (first approximation)
(distance / (B * alpha)))
# φ2 = atan(sin U1 · cos σ + cos U1 · sin σ · cos α1 /
latitude = arctan2(
(sin(cos_u1) * cos(sigma) + cos(cos_u1) * sin(sigma) * cos(azimuth)),
# (1−f) · √sin² α + (sin U1 · sin σ − cos U1 · cos σ · cos α1)² )
((1 - F) * sqrt(pow(sin_alpha, 2) +
pow(sin(cos_u1) * sin(sigma) - cos(cos_u1) * cos(sigma) * cos(azimuth), 2)))
) | {
"domain": "codereview.stackexchange",
"id": 43057,
"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, numpy, coordinate-system, geospatial",
"url": null
} |
python, python-3.x, numpy, coordinate-system, geospatial
def omega():
# λ = atan(sin σ · sin α1 / cos U1 · cos σ − sin U1 · sin σ · cos α1)
_lambda = arctan2(
(sin(sigma) * sin(azimuth)),
(cos(cos_u1) * cos(sigma) - sin(cos_u1) * sin(sigma) * cos(azimuth))
)
# C = f/16 · cos² α · [4 + f · (4 − 3 · cos² α)]
c_sigma = (
(F / 16) * cos2_alpha *
(4 + F * (4 - 3 * cos2_alpha))
)
# L = λ − (1−C) · f · sin α · {σ + C · sin σ · [cos 2σm + C · cos σ · (−1 + 2 · cos² 2σm)]}
return (
_lambda - (1 - c_sigma) * F * sin_alpha * (
sigma + c_sigma * sin(sigma) * (
cos_2sigma_m + c_sigma *
cos(sigma) * (-1 + 2 * pow(cos_2sigma_m, 2))
)))
# return longitude + omega
return latitude, longitude + omega()
direct = vectorize(vincenty_direct)
usage
import numpy as np
from vincenty import direct
def dev_dist(project_seconds=np.array([900, 1800, 2700, 3600])):
"""dev"""
# position
latitude = 33.01
longitude = -98.94
# direction
azimuth = -171.95
# speed
meters_per_second = 11
# distance projection
distance = meters_per_second*project_seconds
# in rads
rad_lat, rad_lon, rad_azi = np.deg2rad((latitude, longitude, azimuth))
#
degs = np.around(np.rad2deg(
direct(rad_lat, rad_lon, rad_azi, distance)), decimals=2)
points = np.swapaxes(degs, 0, 1)
times = [f"+{x:02.0f}min"for x in project_seconds/60]
projection = dict(zip(times, points.tolist()))
if __name__ == '__main__':
dev_dist()
distance (meters)
>>> [ 9900 19800 29700 39600]
degs
>>> [[ 32.92 32.83 32.74 32.66]
[-98.95 -98.97 -98.98 -99. ]]
points
>>> [[ 32.92 -98.95]
[ 32.83 -98.97]
[ 32.74 -98.98]
[ 32.66 -99. ]]
projection
>>> {'+15min': [32.92, -98.95], '+30min': [32.83, -98.97], '+45min': [32.74, -98.98], '+60min': [32.66, -99.0]} | {
"domain": "codereview.stackexchange",
"id": 43057,
"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, numpy, coordinate-system, geospatial",
"url": null
} |
python, python-3.x, numpy, coordinate-system, geospatial
Answer: Not a great idea to from numpy import, since there are so many symbols needed that that can lead to significant namespace pollution. The typical approach is just import numpy as np.
Rather than pow(, 2) you can just **2.
upsilon2 should not be a lambda, and should be a regular function instead.
The angle normalisation of
azimuth = azimuth + TWO_PI if azimuth < 0.0 else(
azimuth - TWO_PI if azimuth > TWO_PI else azimuth
)
is not necessary, and even if it were, you should just do
azimuth = np.mod(azimuth, TWO_PI)
Don't recurse! Python has a very shallow stack capacity and no tail optimization. Just iterate - and this is quite easy with your existing function.
Your indentation sometimes deviates from 4 spaces. Try to keep this consistent.
Rather than _lambda, to escape a keyword it's more frequent to see lambda_.
Don't vectorize(vincenty_direct). You can write an actual vectorised implementation with very little modification to your original implementation.
Add some tests. The only ones that I have shown are to test against regression.
Don't np.around. Keep full precision. There are better ways to truncate precision for print if that's what you're looking for.
Your use of .swapaxes can be replaced with .T.
You would benefit from being a little more granular with your functions, cutting them out of closure scope to make dependencies more explicit. Other benefits are that profiling - if that ever becomes necessary - is much easier.
Suggested
"""Vincenty's distance Direct formulae"""
from pprint import pprint
import numpy as np
# a: Semi-major axis = 6_378_137.0 metres
A = 6_378_137.0
# b: Semi-minor axis ≈ 6_356_752.314_245 metres
B = 6_356_752.314_245
# f = flattening (a−b)/a
F = 1 - B/A
# (a²−b²)/b² ( lat reduction )
F2 = (A / B)**2 - 1
TWO_PI = 2 * np.pi | {
"domain": "codereview.stackexchange",
"id": 43057,
"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, numpy, coordinate-system, geospatial",
"url": null
} |
python, python-3.x, numpy, coordinate-system, geospatial
TWO_PI = 2 * np.pi
def get_upsilon2(u2: float) -> tuple[float, float]:
# u² = cos² α · (a²−b²)/b²
return (
# A = 1 + u²/16384 · {4096 + u² · [−768 + u² · (320 − 175 · u²)]}
1 + u2/16384 * (4096 + u2 * (-768 + u2 * (320 - 175*u2))),
# B = u²/1024 · {256 + u² · [−128 + u² · (74 − 47 · u²)]}
u2/1024 * (256 + u2 * (-128 + u2 * (74 - 47*u2))),
)
def sigma_iteration(sigma_0: np.ndarray, sigma1, alpha, beta, distance) -> tuple[np.ndarray, np.ndarray]:
# cos 2σm = cos(2σ1 + σ)
cos_2sigma_m = np.cos(2 * sigma1 + sigma_0)
# Δσ = B · sin σ · {cos 2σm + B/4 · [cos σ · (−1 + 2 · cos² 2σm)
# − B/6 · cos 2σm · (−3 + 4 · sin² σ) · (−3 + 4 · cos² 2σm)]}
delta_sigma = (
# B · sin σ ·
beta * np.sin(sigma_0) *
# cos 2σm + B/4 ·
(
cos_2sigma_m + beta/4 *
# [cos σ ·
np.cos(sigma_0) *
(
# (−1 + 2 · cos² 2σm) -
-1 + 2*cos_2sigma_m**2 -
# − B/6 · cos 2σm ·
beta/6 * cos_2sigma_m *
# (−3 + 4 · sin² σ) ·
(-3 + 4*np.sin(sigma_0)**2) *
# (−3 + 4 · cos² 2σm)]
(-3 + 4*cos_2sigma_m**2)
)
)
)
# σʹ = s / b·A + Δσ
sigma = distance/B/alpha + delta_sigma
return sigma, cos_2sigma_m
def get_sigma(distance: np.ndarray, alpha: float, beta: float, sigma1: float) -> tuple[np.ndarray, np.ndarray]:
# σ = s / (b·A) (first approximation)
sigma = distance / B / alpha
# iterate until change in σ is negligible (e.g. 10-12 ≈ 0.006mm)
while True:
old_sigma = sigma
sigma, cos_2sigma_m = sigma_iteration(old_sigma, sigma1, alpha, beta, distance)
if np.all(np.abs(old_sigma/sigma - 1) <= 1e-12):
return sigma, cos_2sigma_m | {
"domain": "codereview.stackexchange",
"id": 43057,
"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, numpy, coordinate-system, geospatial",
"url": null
} |
python, python-3.x, numpy, coordinate-system, geospatial
def get_omega(
azimuth: float, sigma: np.ndarray, cos_u1: float,
sin_alpha: float, cos_2sigma_m: np.ndarray, cos2_alpha: float,
) -> np.ndarray:
# λ = atan(sin σ · sin α1 / cos U1 · cos σ − sin U1 · sin σ · cos α1)
lambda_ = np.arctan2(
(np.sin(sigma) * np.sin(azimuth)),
(np.cos(cos_u1) * np.cos(sigma) - np.sin(cos_u1) * np.sin(sigma) * np.cos(azimuth))
)
# C = f/16 · cos² α · [4 + f · (4 − 3 · cos² α)]
c_sigma = (
F/16 * cos2_alpha *
(4 + F*(4 - 3*cos2_alpha))
)
# L = λ − (1−C) · f · sin α · {σ + C · sin σ · [cos 2σm + C · cos σ · (−1 + 2 · cos² 2σm)]}
return (
lambda_ - (1 - c_sigma)*F*sin_alpha * (
sigma + c_sigma * np.sin(sigma) * (
cos_2sigma_m + c_sigma *
np.cos(sigma) * (-1 + 2 * cos_2sigma_m**2)
)
)
)
def get_latitude(azimuth: float, sigma: np.ndarray, cos_u1: float, sin_alpha: float) -> np.ndarray:
# φ2 = atan(sin U1 · cos σ + cos U1 · sin σ · cos α1 /
latitude = np.arctan2(
(np.sin(cos_u1) * np.cos(sigma) + np.cos(cos_u1) * np.sin(sigma) * np.cos(azimuth)),
# (1−f) · √sin² α + (sin U1 · sin σ − cos U1 · cos σ · cos α1)² )
(
(1 - F) * np.sqrt(
sin_alpha**2 +
(
np.sin(cos_u1) * np.sin(sigma) - np.cos(cos_u1) * np.cos(sigma) * np.cos(azimuth)
)**2
)
)
)
return latitude
def vincenty_direct(
latitude: float,
longitude: float,
azimuth: float,
distance: np.ndarray,
) -> tuple[np.ndarray, np.ndarray]:
"""
Returns: lat and long of projected point
"""
# Not necessary:
azimuth = np.mod(azimuth, TWO_PI) | {
"domain": "codereview.stackexchange",
"id": 43057,
"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, numpy, coordinate-system, geospatial",
"url": null
} |
python, python-3.x, numpy, coordinate-system, geospatial
# Not necessary:
azimuth = np.mod(azimuth, TWO_PI)
# tan U1 = (1−f) · tan φ1
tan_u1 = (1 - F) * np.tan(latitude)
# cos U1 = 1 / √1 + tan² U1, sin U1 = tan U1 · cos U1
cos_u1 = np.arctan(tan_u1)
# σ1 = atan(tan U1 / cos α1)
sigma1 = np.arctan2(tan_u1, np.cos(azimuth))
# sin α = cos U1 · sin α1
sin_alpha = np.cos(cos_u1) * np.sin(azimuth)
# cos² α = 1 − sin² α
cos2_alpha = 1 - sin_alpha**2
alpha, beta = get_upsilon2(cos2_alpha * F2)
sigma, cos_2sigma_m = get_sigma(distance, alpha, beta, sigma1)
latitude = get_latitude(azimuth, sigma, cos_u1, sin_alpha)
omega = get_omega(azimuth, sigma, cos_u1, sin_alpha, cos_2sigma_m, cos2_alpha)
return latitude, longitude + omega
def dev_dist(project_seconds=None) -> None:
if project_seconds is None:
project_seconds = np.linspace(900, 3600, 4)
# position
latitude = 33.01
longitude = -98.94
# direction
azimuth = -171.95
# speed
meters_per_second = 11
# distance projection
distance = meters_per_second * project_seconds
# in rads
rad_lat, rad_lon, rad_azi = np.deg2rad((latitude, longitude, azimuth))
degs = np.rad2deg(
vincenty_direct(rad_lat, rad_lon, rad_azi, distance)
)
points = degs.T
assert np.allclose(
points,
(
(32.921612216500890, -98.95482179485320),
(32.833221427146340, -98.96961414990395),
(32.744827642960495, -98.98437722206711),
(32.656430874926910, -98.99911116737137),
),
atol=1e-12, rtol=0,
)
times = (f"+{x:02.0f}min" for x in project_seconds / 60)
projection = dict(zip(times, points.tolist()))
pprint(projection)
if __name__ == '__main__':
dev_dist()
Output
{'+15min': [32.92161221650089, -98.9548217948532],
'+30min': [32.83322142714634, -98.96961414990395],
'+45min': [32.744827642960495, -98.98437722206711],
'+60min': [32.65643087492691, -98.99911116737137]} | {
"domain": "codereview.stackexchange",
"id": 43057,
"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, numpy, coordinate-system, geospatial",
"url": null
} |
java, object-oriented, playing-cards
Title: Blackjack implementation - Java
Question: I have inspired from the recent blackjack question here and decide to code for simple blackjack console application
Please review and let me know What can improve on the code?
Rules for the application:
There's a single dealer and a player
Initially both get two cards
Number 2 to 9 cards have their numerical value that is counted as their score, Face cards have value of 10, Ace's value changes based on the current score
Then Player asks dealer to hit, as long as Player's score is less than 17
When Player reaches 17 or more then they no longer go for hit
Dealer starts their turn, they go for hit as long as Dealer's score is less than 17
After both are done with their turns, Outcome would be decided
Every action has system out, output will be similar to this
Task :GamePlay.main()
Dealer got 4♣ score: 4 status: HIT
Dealer got K♦︎ score: 14 status: HIT
Player got A♦︎ score: 11 status: HIT
Player got J♥ score: 21 status: BLACKJACK
Dealer got 10♠ score: 24 status: BUST
Dealer Bust, Player Wins
class Card
public class Card {
private Suit suit;
private Type type;
public Card(Suit suit, Type type) {
this.suit = suit;
this.type = type;
}
public Suit getSuit() {
return suit;
}
public Type getType() {
return type;
}
@Override
public String toString() {
return this.getType().toString() + this.getSuit().toString();
}
}
enum Suit
public enum Suit {
SPADE('♠'), DIAMOND('♦︎'), CLUB('♣'), HEART('♥');
private final char symbol;
Suit(char symbol) {
this.symbol = symbol;
}
@Override
public String toString() {
return String.valueOf(this.symbol);
}
} | {
"domain": "codereview.stackexchange",
"id": 43058,
"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, object-oriented, playing-cards",
"url": null
} |
java, object-oriented, playing-cards
@Override
public String toString() {
return String.valueOf(this.symbol);
}
}
enum Type
Type enum constructor takes two parameters, their default value and symbol to represent on output, also the enum has getDefaultValue method
Ace has overriden the method. since it has it's own implementation
import static blackjack.GamePlay.ACE_MAX_VALUE;
public enum Type {
TWO(2, "2"), THREE(3, "3"), FOUR(4, "4"), FIVE(5, "5"),
SIX(6, "6"), SEVEN(7, "7"), EIGHT(8, "8"), NINE(9, "9"),
TEN(10, "10"),
ACE(ACE_MAX_VALUE, "A") {
@Override
public int getDefaultValue(int totalValue) {
if (totalValue + ACE_MAX_VALUE > 21) {
return 1;
}
return ACE_MAX_VALUE;
}
},
JACK(10, "J"), QUEEN(10, "Q"), KING(10, "K");
private int defaultValue;
private String symbol;
Type(int defaultValue, String symbol) {
this.defaultValue = defaultValue;
this.symbol = symbol;
}
public int getDefaultValue(int totalValue) {
return this.defaultValue;
}
@Override
public String toString() {
return this.symbol;
}
}
class Deck
Deck has list of all 52 Cards and loads them into the list on constructor, it has getACard method which removes a card from random index and return a Card object for dealer to draw
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class Deck {
private List<Card> cards;
public Deck() {
this.cards = new ArrayList<>();
loadCards();
}
private void loadCards() {
for (Suit suit : Suit.values()) {
for (Type type : Type.values()) {
this.cards.add(new Card(suit, type));
}
}
}
public Card getACard() {
int randomIndex = new Random().nextInt(this.cards.size());
return this.cards.remove(randomIndex);
}
} | {
"domain": "codereview.stackexchange",
"id": 43058,
"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, object-oriented, playing-cards",
"url": null
} |
java, object-oriented, playing-cards
class Dealer
Dealer has the Deck, on constructor it draws two cards and adds to their list of cards
and updates their score and status.
It has hit method which draws a Card from the Deck and returns. based on the value of the card their score and status is updated.
play method does the orchestration also prints the state of the Dealer
canHit method checks the status of the Dealer returns true if they're in HIT status
import java.util.ArrayList;
import java.util.List;
import static blackjack.GamePlay.*;
public class Dealer {
private Deck deck;
private List<Card> cards;
private int score;
private Status status;
public Dealer(Deck deck) {
this.cards = new ArrayList<>();
this.deck = deck;
for (int i = 0; i < INITIAL_CARDS_COUNT; i++) {
play();
}
}
public Card hit() {
return this.deck.getACard();
}
public void play() {
Card card = hit();
this.score += card.getType().getDefaultValue(this.score);
this.cards.add(card);
this.status = Status.getStatus(this.score);
System.out.printf("Dealer got %s \t score: %d \t status: %s \n", card, this.score,this.status.toString());
}
public boolean canHit() {
return this.status.equals(Status.HIT);
}
public Status getStatus() {
return status;
}
public int getScore() {
return score;
}
}
class Player
Player has the Dealer, on constructor it draws two cards and adds to their list of cards and updates their score and status.
It has hit method which draws a Card from the Dealer and returns. based on the value of the card their score and status is updated.
play method does the orchestration also prints the state of the Player
canHit method checks the status of the Dealer returns true if they're in HIT status
import java.util.ArrayList;
import java.util.List;
import static blackjack.GamePlay.INITIAL_CARDS_COUNT;
import static blackjack.Status.HIT; | {
"domain": "codereview.stackexchange",
"id": 43058,
"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, object-oriented, playing-cards",
"url": null
} |
java, object-oriented, playing-cards
import static blackjack.GamePlay.INITIAL_CARDS_COUNT;
import static blackjack.Status.HIT;
public class Player {
private List<Card> cards;
private Dealer dealer;
private int score;
private Status status;
public Player(Dealer dealer) {
this.cards = new ArrayList<>();
this.dealer = dealer;
for (int i = 0; i < INITIAL_CARDS_COUNT; i++) {
play();
}
}
public void play() {
Card card = this.dealer.hit();
this.score += card.getType().getDefaultValue(this.score);
this.cards.add(card);
this.status = Status.getStatus(this.score);
System.out.printf("Player got %s \t score: %d \t status: %s \n", card, this.score,this.status.toString());
}
public boolean canHit() {
return this.status.equals(HIT);
}
public Status getStatus() {
return status;
}
public int getScore() {
return score;
}
}
enum Status
Status enum has constructor takes two params min and max, this decides which Status any score fall in
getStatus method takes score and return Status based on the score
public enum Status {
HIT(0, 16), STAND(17, 20), BLACKJACK(21, 21), BUST(22, 100);
private int min;
private int max;
Status(int min, int max) {
this.min = min;
this.max = max;
}
public static Status getStatus(int score) {
Status[] statuses = Status.values();
for (Status status : statuses) {
if (status.min <= score && status.max >= score) {
return status;
}
}
return null;
}
}
class GamePlay
This is orchestrator for the application creates All objects and decides the outcome of the game
public class GamePlay {
public static final int INITIAL_CARDS_COUNT = 2;
public static final int ACE_MAX_VALUE = 11; | {
"domain": "codereview.stackexchange",
"id": 43058,
"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, object-oriented, playing-cards",
"url": null
} |
java, object-oriented, playing-cards
public static final int INITIAL_CARDS_COUNT = 2;
public static final int ACE_MAX_VALUE = 11;
public static String getOutcome(Player player, Dealer dealer) {
if (player.getStatus().equals(Status.BUST)) {
return "Player Bust, Dealer Wins";
} else if (player.getScore() == dealer.getScore()) {
return "Tie";
} else if (dealer.getStatus().equals(Status.BUST)) {
return "Dealer Bust, Player Wins";
} else if (player.getScore() > dealer.getScore()) {
return "Player Wins";
}
return "Dealer Wins";
}
public static void main(String[] args) {
Deck deck = new Deck();
Dealer dealer = new Dealer(deck);
Player player = new Player(dealer);
while (player.canHit()) {
player.play();
}
while (dealer.canHit()) {
dealer.play();
}
System.out.println(getOutcome(player, dealer));
}
}
Answer: The code looks pretty decent. I can look at it and follow what is going on without too much difficulty. Here are a few things for your consideration. Note that some are aesthetic, and some are not super important for a small program but could be for a larger program, and there are a couple of questions to think about different ways you could have done things.
enum Type | {
"domain": "codereview.stackexchange",
"id": 43058,
"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, object-oriented, playing-cards",
"url": null
} |
java, object-oriented, playing-cards
enum Type
For the Types, ACE is right after TEN and before JACK, QUEEN, and KING. Those last four all have 10 as a value, so it would probably be better to put ACE after them. (General rule of organization: Similar things go together.)
ACE_MAX_VALUE is defined over in the GamePlay class. You may have some aesthetic for putting it there, but it is only used in the Type enum. Also this creates a circular dependency through GamePlay, Deck, Type, GamePlay, etc. Consider moving it into Type, though you may have to use an ugly static nested class. (Note: You can see dependencies in a program like Stan4J or Structure101.)
The word Type is extremely generic. How about something a little more descriptive, perhaps FaceValue?
Dealer and Player
Is it necessary for the Player to have a reference to the Dealer just so the Dealer can get a card for the Player? I realize there is text in the "Rules" at the top saying that the Player gets the card from the Dealer, but it may not be necessary if you let them both know about the Deck.
The GamePlay class has the logic for while (player.canHit()) player.play();. Could Player simply have a playAll() method?
These two classes are nearly identical, so there is duplicate code. Could they be the same? If so, you could move the definition of the INITIAL_CARDS_COUNT constant into that class. (General principle: DRY - Don't Repeat Yourself)
Deck | {
"domain": "codereview.stackexchange",
"id": 43058,
"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, object-oriented, playing-cards",
"url": null
} |
java, object-oriented, playing-cards
Deck
The Deck is creating a new Random() for each draw. You could create one, and save it as part of the class state. This is probably not important for such a small program.
Something else that may not be important in this example, when you remove a card from the List, all other cards, all other cards from the removed index to the end of the list have to be moved down. Mind you, your code is clear and correct as is, however it is just a little inefficient. You could read the item at the index, move the last item to the current item, and then remove the final item from the List so nothing gets moved down.
The method name getACard() might read better as drawCard().
Have you considered unit testing?
How would you unit test this thing? How many unit tests would you need? Perhaps you could have an alternate constructor for Deck that takes in a seed for the Random to get a predictable order.
How would the program have come out different if you had coded it with TDD (or even BDD)? Just in case you (or other readers) don't know, JUnit is the most common Java TDD framework, and Cucumber for Java is the most common Java BDD framework.
enum Status
The game logic only depends on canHit, so you really only need two Statuses - one for playing and one for done. Or perhaps play() can return a boolean indicating whether it is done? Perhaps there should be a separate enum Result?
Nice work. I hope this gives you some ideas to "plus" it. | {
"domain": "codereview.stackexchange",
"id": 43058,
"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, object-oriented, playing-cards",
"url": null
} |
performance, c, strings, mathematics
Title: Entropy of String in C
Question: I have written a C program that calculates Shannon entropy for a C-String (const char *). It works well but in many implementation the code uses some-kind of map like structures which are available by default in their respective language. But we all know C does not have maps. My code is very fast even for 100 megabytes of data.
Here's the formula to calculate Shannon entropy
$$
{\displaystyle \mathrm {H} (X)=-\sum _{i=1}^{n}{\mathrm {P} (x_{i})\log \mathrm {P} (x_{i})}}
$$
Can anyone suggest me even more efficient way to calculate the entropy in C? Any kind of suggestion or improvement is appreciated.
Here's my code: TRY IT ONLINE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <math.h>
static double entropy(const char *str)
{
if (!str) // return -1 is str is NULL
return -1.0;
size_t len = strlen(str); // get the length of str
/*
* cnt -> iterate over the str
* map_append -> stores the index of unique character in str
* imap_append -> stores the index of non-unique character in str
*/
size_t cnt = 0, map_append = 0, imap_append = 0;
int check = false; // boolean type value to store whether char is unique or not
char *map_char = (char *)calloc(len + 1, sizeof(char)); // heap allocation to store unique characters
size_t *map_cnt = (size_t *)calloc(len + 1, sizeof(size_t)); // heap allocation to store the freq. of unique characters | {
"domain": "codereview.stackexchange",
"id": 43059,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, c, strings, mathematics",
"url": null
} |
performance, c, strings, mathematics
for (cnt = 0; cnt < len; cnt++)
{
check = false;
for (imap_append = 0; map_char[imap_append] != '\0'; imap_append++)
{
if (map_char[imap_append] == str[cnt])
{
check = true; // char is not unique
break;
}
}
if (check == false) // char is unique
{
map_char[map_append] = str[cnt];
map_cnt[map_append] = 1;
map_append++;
// add it to the `map_char` and set `map_cnt` value to 1
}
else
map_cnt[imap_append] += 1; // just increment the freq. of that not-unique char, at `imap_append`
}
/* just the application of the formula */
double result = 0.0;
double freq = 0.0;
for (size_t i = 0; map_char[i] != '\0'; i++)
{
freq = (double)map_cnt[i] / (double)len;
result -= freq * (log10(freq) / log10(2.0));
}
free(map_char); // no mem leaks
free(map_cnt); // no mem leaks
return result;
}
int main(int argc, char const **argv)
{
if (argc == 1)
{
fprintf(stderr, "no file input\n");
return EXIT_FAILURE;
}
FILE *f = fopen(argv[1], "r");
if (!f)
{
fprintf(stderr, "`%s` could not be opened or was not found.\n", argv[1]);
return EXIT_FAILURE;
}
fseek(f, 0, SEEK_END);
size_t len = ftell(f);
fseek(f, 0, SEEK_SET);
char *data = (char *)calloc(len, sizeof(char));
fread(data, sizeof(char), len, f);
fclose(f);
printf("Length of file: `%s` = %zu\n", argv[1], len);
printf("Entropy of file: `%s` = %f\n", argv[1], entropy((const char *)data));
return EXIT_SUCCESS;
}
I compiled the above program using the command:
gcc -Og -O3 -Ofast -Os -s main.c -lm -o main
My output was: (That 100MB file was generated by random ASCII characters)
Length of file: `./temp.txt` = 104857600
Entropy of file: `./temp.txt` = 6.569855 | {
"domain": "codereview.stackexchange",
"id": 43059,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, c, strings, mathematics",
"url": null
} |
performance, c, strings, mathematics
Here's a benchmark on a 100 megabytes file on zsh shell on Intel i5-7200U:
./main ./temp.txt 4.54s user 0.06s system 99% cpu 4.598 total
Answer: Some general remarks
You include <stdbool.h>, but still use int check to hold a boolean value. That should be bool check.
The check if (check == false) can be shorted to if (!check).
Memory allocation can fail, you have to check the return value of the calloc() calls. In the case of a failure you have to decide how to report that to the caller.
Some variables can be declared at a narrower scope, e.g.
double freq = 0.0;
for (size_t i = 0; map_char[i] != '\0'; i++)
{
freq = (double)map_cnt[i] / (double)len;
// ...
}
should be
for (size_t i = 0; map_char[i] != '\0'; i++)
{
double freq = (double)map_cnt[i] / (double)len;
// ...
}
Possible improvements of the algorithm
A char has 8 bits on most platforms (including all POSIX platforms). In that case there are only 255 different characters, plus the null character as the terminator.
Which means that it always suffices to allocate the tables which space for 256 entries (or 1 << CHAR_BIT, in general). CHAR_BIT and related constants are defined in <limits.h>.
That saves a lot of space if the input string is long. It also allows to make the tables local stack arrays and get rid of calloc():
char map_char[1 << CHAR_BIT] = { 0 };
size_t map_cnt[1 << CHAR_BIT] = { 0 };
Even better: Use the character itself as the index into the table, so that the inner loop becomes obsolete:
size_t frequencies[1 << CHAR_BIT] = { 0 };
for (const char *p = str; *p != 0; p++) {
frequencies[*p - CHAR_MIN]++;
}
The computation of the entropy then works are before, only that zero frequencies must be skipped:
size_t len = strlen(str);
double result = 0.0;
for (int i = 0; i < 1 << CHAR_BIT; i++) {
if (frequencies[i] != 0) {
double freq = (double)frequencies[i] / (double)len;
result -= freq * (log(freq) / log(2.0));
}
} | {
"domain": "codereview.stackexchange",
"id": 43059,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, c, strings, mathematics",
"url": null
} |
performance, c, strings, mathematics
Processing large files
It is not necessary to read the entire file into memory. You can read it in chunks, update the frequency table for each chunk, and finally compute the entropy.
That saves a lot of space for large input files. | {
"domain": "codereview.stackexchange",
"id": 43059,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, c, strings, mathematics",
"url": null
} |
c++, algorithm, recursion
Title: Finding the largest value in array - Recursion
Question: I know this may be a silly question (I'm just learning about recursion, and I think there are still things that are still not clear to me.), but... is this a good implementation of a recursive function to find the maximum number in an array?
#include <iostream>
#include <cstdlib>
using std::cout;
using std::endl;
/* function prototype */
int find_max(const int [], int);
/* main function */
int
main(void)
{
int array[] = {2, 6, 8, 23, 45, 43, 51, 62, 83, 78, 61, 18, 71, 34, 72};
int size = sizeof(array) / sizeof(array[0]);
cout << "HIGHEST: " << find_max(array, size) << endl;
exit(EXIT_SUCCESS);
}
/* function definition */
int
find_max(const int array[], int size)
{
int i = 1;
int highest = array[0], l = 0;
if (i < size)
l = find_max(array+i, size-1);
if (l > highest)
highest = l;
return highest;
}
output:
./main
HIGHEST: 83
what I basically want to do is implement the same algorithm using recursive structure.
or rather implement the function below.
int
find_max(const int array[], int size)
{
int highest = array[0];
for (int i = 1; i < size; i++)
{
if (array[i] > highest)
highest = array[i];
}
return highest;
} | {
"domain": "codereview.stackexchange",
"id": 43060,
"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, recursion",
"url": null
} |
c++, algorithm, recursion
Answer: I respectfully disagree with the advice to prefer iteration to recursion. I personally prefer to express most algorithms recursively. It’s much more suitable to a kind of programming style, using only static single assignments, where certain kinds of bugs become impossible to write without the compiler catching them. It’s often easier to reason about the code and prove it correct. And, properly-written, it’s just as efficient.
For several decades, programmers were taught to turn recursive functions into iterative loops, but that was originally because compilers used to be bad at optimizing recursive calls. That’s no longer as true as it was, so it’s now a matter of personal preference.
Besides, you’ll have to learn to program in a functional language that has only recursive calls and not loops, if you want a computer science degree these days.
So, how do we write this in a recursive call? For the sake of explaining exactly what I’m doing and why, I’m going to ridiculously overdo it. This would be one line of code in a functional language. With that in mind, in functional style, all the local state of the loop becomes parameters of a function, and whenever that local state changes, such as the loop incrementing its counter and repeating, become the function returning a call to itself.
What, then, is the local state? The code you want to transform starts out as
int
find_max(const int array[], int size)
{
int highest = array[0];
for (int i = 1; i < size; i++)
{
if (array[i] > highest)
highest = array[i];
}
return highest;
} | {
"domain": "codereview.stackexchange",
"id": 43060,
"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, recursion",
"url": null
} |
c++, algorithm, recursion
There are four local variables here: array, size, i and highest. You already figured out, in a similar question you asked, that you can reduce this to three by searching from back to front instead of front to back; the loop for ( auto i = size; i > 0; --i ) only uses size to initialize i, and only need i thereafter. Another way to bring this down to three state variables would be to recursively search the subarray starting at array+1 of length size-1, the subarray starting at array+2 of length size-2, and so on. Another common idiom for this is to use a current and end pointer, and stop when current is equal to end. Here, let’s use the same approach you did in your other question and count down.
Since the local update we want to keep around consists of array, i, and highest, our function signature should look like
int find_max( const int array[], size_t i, int highest )
Only, like in my other answer, we want this to be constexpr so it can perform constant-folding, and noexcept to help the compiler optimize. On top of that, the only time the state chances is when we make a tail-recursive call, and we can only update the entire state together, so there is no way we can accidentally forget to update one of the state variables or update it twice. So, with static single assignments, the function declaration becomes,
constexpr int find_max( const int array[], size_t i, int highest ) noexcept
Only, the original caller passed in array and size, so this is actually a helper function that find_max will call, and find_max itself will use the same interface as before. So, we actually want a pair of functions:
static constexpr int find_max_helper( const int array[], const size_t i, const int highest ) noexcept;
constexpr int find_max( const int array[], const size_t size ); | {
"domain": "codereview.stackexchange",
"id": 43060,
"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, recursion",
"url": null
} |
c++, algorithm, recursion
constexpr int find_max( const int array[], const size_t size );
We want to make sure to write only tail calls, so our function should have an if/then/else structure, where each branch returns either an int or a function call. Let’s see the original function again.
int
find_max(const int array[], int size)
{
int highest = array[0];
for (int i = 1; i < size; i++)
{
if (array[i] > highest)
highest = array[i];
}
return highest;
}
What I ideally try to do (but don’t always, especially for really short examples like this) is write the contract for my functions in a comment first. In this case, the name of the function and its parameters are self-explanatory, but that might look like:
constexpr int find_max( const int array[], const size_t size )
/* Returns the maximum value of the array of the given size.
*/
Only, wait, what is the maximum value of a zero-length array? Your implementation just checks array[0] unconditionally, so find_max( NULL, 0 ) would have undefined behavior, usually a segmentation fault. You always, always, always check for a buffer overrun in C and C++. It is never too early to get in the habit. I seriously mean it. That could be an assert(), but for this example, let’s throw an std::logic_error exception.
And there are several possible ways we could have handled this, so it actually becomes important to document the behavior of the function in this case, or at least warn anyone who uses this function what assumptions it makes.
So the first few lines of our function will look like this:
constexpr int find_max( const int array[], const size_t size )
/* Returns the maximum value of the array of the given size.
* Throws std::logic_error if size is 0.
*/
{
if ( size == 0 ) {
throw std::logic_error("Max of a zero-length array");
} | {
"domain": "codereview.stackexchange",
"id": 43060,
"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, recursion",
"url": null
} |
c++, algorithm, recursion
What about the rest? We’re reducing the array from back to front and you initialize highest to the first element before you start looping. We refactored to search from the back, so the first element we check is now the rightmost instead of the leftmost, and we replace iterations of the loop with tail-calls to a helper function, but we can follow the exact same logic. our initial state has i equal to size-1 (and we just checked that size is greater than 0, so this is in bounds), array equal to the value we were passed, and highest equal to the last element of array, which is array[size-1].
So far, then, we have
static constexpr int find_max_helper( const int array[], const size_t i, const int highest ) noexcept;
/* Searches the array from index i to 0 for an element greater than highest.
* Intended to be called only from find_max.
*/
constexpr int find_max( const int array[], const size_t size )
/* Returns the maximum value of the array of the given size.
* Throws std::logic_error if size is 0.
*/
{
if ( size == 0 ) {
throw std::logic_error("Max of a zero-length array");
}
return find_max_helper( array, size-1, array[size-1] )
}
Now we just need to implement find_max_helper. It’s pretty straightforward: check whether we’ve reached the start of the array, and if not, find the new maximum and recurse. So, there are three branches: the termination check, the case where the current element is higher, and the case where it isn’t.
static constexpr int find_max_helper( const int array[], const size_t i, const int highest ) noexcept
/* searches the array from index i to 0 for an element greater than highest.
* Intended to be called only from find_max.
*/
{
if ( i == 0 ) {
return highest;
} else if ( array[i-1] > highest ) {
return find_max_helper( array, i-1, array[i-1] );
} else {
return find_max_helper( array, i-1, highest );
}
} | {
"domain": "codereview.stackexchange",
"id": 43060,
"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, recursion",
"url": null
} |
c++, algorithm, recursion
You could also express this as a series of if statements that either return or fall through, making it clearer that the function always terminates in a valid return) or in a nested ternary expression like in your other question for review.
Putting it all together, and setting our types correctly in the main test driver, we get:
#include <cassert>
#include <cstdlib> // for EXIT_SUCCESS
#include <iostream>
#include <stdexcept> // For runtime_error
using std::cout, std::endl, std::size_t;
static constexpr int find_max_helper( const int array[], const size_t i, const int highest ) noexcept
/* Searches the array from index i to 0 for an element greater than highest.
* Intended to be called only from find_max.
*/
{
if ( i == 0 ) {
return highest;
} else if ( array[i-1] > highest ) {
return find_max_helper( array, i-1, array[i-1] );
} else {
return find_max_helper( array, i-1, highest );
}
}
constexpr int find_max( const int array[], const size_t size )
/* Returns the maximum value of the array of the given size.
* Throws std::logic_error if size is 0.
*/
{
if ( size == 0 ) {
throw std::logic_error("Max of a zero-length array");
}
return find_max_helper( array, size-1, array[size-1] );
}
int main(void)
// Test driver for find_max.
{
constexpr int array[] = {2, 6, 8, 23, 45, 43, 51, 62, 83, 78, 61, 18, 71, 34, 72};
constexpr size_t size = sizeof(array) / sizeof(array[0]);
cout << "HIGHEST: " << find_max(array, size) << endl;
return EXIT_SUCCESS;
}
The call to find_max compiles to
mov esi, 83 | {
"domain": "codereview.stackexchange",
"id": 43060,
"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, recursion",
"url": null
} |
c++, algorithm, recursion
The call to find_max compiles to
mov esi, 83
This is why you always write your functions as constexpr when you can. In the real world, that can typically make a program run 33% faster. If you want to actually see the generated code, you can force the compiler to actually generate the code by making a call to some data it cannot constant-fold.
int main(void)
// Test driver for find_max.
{
#if 0
constexpr int array[] = {2, 6, 8, 23, 45, 43, 51, 62, 83, 78, 61, 18, 71, 34, 72};
constexpr size_t size = sizeof(array) / sizeof(array[0]);
#endif
extern const int array[];
extern const size_t size;
cout << "HIGHEST: " << find_max(array, size) << endl;
return EXIT_SUCCESS;
}
What this will tell you is that modern compilers don’t literally compile this as written. What they actually do is figure out for you that you are doing a reduction of the array with the max operation, which is associative and therefore can be automatically vectorized.
And, in fact, most code with loops or a tail-recursive accumulator aren’t supposed to literally iterate or recurse one element at the time. We actually want the compiler to notice that a vectorized or parallelized algorithm is equivalent to the specification we gave it.
But, there is a much more natural way to express this. Just say we want to perform a reduction operation on the array. In the STL, that’s <valarray>
#include <cstdlib> // for EXIT_SUCCESS
#include <iostream>
#include <valarray>
using std::cout, std::endl;
int main(void)
// Test driver for find_max.
{
const std::valarray array = {2, 6, 8, 23, 45, 43, 51, 62, 83, 78, 61, 18, 71, 34, 72};
cout << "HIGHEST: " << array.max() << endl;
return EXIT_SUCCESS;
} | {
"domain": "codereview.stackexchange",
"id": 43060,
"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, recursion",
"url": null
} |
python
Title: Calculate reservoir volume after rain falls
Question: I want to get better at commenting
# The current volume of a water reservoir (in cubic metres)
reservoir_volume = 4.445e8
# The amount of rainfall from a storm (in cubic meters)
rainfall = 5e6
# decrease the rainfall variable by 10% to account for runoff
rainfall -= (rainfall * 10/100) # First, you want to calculate
# how much of 10% of the 'rainfall' variable, then you subtract that
# from the actual value of the 'rainfall' variable. Finally, assign
# that value as the new value for the 'rainfall' variable.
# add the rainfall variable to the reservoir_volume variable
reservoir_volume += rainfall # Add both the 'reservoir_volume'
# variable and the 'rainfall' variable and then assign that to the
# 'reservoir_volume' variable as its new value
# increase reservoir_volume by 5% to account for stormwater that
# flows into the reservoir in the days following the storm
reservoir_volume += (reservoir_volume * (5 / 100)) #First, you calculate
# how much 5% of the value from the 'reservoir_volume' variable is. Then,
# you add that value to 'reservoir_volume' from the previous line and
# assign that new value to the 'reservoir_volume' variable
# decrease reservoir_volume by 5% to account for evaporation
reservoir_volume -= reservoir_volume * (5 / 100)
# we get the value of the 'reservoir_volume' from the previous line,
# then we multiply 5% to get the amount of water that got evaporated.
# After that, we subtract that water that got evaporated from the value of the
# 'reservoir_volume' variable. Finally, assign that new value for
# 'reservoir_volume' variable.
# subtract 2.5e5 cubic metres from reservoir_volume to account for water that's piped to arid regions.
reservoir_volume -= 2.5e5 #subtract 2.5e5 cubic metres from reservoir_volume to
# account for water that's piped to arid regions. After that, assign that
# value to be the new value for the 'reservoir_volume' variable. | {
"domain": "codereview.stackexchange",
"id": 43061,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python",
"url": null
} |
python
# print the new value of the reservoir_volume variable
print(reservoir_volume) # Going through that computation, we should get a value a float of 447627500.0
Answer: Your question is important because code writing is a form of technical
writing. Few software engineers view their craft explicitly in these terms,
and most software education focuses overwhelmingly on algorithms and data
structures, leaving effective technical writing as a kind of afterthought --
presumably as something that students will figure out through hard-earned
experience.
Comments are very useful. Contrary to the claims of some black-and-white
thinkers in our field -- who make claims like "the code should speak for
itself" or "comments are a code smell" -- comments are a vital tool in your
arsenal. Ignore anyone who says you shouldn't be writing comments at all.
Well-designed comments can enhance code readability in substantial ways.
But code is more important than comments. Even though comments are powerful
and vital, they are of secondary importance. The code matters most. The job of
comments is to enhance and clarify, not dominate. Your current comments invert
that relationship: the comments are so expansive that they undermine
readability. The trick is to find an effective balance.
Prefer named constants over explained values. Your current
code has magic values scattered throughout. When you do that you increase
the perceived need to elaborate on their meaning. A more effective strategy
is to give those values meaningful labels, in the form of constant names.
# Reservoir, rainfall, and irrigation volumes (cubic metres).
INITIAL_VOLUME = 4.445e8
RAINFALL = 5e6
IRRIGATION = 2.5e5
# Proportions of:
# - Rain diverted to runoff.
# - Reservoir increased by stormwater.
# - Reservoir decreased by evaporation.
RUNOFF_RATIO = 0.1
STORMWATER_RATIO = 0.05
EVAPORATION_RATIO = 0.05 | {
"domain": "codereview.stackexchange",
"id": 43061,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python",
"url": null
} |
python
Organize code in commented paragraphs. As illustrated above, if you group
related lines of code together -- and give the entities meaningful names -- you
can often achieve quite effective commenting in very few words. Each chunk of
code is an organized unit (a "paragraph") with a leading comment that tries to
convey the essential purpose of the code and to clarify any details that are
not already obvious from the code. The comments also play an important role in
allowing subsequent readers to scan the code very quickly, "speed-reading" the
code by quickly scanning the comments until they find the paragraph of
immediate concern.
Organize documents to aid navigation and readability. That organizational principle can be generalized to many
other forms of technical communication, such as sending
email or writing code reviews: organize the content so that
it's easy for the reader to navigate the document, skim
quickly, or even skip sections. Case in
point: most of my reviews on this website rely on a
similar technique, with bolded headlines attempting to announce
or summarize the key point of each paragraph.
In nearly all cases, put comments on their own lines. Comments
tacked on the end of code lines are usually less flexible and
require more ongoing maintenance as the code evolves over time
(there are exceptions to this rule, but they are fairly rare).
The ratio comments above are a good example: even though one
might be tempted to write these as line-trailing comments,
I usually find that readability and maintainability are better
when the comments sit at the top of each paragraph, on their own
lines.
With good organization and naming, the algorithm itself often needs little
explanation. The comment shown here does not add a lot of substance, but
that's OK. In this case, the comment mostly plays
two roles: (1) it reinforces the overall purpose
(computing volume after it rains); and (2) it supports
organizational goals by
maintaining the overall symmetry of a | {
"domain": "codereview.stackexchange",
"id": 43061,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python",
"url": null
} |
python
organizational goals by
maintaining the overall symmetry of a
document structured as commented paragraphs.
# Compute reservoir volume after a rain event.
reservoir = INITIAL_VOLUME + RAINFALL * (1 - RUNOFF_RATIO)
reservoir += reservoir * STORMWATER_RATIO
reservoir -= reservoir * EVAPORATION_RATIO
reservoir -= IRRIGATION
print(reservoir) | {
"domain": "codereview.stackexchange",
"id": 43061,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python",
"url": null
} |
python
Next steps. Start putting your code in functions. And consider
using argparse to parameterize the script rather than hardcoding all
of the values and ratios. | {
"domain": "codereview.stackexchange",
"id": 43061,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python",
"url": null
} |
javascript, performance
Title: JavaScript to click a button after a random number of seconds?
Question: I'm trying to optimize my JavaScript code to be a short as possible (this is just for fun). Any thoughts would be appreciated!
Basically, the script automatically clicks an "I'm still here" button on a website. To do that, it checks every 100 ms for the prompt (class .dialog-box), and if it sees it, it waits between 1 and 5 seconds and then clicks the "I'm here" button (class .here-button).
function delay(n){
return new Promise(function(resolve){
setTimeout(resolve,n);
});
}
let p=x => document.querySelector(x);
(async function() {
while(true){
await delay(100);
if(x=p(".dialog-box")) {
x.style.visibility = "hidden";
await delay(1e3+4e3*Math.random());
console.log(new Date().toLocaleTimeString() + ": Clicked");
p(".here-button").click();
}
}
})();
I'm going to run it through a minifier as well, but I'm curious if there are ways to make the code shorter?
Thanks in advance!
Answer: Nice using scientific notation to shave a character off those milliseconds.
Instead of using async and promises, you could just run an anonymous interval every 100ms. Each time the interval runs, it checks for the .dialog-box element. If it finds it, it stops searching until after it waits for 1–5 seconds and clicks the .here-button element—then resumes searching.
A human-friendly version
let searching = 1, getElement = selector => document.querySelector(selector)
setInterval(() => {
if (searching && getElement('.dialog-box')) {
searching = 0
setTimeout(() => {
getElement('.here-button').click()
searching = 1
}, 1e3 + 4e3 * Math.random())
}
}, 100) | {
"domain": "codereview.stackexchange",
"id": 43062,
"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, performance",
"url": null
} |
javascript, performance
Shortened variable names
let s = 1, e = s => document.querySelector(s)
setInterval(() => {
if (s && e('.dialog-box')) {
s = 0
setTimeout(() => {
e('.here-button').click()
s = 1
}, 1e3 + 4e3 * Math.random())
}
}, 100)
Minified (160 characters)
let s=1,e=s=>document.querySelector(s);setInterval(()=>{if(s&&e('.dialog-box')){s=0;setTimeout(()=>{e('.here-button').click();s=1},1e3+4e3*Math.random())}},100) | {
"domain": "codereview.stackexchange",
"id": 43062,
"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, performance",
"url": null
} |
python, design-patterns, library
Title: Number partitioning: how to allow both 'light' and 'heavy' output?
Question: I am working on a library for algorithms for multiway number partitioning.
One challenge I face is that some users need the entire partition, while other users need only the sums of the parts. For example, suppose the input is the following list: [1,2,3,3,5,9,9], and the goal is to partition them into two subsets. Then the entire partition could be [[9, 5, 2], [9, 3, 3, 1]], but if a user only needs the sums, then the output would be [16, 16]. In this case, it is a waste of time to maintain the lists.
Initially, I thought of writing two variants for each algorithm. For example, for the greedy number partitioning algorithm, I had:
def greedy_partition(numbins: int, items: List[float]):
"""
Partition the given items using the greedy number partitioning algorithm.
It return the entire partition, so it runs slower.
>>> greedy_partition(numbins=2, items=[1,2,3,3,5,9,9])
[[9, 5, 2], [9, 3, 3, 1]]
>>> greedy_partition(numbins=3, items=[1,2,3,3,5,9,9])
[[9, 2], [9, 1], [5, 3, 3]]
"""
bins = [[] for _ in range(numbins)]
for item in sorted(items, reverse=True):
index_of_least_full_bin = min(range(numbins), key=lambda i: sum(bins[i]))
bins[index_of_least_full_bin].append(item)
return bins
def greedy_sums(numbins: int, items: List[float]):
"""
Partition the given items using the greedy number partitioning algorithm.
It returns only the sums, so it runs much faster.
>>> greedy_sums(numbins=2, items=[1,2,3,3,5,9,9])
[16, 16]
>>> greedy_sums(numbins=3, items=[1,2,3,3,5,9,9])
[11, 10, 11]
"""
sums = [0 for _ in range(numbins)]
for item in sorted(items, reverse=True):
index_of_least_full_bin = min(range(numbins), key=lambda i: sums[i])
sums[index_of_least_full_bin] += item
return sums | {
"domain": "codereview.stackexchange",
"id": 43063,
"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, design-patterns, library",
"url": null
} |
python, design-patterns, library
This works, but the algorithm is duplicated. If I add more algorithms, I will have to write each of them twice.
EDIT: Of course, I can use only greedy_partition, and then take the sum of each part. But this is extremely inefficient when the number of items is large. For example, I tested both functions on increasing number of items, and got the following results (in seconds):
3 bins, 1000 items: greedy_partition=0.022589921951293945. greedy_sums=0.0010304450988769531.
3 bins, 10000 items: greedy_partition=2.2264041900634766. greedy_sums=0.013550519943237305.
3 bins, 20000 items: greedy_partition=9.81221604347229. greedy_sums=0.020364999771118164.
3 bins, 40000 items: greedy_partition=36.83849239349365. greedy_sums=0.04088854789733887.
My current solution is as follows. I defined an abstract class to handle the bins during the run:
class Bins(ABC):
def __init__(self, numbins: int):
self.num = numbins
@abstractmethod
def add_item_to_bin(self, item: float, bin_index: int):
pass
@abstractmethod
def result(self):
return None
I defined two sub-classes: one keeps only the sums, and the other keeps the partition too:
class BinsKeepingSums(Bins):
def __init__(self, numbins: int):
super().__init__(numbins)
self.sums = numbins*[0]
def add_item_to_bin(self, item: float, bin_index: int):
self.sums[bin_index] += item
def result(self):
return self.sums
class BinsKeepingContents(BinsKeepingSums):
def __init__(self, numbins: int):
super().__init__(numbins)
self.bins = [[] for _ in range(numbins)]
def add_item_to_bin(self, item: float, bin_index: int):
super().add_item_to_bin(item, bin_index)
self.bins[bin_index].append(item)
def result(self):
return self.bins | {
"domain": "codereview.stackexchange",
"id": 43063,
"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, design-patterns, library",
"url": null
} |
python, design-patterns, library
def result(self):
return self.bins
Now, I can write the algorithm only once, sending the desired Bins structure as parameter:
def greedy(bins: Bins, items: List[float]):
"""
Partition the given items using the greedy number partitioning algorithm.
Return the partition.
>>> greedy(bins=BinsKeepingSums(2), items=[1,2,3,3,5,9,9])
[16, 16]
>>> greedy(bins=BinsKeepingContents(2), items=[1,2,3,3,5,9,9])
[[9, 5, 2], [9, 3, 3, 1]]
"""
for item in sorted(items, reverse=True):
index_of_least_full_bin = min(range(bins.num), key=lambda i: bins.sums[i])
bins.add_item_to_bin(item, index_of_least_full_bin)
return bins.result()
Before I implement some more algorithms, I will be happy for feedback regarding this solution. Particularly, how to make it more simple, general, intuitive and efficient.
NOTE: I asked a different question on a similar topic here Greedy number partitioning algorithm
Answer: Summing the items seems like a special case of the partitioning problem.
So I would implement it as an operation on the return value of the partitioning:
def greedy_sums(numbins: int, items: list[float]) -> list[float]:
"""..."""
return [sum(items) for items in greedy_partition(numbins, items)]
Benefits:
No duplicated code
Code reuse
No complex classes | {
"domain": "codereview.stackexchange",
"id": 43063,
"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, design-patterns, library",
"url": null
} |
python, design-patterns, library
Benefits:
No duplicated code
Code reuse
No complex classes
Your worry about "needlessly" keeping the lists to me sounds like premature and possibly useless optimization.
I would worry about that if and only if you'll find significant performance drops in real-world application of the algorithms.
Performance
Your performance loss comes from a suboptimal implementation of your partitioning algorithm. You can improve it, by tracking the sums as keys:
def greedy_bins_and_sums(numbins: int, items: list[float]):
"""..."""
bins = [[] for _ in range(numbins)]
sums = [0] * numbins
for item in sorted(items, reverse=True):
index_of_least_full_bin = min(range(numbins), key=sums.__getitem__)
bins[index_of_least_full_bin].append(item)
sums[index_of_least_full_bin] += item
return bins, sums
You can verify that it produces the same results with:
@contextmanager
def perf_count():
start = perf_counter()
yield
print('Time:', perf_counter() - start)
def main():
for size in (1000, 10000, 40000):
lst = [randint(0, size) for _ in range(size)]
with perf_count():
parts1 = greedy_partition(3, lst)
with perf_count():
parts2, sums = greedy_bins_and_sums(3, lst)
print(parts1 == parts2)
Time: 0.006648327998846071
Time: 0.001240477999090217
True
Time: 0.5112279509994551
Time: 0.012690333998762071
True
Time: 8.914125162998971
Time: 0.058278149999750894
True | {
"domain": "codereview.stackexchange",
"id": 43063,
"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, design-patterns, library",
"url": null
} |
python, design-patterns, library
This way, you can provide the user directly with the partitions and their sums as the function now calculates both.
By using sums.__getitem__ you can get another small performance boost, since you spare one extra call to the wrapping lambda.
A custom data structure
If you prefer to use a custom data structure, another alternative would be to subclass list into a container that keeps track of its sums:
class Bin(list):
"""Represents a bin with tracked sum."""
def __init__(self):
super().__init__()
self.sum = 0
def append(self, item: float | int) -> None:
"""Adds an item and updates its sum."""
super().append(item)
self.sum += item
def greedy(numbins: int, items: list[float]) -> list[Bin]:
"""
Partition the given items using the greedy number partitioning algorithm.
>>> greedy_partition(numbins=2, items=[1,2,3,3,5,9,9])
[[9, 5, 2], [9, 3, 3, 1]]
>>> greedy_partition(numbins=3, items=[1,2,3,3,5,9,9])
[[9, 2], [9, 1], [5, 3, 3]]
"""
partitions = [Bin() for _ in range(numbins)]
for item in sorted(items, reverse=True):
min(partitions, key=lambda b: b.sum).append(item)
return partitions
This has the benefit, that users can still use the items like lists, but can also access its property sum to get the respective bin's sum without cost. | {
"domain": "codereview.stackexchange",
"id": 43063,
"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, design-patterns, library",
"url": null
} |
python, python-3.x
Title: Comparison function returning -1, 0 or +1
Question: I was solving this:
Write a compare function that returns 1 if x > y, 0 if x == y, and -1 if x < y.
Writing the code, it seemed that after the first if statement, either elif, else and if could be used. (I wrote examples on the code comments).
Which one is better and why? (Even if it's just to be closer to the best practices among programmers, I'm just starting out and I'd like to avoid bad habits, thank you!)
def compare(x,y):
if x > y:
return 1
elif x == y:
return 0
elif x < y:
return -1
# doubt: Why not use 'if' here instead of 'elif'? like:
# def compare(x,y):
# if x > y:
# return 1
# if x == y:
# return 0
# if x < y:
# return -1
# doubt: Why not make the last statement 'else' instead of 'elif'? like:
# def compare(x,y):
# if x > y:
# return 1
# elif{or 'if'?} x == y:
# return 0
# else:
# return -1
def compare_numbers():
x = int(input('value for x: '))
y = int(input('Value for y: '))
return compare(x,y)
print(compare_numbers()) | {
"domain": "codereview.stackexchange",
"id": 43064,
"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
print(compare_numbers())
Answer: Select the form of if-else that reinforces your intent. Your intention in
compare() is to make an exclusive categorization: greater than, equal to, or
less than. The appropriate structure for that situation is if-elif-else. Even
though, from a narrowly mathematical point of view, one could argue that
if-elif-elif or even if-if-if would "work" the same way in this particular
case, they convey the wrong message: they imply that some inputs might satisfy
none of the tests and therefore that the function could return None. Because
we know how numbers work, we know that won't happen in this specific case, but
you want to select the if-else style that reinforces your intent, not a
style that raises new questions. In a case this simple, I would express
if-elif-else like this, but that's mostly a code layout preference rather
than a strong opinion.
def compare(x, y):
return 1 if x > y else -1 if x < y else 0
Use a consistent indentation style. Four spaces or two spaces, not both. In my experience, four is most commonly used and recommended.
You should be using a main guard and validating user inputs. But you already know
that. | {
"domain": "codereview.stackexchange",
"id": 43064,
"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
} |
vba
Title: Best Way to Return a Value from a Function
Question: In my example, Method1 uses a variable to store the return values and then assigns the variable to the function. Method2 adds the return values directly to the function.
Questions:
What is the pattern of Method2 called?
Is one method prefered over the other and why?
Function Method1(FirstNumber As Long, LastNumber As Long) As Collection
Dim Map As New Collection
Dim n As Long
For n = FirstNumber To LastNumber
Method1.Add n
Next
Set Method1 = Map
End Function
Function Method2(FirstNumber As Long, LastNumber As Long) As Collection
Set Method2 = Collection
Dim n As Long
For n = FirstNumber To LastNumber
Method2.Add n
Next
End Function
Addendum
Could someone explain the votes to close the question? I have written well over 50 of these types of functions this year alone. Not to mention that as a contributor to SO, I feel like hearing from other developers opinions on the subject will help me improve my answers.
Feel free to down vote and vote to close the question again for me commenting in my post.
Edit 1
There was a typo in my original code. This is how Method1 should have been written.
Function Method1(FirstNumber As Long, LastNumber As Long) As Collection
Dim Map As New Collection
Dim n As Long
For n = FirstNumber To LastNumber
Map.Add n
Next
Set Method1 = Map
End Function
I restored my original post and added this edit for clarification.
Answer: Method 1 is marginally (really barely) less efficient because of the additional variable. However Method 2 sometimes doesn't do what you might want (/expect):
Function Method2(LastNumber As Long) As Collection
Set Method2 = New Collection
Dim n As Long
For n = 1 To LastNumber
Method2.Add n
Next
'print the first item from the collection for logging
Debug.Print Method2(1) 'Stack Overflow?!
End Function | {
"domain": "codereview.stackexchange",
"id": 43065,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "vba",
"url": null
} |
vba
Or
Function Method2(Optional ByVal LastNumber As Long = 5) As Collection
Set Method2 = New Collection
Dim n As Long
For n = 1 To LastNumber
add_n Method2(), n 'blink and you miss it, not the most obvious error
Next
End Function
Sub add_n(ByVal coll As Collection, ByVal n As Long)
coll.Add n
End Sub
It's just a bit higher risk; confusing a variable with a function call. That makes Method 1 better in my book unless you are doing something performance critical or a one-liner (e.g. I would assign directly to the function name if I'm doing low level stuff with pointers and API calls)
I call the return variable result which encourages me not to forget to assign it to the function name at the end
Even weirder error:
Function Method2(LastNumber As Long) As Scripting.Dictionary
Set Method2 = New Dictionary
Dim n As Long
Method2(1) = "First value" 'Argument not optional error, try work that one out
For n = 2 To LastNumber
Method2.Add n, n
Next
End Function | {
"domain": "codereview.stackexchange",
"id": 43065,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "vba",
"url": null
} |
java, functional-programming
Title: A Union Data Type
Question: Introduction
I'm trying to get familiar with functional programming by implementing some functional concepts.
One of these concepts that I've attempted to implement below is a Union data type (or more specifically, a Union2, to indicate that it's a union of two values as a union data type can represent many values).
I know there is an Either data type but I don't think it's appropriate to use the Either data type in the case of a Union2 because at least from my understanding, there's an implication of "correctness" when it comes to the Left value vs. the Right value. In more concrete terms, a filter method might make sense on an Either but I would argue would not make sense on a Union2.
Use Case
I've seen this occur in legacy systems where there are two different types of unique identifiers for a given entity - like a UUID and, say, an integer primary key.
You can imagine this system might have an API method like getEntityByIdentifier that takes a Union2 of UUID and Integer and returns an Optional<Entity>
Optional<Entity> getEntityByIdentifier(Union2<UUID, Integer> identifier) {
return identifier.fold(
uuid -> getByUUID(uuid),
primaryKey -> getByPrimaryKey(primaryKey)
);
}
Implementation
public class Union2<T1, T2> {
private final Optional<T1> _1;
private final Optional<T2> _2;
Union2(final T1 _1, final T2 _2) {
this._1 = Optional.ofNullable(_1);
this._2 = Optional.ofNullable(_2);
if (this._1.isEmpty() && this._2.isEmpty()) {
throw new IllegalArgumentException("Union must contain a non-null value");
}
if (this._1.isPresent() && this._2.isPresent()) {
throw new IllegalArgumentException("Union contains two non-null values");
}
}
public static <T1, T2> Union2<T1, T2> _1(final T1 _1) {
return new Union2<>(_1, null);
} | {
"domain": "codereview.stackexchange",
"id": 43066,
"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, functional-programming",
"url": null
} |
java, functional-programming
public static <T1, T2> Union2<T1, T2> _2(final T2 _2) {
return new Union2<>(null, _2);
}
public <R> Union2<R, T2> map1(
final Function<T1, R> mapper1
) {
return map(
mapper1,
Function.identity()
);
}
public <R> Union2<T1, R> map2(
final Function<T2, R> mapper2
) {
return map(
Function.identity(),
mapper2
);
}
public <R1, R2> Union2<R1, R2> map(
final Function<T1, R1> mapper1,
final Function<T2, R2> mapper2
) {
return fold(
(_1) -> Union2._1(mapper1.apply(_1)),
(_2) -> Union2._2(mapper2.apply(_2))
);
}
public <R> R fold(
final Function<T1, R> mapper1,
final Function<T2, R> mapper2
) {
return _1
.map(mapper1)
.orElseGet(
() -> _2
.map(mapper2)
.orElseThrow(() -> new RuntimeException("All values are null"))
);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Union2<?, ?> union = (Union2<?, ?>) o;
return Objects.equals(_1, union._1) && Objects.equals(_2, union._2);
}
@Override
public int hashCode() {
return Objects.hash(_1, _2);
}
@Override
public String toString() {
return "Union{" +
"_1=" + _1 +
", _2=" + _2 +
'}';
}
}
Discussion
Does the implementation / use-case make sense?
Am I missing any potentially useful methods?
I've represented the underlying data as Optionals and made the decision to trade a slight increase in memory so I could use the more functional interface presented by Optionals. | {
"domain": "codereview.stackexchange",
"id": 43066,
"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, functional-programming",
"url": null
} |
java, functional-programming
Answer: For the record
Here's the official opinion on using Optionals instead of if-statements: https://stackoverflow.com/a/26328555 Our intention was to provide a limited mechanism for library method return types where there needed to be a clear way to represent "no result", and using null for such was overwhelmingly likely to cause errors.
Here's the reason why Java does not have a generic Pair data type and I think similar wisdom can be applied here too: https://stackoverflow.com/a/156685 The main argument is that a class Pair doesn't convey any semantics about the relationship between the two values
Review
The specific use case is a design error and in my opinion should not be solved with a generic solution, as generic solutions tend to leak out and encourage the implementation of more design errors elsewhere.
Having a non-private constructor along with the static initializers forces you to do unnecessary error checking to ensure the correctness of the state of the instance. Is there a reason why the class is not final? The implmentation of the operations are pretty much set in stone so allowing subclassing only introduces the possibility for the subclass to break the contract of the fold and map methods. I would rather make the class final, make the constructor private and rely on the static initializers to not allow construction with invalid parameters.
Style wise, if the input parameter checking needs to stay in the constructor, I would rather first check that the constructor parameters are correct before assigning them to instance variables just to avoid any possibility of invalid object state. But since you've deliberately chosen to absolutely never write an if-statement, I suppose that this is what you need to do :).
Numbers as field names force you to do unconventional naming (the underscore prefix) which is very confusing. Just use a and b. They're just as uninformative but at least they don't break naming conventions. | {
"domain": "codereview.stackexchange",
"id": 43066,
"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, functional-programming",
"url": null
} |
java, functional-programming
There is nothing wrong with if-statements and null-checks. | {
"domain": "codereview.stackexchange",
"id": 43066,
"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, functional-programming",
"url": null
} |
javascript, geospatial
Title: Modify polyline vertices
Question: I have an ArcGIS Arcade script that uses JavaScript syntax.
The script loops through GIS polylines and updates a coordinate.
The coordinate is called an "M" coordinate (aka a "Measure-value"). M coordinates are similar to X and Y coordinates, but are used for specialized linear referencing purposes.
//var geom = Dictionary(Text(Geometry($feature)));
//var paths = geom['paths'];
var paths = [[[0,5,null],[10,10, null],[30,0, null],[50,10, null],[60,10, null]]] //input data for Code Review testing purposes
var geom_updated = false;
var length = 0;
for (var path_idx in paths) {
for (var vertex_idx in paths[path_idx]) {
//Set the first vertex's M-value to 0.
if (vertex_idx == 0) {
paths[0][0][-1] = 0;
geom_updated = true;
//For the rest of the vertices, set the M-value to the cumulative length of the line.
} else {
//Set the startpoint and endpoint of the current segment of the polyline.
//Note: The geometry type, and its subtypes (Point and Polyline) are immutable: https://community.esri.com/t5/arcgis-pro-questions/are-arcade-geometry-subtypes-immutable-i-e-point/m-p/1150097#M52278
var startpoint = Point({ 'x': paths[path_idx][vertex_idx - 1][0], 'y': paths[path_idx][vertex_idx - 1][1], 'spatialReference': { 'wkid': 26917 } });
var endpoint = Point({ 'x': paths[path_idx][vertex_idx][0], 'y': paths[path_idx][vertex_idx][1], 'spatialReference': { 'wkid': 26917 } }); | {
"domain": "codereview.stackexchange",
"id": 43067,
"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, geospatial",
"url": null
} |
javascript, geospatial
//The Distance() function returns the planar distance between two geometries in the given units. This is a planar measurement using Cartesian mathematics. https://developers.arcgis.com/arcade/function-reference/geometry_functions/#distance
//I think the Pythagorean theorem would produce the same result: https://stackoverflow.com/questions/20916953/get-distance-between-two-points-in-canvas
length = length + Distance(startpoint, endpoint);
paths[path_idx][vertex_idx][-1] = length;
geom_updated = true;
}
}
}
if (!geom_updated) {
return
}
return {
//"result": {"geometry": Polyline(geom)}
"result": { "geometry": paths }
};
//Output: [[[0,5,0],[10,10,11.18],[30,0,33.54],[50,10,55.90],[60,10,65.90]]]
Related: ArcGIS Arcade Function Reference
How can the script be improved?
Answer: I rewrote your script to the code below:
function pythagoras(x1, y1, x2, y2)
{
return Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2));
}
//input data for Code Review testing purposes
var paths = [[[0,5,null],[10,10, null],[30,0, null],[50,10, null],[60,10, null]]];
for (const path of paths) {
let oldX = path[0][0], oldY = path[0][1], length = 0;
for (const point of path) {
let newX = point[0], newY = point[1];
length += pythagoras(oldX, oldY, newX, newY);
point[2] = length;
oldX = newX;
oldY = newY;
}
}
console.log(paths); | {
"domain": "codereview.stackexchange",
"id": 43067,
"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, geospatial",
"url": null
} |
javascript, geospatial
console.log(paths);
I did away with your Point() and Distance() because I don't have them. I think you can extract something useful from this.
Your code isn't very different. I still use two nested loops, which is inevitable, I think. Some people will try to remove the loops and replace them by array functions, but they do basically the same while hiding the loops. This is more honest. The outer loop, loops over the paths, and the inner loop over the points in each path. As you can see I use two temporary points; The "old" and "new", and compute the distance between them. That is added to an existing "length" and stored with each point.
The output is:
[[[0, 5, 0],
[10, 10, 11.180339887498949],
[30, 0, 33.54101966249685],
[50, 10, 55.90169943749475],
[60, 10, 65.90169943749476]]]
Instead of working with (x,y) coordinates, I could also work with points, like this:
function pythagoras(p1, p2)
{
return Math.sqrt(Math.pow(p2[0] - p1[0], 2) + Math.pow(p2[1] - p1[1], 2));
}
//input data for Code Review testing purposes
var paths = [[[0,5,null],[10,10, null],[30,0, null],[50,10, null],[60,10, null]]];
for (const path of paths) {
let oldPoint = path[0], length = 0;
for (const newPoint of path) {
length += pythagoras(oldPoint, newPoint);
point[2] = length;
oldPoint = newPoint;
}
}
console.log(paths);
This is slightly easier to read, but basically does exactly the same. | {
"domain": "codereview.stackexchange",
"id": 43067,
"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, geospatial",
"url": null
} |
c#, linq
Title: Is there a way to use lambda function to get the list?
Question: I have a data set.
public class EmployeeRepository
{
public static List<Employee> AllEmployees()
{
var loc1 = new List<Location> { new Location { City = "Gretna", State = "VA", ZipCode = "24587" }, new Location { City = "Charlotte", State = "NC", ZipCode = "28012" } };
var loc2 = new List<Location> { new Location { City = "Boston", State = "MA", ZipCode = "02333" }, new Location { City = "Waldham", State = "MA", ZipCode = "02323" } };
var loc3 = new List<Location> { new Location { City = "Greenville", State = "NC", ZipCode = "29011" }};
var loc4 = new List<Location> { new Location { City = "Greenville", State = "SC", ZipCode = "26000" }, new Location { City = "Charleston", State = "SC", ZipCode = "26011" } };
return new List<Employee>()
{
new Employee {Id = 1, Department = new Department{Id = 1, Name = "Technology" }, Locations = loc1 },
new Employee {Id = 2, Department = new Department{Id = 1, Name = "Technology" }, Locations = loc2},
new Employee {Id = 3, Department = new Department{Id = 1, Name = "Technology" }, Locations = loc3 },
new Employee {Id = 4, Department = new Department{Id = 2, Name = "IT" }, Locations = loc4 },
new Employee {Id = 5, Department = new Department{Id = 2, Name = "IT" }, Locations = loc4 },
new Employee {Id = 6, Department = new Department{Id = 3, Name = "Sales" }, Locations = loc3 },
new Employee {Id = 7, Department = new Department{Id = 3, Name = "Sales" }, Locations = loc2},
new Employee {Id = 9, Department = new Department{Id = 4, Name = "Marketing" }, Locations = loc2 },
new Employee {Id = 9, Department = new Department{Id = 4, Name = "Marketing" }, Locations = loc1 },
};
}
} | {
"domain": "codereview.stackexchange",
"id": 43068,
"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#, linq",
"url": null
} |
c#, linq
Now I want to return all locations if the department name is given.
My code is working
public List<Location> GetLocations(string name)
{
List<Location> locations = new List<Location>();
var collection = EmployeeRepository.AllEmployees();
var temp = (from e in collection where e.Department.Name == name select e);
foreach(var item in temp)
{
locations.AddRange(item.Locations);
}
return locations.Distinct().ToList();
}
But is there a better way in one linq query/method to do that?
UPDATE:
public class Employee
{
public int Id { get; set; }
public Department Department { get; set; }
public List<Location> Locations { get; set; }
public decimal Salary { get; set; }
}
public class Location
{
public string City { get; set; }
public string State { get; set; }
public string ZipCode { get; set; }
}
public class Department
{
public int Id { get; set; }
public string Name { get; set; }
}
Answer: Consider using records since none of your data change.
Consider using target typing so that your list initialisation is more terse.
Don't foreach - Linq indeed has in-built support for this.
Suggested
namespace StackExchange.EmployeeExample;
public record Department(
int Id,
string Name
) {}
public record Location(
string City,
string State,
string ZipCode
) {}
public record Employee(
int Id,
Department Department,
List<Location> Locations,
decimal? Salary = null
) {} | {
"domain": "codereview.stackexchange",
"id": 43068,
"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#, linq",
"url": null
} |
c#, linq
public class EmployeeRepository
{
public static List<Employee> AllEmployees
{
get
{
var loc1 = new List<Location>
{
new(City: "Gretna", State: "VA", ZipCode: "24587"),
new(City: "Charlotte", State: "NC", ZipCode: "28012"),
};
var loc2 = new List<Location>
{
new(City: "Boston", State: "MA", ZipCode: "02333"),
new(City: "Waldham", State: "MA", ZipCode: "02323"),
};
var loc3 = new List<Location>
{
new(City: "Greenville", State: "NC", ZipCode: "29011"),
};
var loc4 = new List<Location>
{
new(City: "Greenville", State: "SC", ZipCode: "26000"),
new(City: "Charleston", State: "SC", ZipCode: "26011"),
};
return new List<Employee>()
{
new(Id: 1, Department: new Department(Id: 1, Name: "Technology"), Locations: loc1),
new(Id: 2, Department: new Department(Id: 1, Name: "Technology"), Locations: loc2),
new(Id: 3, Department: new Department(Id: 1, Name: "Technology"), Locations: loc3),
new(Id: 4, Department: new Department(Id: 2, Name: "IT"), Locations: loc4),
new(Id: 5, Department: new Department(Id: 2, Name: "IT"), Locations: loc4),
new(Id: 6, Department: new Department(Id: 3, Name: "Sales"), Locations: loc3),
new(Id: 7, Department: new Department(Id: 3, Name: "Sales"), Locations: loc2),
new(Id: 9, Department: new Department(Id: 4, Name: "Marketing"), Locations: loc2),
new(Id: 9, Department: new Department(Id: 4, Name: "Marketing"), Locations: loc1),
};
}
} | {
"domain": "codereview.stackexchange",
"id": 43068,
"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#, linq",
"url": null
} |
c#, linq
public static List<Location> GetLocations(string departmentName) =>
AllEmployees
.Where(e => e.Department.Name == departmentName)
.SelectMany(e => e.Locations)
.Distinct()
.ToList();
public static void Main()
{
var result = GetLocations("Technology");
}
} | {
"domain": "codereview.stackexchange",
"id": 43068,
"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#, linq",
"url": null
} |
python, beginner
Title: An electron configuration writer given the number of electrons
Question: I'm new to programming, especially Python (started in python3) and I want to ask if this piece of code is good enough or not. This is part of my personal project, that is, to make a personal library on chemistry. Also, if this is allowed, I want to ask if, for the following code, lookup is better than calculation.
This is a function that can give either the full or compact electron configuration given the number of electrons (electrons). In this function, the full configuration depends on the compact configuration.
To get the compact configuration, the greatest number of electrons in the inert elements less than the given number of electrons is found (inert_number). The 'position' of the writer with respect to the subshells is determined based on inert_number (subshell_index). From subshell_index, the number of electrons per subshells is given (base). Subtracting inert_number from electrons, we have copy. A loop will start which will end if base >= copy. The result will be a list starting with the atomic symbol of the element in square brackets (inert_head), followed by the remaining electrons in subshells. The exceptions to this are the elements with unusual configurations where their configurations are found through a lookup and the first two elements whose compact configurations do not start with an atomic symbol.
To get the full configuration, the compact configuration will be taken first. While the first element of the configuration is an atomic symbol, the process will be recursive. The first element will be taken, making a lookup to get the atomic number and the compact configuration will be found. The results of this will be appended to get the full configuration.
inerts_number = [2, 10, 18, 36, 54, 86, 118]
inerts_config_index = [1, 3, 5, 8, 11, 15, 19] | {
"domain": "codereview.stackexchange",
"id": 43069,
"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, beginner",
"url": null
} |
python, beginner
atomic_symbols = [
"H", "He", "Li", "Be", "B", "C", "N", "O", "F", "Ne",
"Na", "Mg", "Al", "Si", "P", "S", "Cl", "Ar", "K", "Ca",
"Sc", "Ti", "V", "Cr", "Mn", "Fe", "Co", "Ni", "Cu", "Zn",
"Ga", "Ge", "As", "Se", "Br", "Kr", "Rb", "Sr", "Y", "Zr",
"Nb", "Mo", "Tc", "Ru", "Rh", "Pd", "Ag", "Cd", "In", "Sn",
"Sb", "Te", "I", "Xe", "Cs", "Ba", "La", "Ce", "Pr", "Nd",
"Pm", "Sm", "Eu", "Gd", "Tb", "Dy", "Ho", "Er", "Tm", "Yb",
"Lu", "Hf", "Ta", "W", "Re", "Os", "Ir", "Pt", "Au", "Hg",
"Tl", "Pb", "Bi", "Po", "At", "Rn", "Fr", "Ra", "Ac", "Th",
"Pa", "U", "Np", "Pu", "Am", "Cm", "Bk", "Cf", "Es", "Fm",
"Md", "No", "Lr", "Rf", "Db", "Sg", "Bh", "Hs", "Mt", "Ds",
"Rg", "Cn", "Nh", "Fl", "Mc", "Lv", "Ts", "Og"]
elems_with_odd_configs = [
24, 29, 41, 42, 44,
45, 46, 47, 57, 58,
64, 78, 79, 89, 90,
91, 92, 93, 96]
configs_of_odds = [
["[Ar]", 1, 5],
["[Ar]", 1, 10],
["[Kr]", 1, 4],
["[Kr]", 1, 5],
["[Kr]", 1, 7],
["[Kr]", 1, 8],
["[Kr]", 0, 10],
["[Kr]", 1, 10],
["[Xe]", 2, 0, 1],
["[Xe]", 2, 1, 1],
["[Xe]", 2, 7, 1],
["[Xe]", 1, 14, 9],
["[Xe]", 1, 14, 10],
["[Rn]", 2, 0, 1],
["[Rn]", 2, 0, 2],
["[Rn]", 2, 2, 1],
["[Rn]", 2, 3, 1],
["[Rn]", 2, 4, 1],
["[Rn]", 2, 7, 1]]
subshell_value = [
2, 2, 6, 2, 6,
2, 10, 6, 2, 10,
6, 2, 14, 10, 6,
2, 14, 10, 6]
def electron_config(electrons: int, config_type: str = 'compact') -> list:
def __compact_config(electrons: int) -> list:
electron_config = []
inert_number = 0
subshell_index = 0
if electrons > 2:
inert_number = max([x for x in inerts_number if x < electrons])
subshell_index = inerts_config_index[inerts_number.index(inert_number)]
inert_head = f'[{atomic_symbols[inert_number - 1]}]'
electron_config.append(inert_head)
else:
inert_number = 0 | {
"domain": "codereview.stackexchange",
"id": 43069,
"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, beginner",
"url": null
} |
python, beginner
if electrons in elems_with_odd_configs:
return configs_of_odds[elems_with_odd_configs.index(electrons)]
else:
copy = electrons - inert_number
if electrons > 2:
index = subshell_index
else:
copy = electrons
index = 0
while True:
base = subshell_value[index]
if base < copy:
electron_config.append(base)
copy -= base
index += 1
else:
if copy > 0:
electron_config.append(copy)
break
return electron_config
def __full_config(electrons: int) -> list:
temp_config = []
compact_config = __compact_config(electrons)
inert_elem = ''
if electrons > 2:
inert_elem = str(compact_config[0]).removeprefix('[').removesuffix(']')
inert_electrons = atomic_symbols.index(inert_elem) + 1
if inert_elem in ['He', 'Ne', 'Ar', 'Kr', 'Xe', 'Rn']:
temp_config = __full_config(inert_electrons) + compact_config[1:]
else:
temp_config = __compact_config(electrons)
return temp_config
if config_type == 'compact':
return __compact_config(electrons)
elif config_type == 'full':
return __full_config(electrons)
else:
raise ValueError(f'Expected \'compact\' or \'full\', received {config_type} instead') | {
"domain": "codereview.stackexchange",
"id": 43069,
"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, beginner",
"url": null
} |
python, beginner
An alternative way I did was to add inert_number and subshell_index as optional parameters to __compact_config with None as default values. If both are None, proceed as usual. Then, to get the full configuration, __compact_config will be called and inert_number = 0, subshell_index = 0. This will be the changes:
...
def __compact_config(electrons: int, inert_number: int = None, subshell_index: int = None) -> list:
...
if inert_number is None and subshell_index is None:
if electrons > 2:
inert_number = max([x for x in inerts_number if x < electrons])
subshell_index = inerts_config_index[inerts_number.index(inert_number)]
inert_head = f'[{atomic_symbols[inert_number - 1]}]'
electron_config.append(inert_head)
else:
inert_number = 0
...
def __full_config(electrons: int) -> list:
return __compact_config(electrons, inert_number = 0, subshell_index = 0)
In __full_config, is it better to use the recursive way to show what the 'usual' way is when finding the electron configuration, or start from the first subshell using the writer from __compact_config? | {
"domain": "codereview.stackexchange",
"id": 43069,
"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, beginner",
"url": null
} |
python, beginner
Answer: Your database literals (atomic_symbols, etc.) should all be tuples () instead of lists [] for immutability. However, as I show below, some are better-suited to dictionaries instead of sequences.
Your electron_config function is really just two functions: one for compact, and one for full. If you were to keep them as one function, config_type should not be hinted as str, but as Literal['compact', 'full']. But the two halves share no logic. Better to extract your two inner functions as outer functions. Also, those inner functions - since they were in function scope - are never visible to the outside, currently, so there's no point in prefixing them with underscores.
inert_elem in ['He', 'Ne', 'Ar', 'Kr', 'Xe', 'Rn'] should use a set literal {}, and that literal should be moved to the same location as your other database constants.
This:
.removeprefix('[').removesuffix(']')
is evidence that you have premature formatting on your element name. I don't see why you would surround the element name in brackets at all, but if you must, it should be done later in a formatting function.
Your return format is strange: it's "maybe" a string, followed by a list of integers. Best to separate this into a
tuple[
Optional[str],
list[int]
] | {
"domain": "codereview.stackexchange",
"id": 43069,
"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, beginner",
"url": null
} |
python, beginner
or, better, replace the list with a generator and don't successive-append().
Add unit tests. I've only shown regression tests.
Some of your data structure patterns are non-ideal. For instance, elems_with_odd_configs should really just be the keys of configs_of_odds refactored as a dictionary. Your max search is also not ideal, and should be replaced with a call to bisect_left to find the closest appropriate value in logarithmic instead of linear time (though the performance will not be noticeable given how small the sequence is). Avoid .index() when possible.
Rather than maintaining your own index into SUBSHELL_VALUE, just iterate base over a slice.
A light refactor covering some of the above is
from typing import Optional, Iterable, Iterator
from bisect import bisect_left
INERTS_CONFIG_INDEX = (1, 3, 5, 8, 11, 15, 19)
INERTS_NUMBER = (2, 10, 18, 36, 54, 86, 118)
ATOMIC_SYMBOLS = (
'H', 'He', 'Li', 'Be', 'B', 'C', 'N', 'O', 'F', 'Ne',
'Na', 'Mg', 'Al', 'Si', 'P', 'S', 'Cl', 'Ar', 'K', 'Ca',
'Sc', 'Ti', 'V', 'Cr', 'Mn', 'Fe', 'Co', 'Ni', 'Cu', 'Zn',
'Ga', 'Ge', 'As', 'Se', 'Br', 'Kr', 'Rb', 'Sr', 'Y', 'Zr',
'Nb', 'Mo', 'Tc', 'Ru', 'Rh', 'Pd', 'Ag', 'Cd', 'In', 'Sn',
'Sb', 'Te', 'I', 'Xe', 'Cs', 'Ba', 'La', 'Ce', 'Pr', 'Nd',
'Pm', 'Sm', 'Eu', 'Gd', 'Tb', 'Dy', 'Ho', 'Er', 'Tm', 'Yb',
'Lu', 'Hf', 'Ta', 'W', 'Re', 'Os', 'Ir', 'Pt', 'Au', 'Hg',
'Tl', 'Pb', 'Bi', 'Po', 'At', 'Rn', 'Fr', 'Ra', 'Ac', 'Th',
'Pa', 'U', 'Np', 'Pu', 'Am', 'Cm', 'Bk', 'Cf', 'Es', 'Fm',
'Md', 'No', 'Lr', 'Rf', 'Db', 'Sg', 'Bh', 'Hs', 'Mt', 'Ds',
'Rg', 'Cn', 'Nh', 'Fl', 'Mc', 'Lv', 'Ts', 'Og',
) | {
"domain": "codereview.stackexchange",
"id": 43069,
"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, beginner",
"url": null
} |
python, beginner
CONFIGS_OF_ODDS = {
24: ('Ar', (1, 5)),
29: ('Ar', (1, 10)),
41: ('Kr', (1, 4)),
42: ('Kr', (1, 5)),
44: ('Kr', (1, 7)),
45: ('Kr', (1, 8)),
46: ('Kr', (0, 10)),
47: ('Kr', (1, 10)),
57: ('Xe', (2, 0, 1)),
58: ('Xe', (2, 1, 1)),
64: ('Xe', (2, 7, 1)),
78: ('Xe', (1, 14, 9)),
79: ('Xe', (1, 14, 10)),
89: ('Rn', (2, 0, 1)),
90: ('Rn', (2, 0, 2)),
91: ('Rn', (2, 2, 1)),
92: ('Rn', (2, 3, 1)),
93: ('Rn', (2, 4, 1)),
96: ('Rn', (2, 7, 1)),
}
SUBSHELL_VALUE = (
2, 2, 6, 2, 6,
2, 10, 6, 2, 10,
6, 2, 14, 10, 6,
2, 14, 10, 6,
)
INERT_ELEMS = {
'He', 'Ne', 'Ar', 'Kr', 'Xe', 'Rn',
}
def generate_electrons(index: int, copy: int) -> Iterator[int]:
for base in SUBSHELL_VALUE[index:]:
if base >= copy:
if copy > 0:
yield copy
break
yield base
copy -= base
def make_compact_config(electrons: int) -> tuple[
Optional[str], # inert head
Iterable[int], # electron counts
]:
odd_config = CONFIGS_OF_ODDS.get(electrons)
if odd_config is not None:
return odd_config
if electrons <= 2:
return None, generate_electrons(index=0, copy=electrons)
inert_index = bisect_left(INERTS_NUMBER, electrons) - 1
inert_number = INERTS_NUMBER[inert_index]
subshell_index = INERTS_CONFIG_INDEX[inert_index]
inert_head = ATOMIC_SYMBOLS[inert_number - 1]
return inert_head, generate_electrons(index=subshell_index, copy=electrons - inert_number)
def make_full_config(electrons: int) -> Iterator[int]:
inert_elem, compact_config = make_compact_config(electrons)
if electrons > 2:
inert_electrons = ATOMIC_SYMBOLS.index(inert_elem) + 1
if inert_elem in INERT_ELEMS:
yield from make_full_config(inert_electrons)
yield from compact_config | {
"domain": "codereview.stackexchange",
"id": 43069,
"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, beginner",
"url": null
} |
python, beginner
yield from compact_config
def test() -> None:
inert_head, config = make_compact_config(1)
assert inert_head is None
assert tuple(config) == (1,)
inert_head, config = make_compact_config(10)
assert inert_head == 'He'
assert tuple(config) == (2, 6)
inert_head, config = make_compact_config(42)
assert inert_head == 'Kr'
assert tuple(config) == (1, 5)
inert_head, config = make_compact_config(100)
assert inert_head == 'Rn'
assert tuple(config) == (2, 12)
assert tuple(make_full_config(1)) == (1,)
assert tuple(make_full_config(10)) == (2, 2, 6)
assert tuple(make_full_config(42)) == (2, 2, 6, 2, 6, 2, 10, 6, 1, 5)
assert tuple(make_full_config(100)) == (2, 2, 6, 2, 6, 2, 10, 6, 2, 10, 6, 2, 14, 10, 6, 2, 12)
if __name__ == '__main__':
test() | {
"domain": "codereview.stackexchange",
"id": 43069,
"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, beginner",
"url": null
} |
beginner, c, linked-list
Title: C - Linked List Practice
Question: Been studying data structures in C to get more grasp on the fundamentals as a freshman at uni. This is a coding-challenge that I've given to myself to understand Linked Lists better.
Basically, my aim was to create 2 nodes, along with the node.header that i've written, which has the functions to add nodes to the head, body, or tail of the list.
And another function in that header to combine these two linked lists together into one.
How can I get this code better, do you see any mistakes or improvements that can be done with the working code? I think I got a better grasp on pointers more after coding this and planning to go deeper.
The code is already working, though there are bugs that I still am working on understanding pointers more and memory allocation,
such as free() function when used in the header gets my program go wild and not setting nextptr as null, i've mentioned this because they are commented in the code, as not working.
Main.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "node.h"
void modify_nodes(struct node *list,struct node **head);
void create_nodes(struct node **head);
int main(){
struct node *head = NULL;
create_nodes(&head);
puts("You're modifying the First one");
modify_nodes(head,&head);
struct node *head2 = NULL;
create_nodes(&head2);
puts("You're modifying the Second one");
modify_nodes(head2,&head2);
concatenate_lists(&head2,&head);
print_list(head); //head2 doesnt work out here because i can't check out if there is a previous node or not.
}
void modify_nodes(struct node *list,struct node **head){
enum choose_menu menu;
int input_value; | {
"domain": "codereview.stackexchange",
"id": 43070,
"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, linked-list",
"url": null
} |
beginner, c, linked-list
printf("To Add a Node to the Head, Press 1\n"
"To Add a Node to the Middle, Press 2\n"
"To Add a Node to the End, Press 3\n"
"To Finish the process, Press 0\n\n"
);
scanf("%d",&input_value);
while(input_value != END_OPERATION){
scanf("%d",&input_value);
if(input_value == ADD_HEAD){
add_node_head(&list);
}else if(input_value == ADD_MIDDLE){
puts("Please enter at which place you want your node to be...");
scanf("%d",&input_value);
add_node_middle(&list,input_value);
}else if(input_value == ADD_LAST){
add_node_last(&list);
}
}
*head = list;
}
void create_nodes(struct node **head){
(*head) = (struct node*)malloc(sizeof(struct node));
(*head)->value = 'x';
(*head)->nextPtr = NULL;
}
node.h
#ifndef NODE_H_INCLUDED
#define NODE_H_INCLUDED
enum choose_menu{ADD_HEAD = 1, ADD_MIDDLE = 2, ADD_LAST = 3, END_OPERATION = 0};
struct node{
char value;
struct node *nextPtr;
};
void print_list(struct node *firstNode){
while(firstNode != NULL){
printf("%c--->",firstNode->value);
firstNode = firstNode->nextPtr;
}
printf("NULL");
}
void add_node_head(struct node **head){
struct node *add = NULL;
add = (struct node*)malloc(sizeof(struct node));
add->value = 'a';
add->nextPtr = *head;
*head = add;
//free(add);
}
void add_node_last(struct node **head){
struct node *new_ = NULL;
new_ = (struct node*)malloc(sizeof(struct node));
new_->nextPtr=NULL;
new_->value = 'b';
struct node *temp;
temp = (struct node*)malloc(sizeof(struct node));
temp = *head;
while(temp->nextPtr != NULL){
temp = temp->nextPtr;
}
temp->nextPtr = new_;
/* free(temp);
free(new_);*/
} | {
"domain": "codereview.stackexchange",
"id": 43070,
"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, linked-list",
"url": null
} |
beginner, c, linked-list
void add_node_middle(struct node **head,int position){
struct node *newNode;
newNode = (struct node*)malloc(sizeof(struct node));
newNode->value = 'c';
struct node *temp = *head;
for(int i=2; i<position; i++){
if(temp->nextPtr != NULL){
temp = temp->nextPtr;
}
}
newNode->nextPtr = temp->nextPtr;
temp->nextPtr = newNode;
//free(newNode);
}
void concatenate_lists(struct node **adding,struct node **beginning){
struct node *temp = NULL;
temp = (struct node*)malloc(sizeof(struct node));
struct node *head = NULL;
head = (struct node*)malloc(sizeof(struct node));
temp = *beginning;
head = temp;
while(temp->nextPtr != NULL){
temp = temp->nextPtr;
}
temp->nextPtr = *adding;
*beginning = head;
/*free(temp);
free(head);*/
}
#endif // NODE_H_INCLUDED
Answer: Overall design
Linked list are often used quite heavily in an application such that there may be many, millions, of your link lists. Many of these, maybe even most, will be empty lists. To that end, I would forego the head node and use a null pointer to indicate an empty list.
Adding: O(n) or O(1)
Instead of using a loop to find the end, consider a linked-list that points to the end. The end.next then points to the beginning. Then adding to the front or back, deleting from the front, are all O(1). To walk the list, rather than look for a final next that is NULL, look for a next that is the same as end.
Abstract data
Rather than code char value, "%c", use typedef char ll_data, #define LL_FORMAT "%c" so one can rapidly amend code for other types.
Add function to consume the first node
Add function to free the entire linked list
Simplify malloc() usage
Cast not needed. Allocate to the size of the referenced data, not the type. Easier to code right, review and maintain.
// add = (struct node*)malloc(sizeof(struct node));
add = malloc(sizeof *add);
// or
add = malloc(sizeof add[0]); | {
"domain": "codereview.stackexchange",
"id": 43070,
"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, linked-list",
"url": null
} |
beginner, c, linked-list
Test for allocation success
On out-of-memory, do something. Do you want to return an error indication, quit, ...
add = malloc(sizeof add[0]);
if (add == NULL) {
TBD_code();
}
Use const
When the pointed-to-data is not changed, use const. This adds info to the function declaration, allows for some optimizations, and increases use.
// void print_list(struct node *firstNode){
void print_list(const struct node *firstNode) {
Put functions in a .c file
Coordinate names
Code is about link lists, not about nodes. Consider ll.h, ll.c, struct ll, ll_print(), ll_add_head(), enum ll_choose_menu, ll_concatenate(), ...
Favorite idea: apply()
A bit advanced, but add a function to that accepts the link list, a function and state variable to apply to every node of the list.
int ll_apply(struct ll *list, int (f)(void *state, struct ll *list), void *state);
Then for each node, from first to last call f(state, node). If the function returns non-zero, return immediately with that value, else go on to the next node.
Think of how easy then to use this to print the list, search the list, count the list, update nodes of the list, ... Just create a supporting function that handles one node. No need to create yet another iterator. | {
"domain": "codereview.stackexchange",
"id": 43070,
"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, linked-list",
"url": null
} |
c++, c++11, design-patterns, template, decorator-pattern
Title: Decorator Pattern with member functions
Question: Motivation: without SaveDecorator, we would have to write:
void Person::save (std::ostream& os) const {
os << tag << '\n';
saveParticular(os);
}
void Worker::save (std::ostream& os) const {
os << tag << '\n';
Person::saveParticular(os);
saveParticular(os);
}
void Teacher::save (std::ostream& os) const {
os << tag << '\n';
Person::saveParticular(os);
Worker::saveParticular(os);
saveParticular(os);
}
and it is easy to forget to always add the line os << tag << '\n'; at the beginning for new derived types of Person. So SaveDecorator will decorate the save member functions, which is appearing as virtual overrides in all the derived types of Person, as follows:
#include <iostream>
template <typename T> // Could not seem to apply pack expansion with the syntax 'void(T::*)(std::ostream&) const... fs', so this alias is apparently needed.
using memberf = void(T::*)(std::ostream&) const;
template <typename...> struct SaveDecorator;
template <>
struct SaveDecorator<> {
template <typename T> void execute (const T*, std::ostream&) const {} // End of recursion.
};
template <typename T, typename... Ts>
class SaveDecorator<T, Ts...> : public SaveDecorator<Ts...> {
void(T::*func)(std::ostream&) const;
public:
SaveDecorator (void(T::*f)(std::ostream&) const, memberf<Ts>... fs) : SaveDecorator<Ts...>(fs...), func(f) { }
void operator()(const T* t, std::ostream& os) const { os << T::tag << '\n'; execute(t, os); }
protected:
void execute (const T* t, std::ostream& os) const {
SaveDecorator<Ts...>::execute(t, os); // More decorated lines to func that are added in the middle.
(t->*func)(os);
}
};
template <typename T, typename... Ts>
SaveDecorator<T, Ts...> makeSaveDecorator() {
return SaveDecorator<T, Ts...>(&T::saveParticular, &Ts::saveParticular...);
} | {
"domain": "codereview.stackexchange",
"id": 43071,
"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, design-patterns, template, decorator-pattern",
"url": null
} |
c++, c++11, design-patterns, template, decorator-pattern
class Person {
std::string name;
public:
static const std::string tag;
virtual ~Person() = default;
Person (const std::string& n) : name(n) { }
virtual void save (std::ostream& os) const { makeSaveDecorator<Person>()(this, os); }
void saveParticular (std::ostream& os) const { os << name << '\n'; }
};
const std::string Person::tag = "Person";
class Worker : public Person {
int ID;
public:
static const std::string tag;
Worker (const std::string& name, int i) : Person(name), ID(i) { }
virtual void save (std::ostream& os) const override { makeSaveDecorator<Worker, Person>()(this, os); }
void saveParticular (std::ostream& os) const { os << ID << '\n'; }
};
const std::string Worker::tag = "Worker";
class Teacher : public Worker {
std::string school;
public:
static const std::string tag;
Teacher (const std::string& name, int ID, const std::string& s) : Worker(name, ID), school(s) { }
virtual void save (std::ostream& os) const override { makeSaveDecorator<Teacher, Worker, Person>()(this, os); }
void saveParticular (std::ostream& os) const { os << school << '\n'; }
};
const std::string Teacher::tag = "Teacher";
int main() {
Person person("Mike");
Worker worker("Sam", 25);
Teacher teacher("Mary", 45, "Northern CI");
person.save(std::cout);
worker.save(std::cout);
teacher.save(std::cout);
}
Output:
Person
Mike
Worker
Sam
25
Teacher
Mary
45
Northern CI
Here is the decorator class rewritten as generically as I could:
#include <iostream>
template <typename R, typename T, typename... Args> // Could not seem to apply pack expansion with the syntax 'R(Ts::*)(Args...) const... fs', so this alias is apparently needed.
using memberf = R(T::*)(Args...) const;
template <typename...> struct MemberFunctionDecorator; | {
"domain": "codereview.stackexchange",
"id": 43071,
"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, design-patterns, template, decorator-pattern",
"url": null
} |
c++, c++11, design-patterns, template, decorator-pattern
template <typename...> struct MemberFunctionDecorator;
template <template <typename, typename...> class Pack, typename R, typename... Args>
struct MemberFunctionDecorator<Pack<R, Args...>> {
MemberFunctionDecorator (R(*)(Args...)) { }
template <typename T> R execute (const T*, Args&&...) const {} // End of recursion.
};
template <template <typename, typename...> class Pack, typename R, typename... Args, typename T, typename... Ts>
class MemberFunctionDecorator<Pack<R, Args...>, T, Ts...> : public MemberFunctionDecorator<Pack<R, Args...>, Ts...> {
R(*argFunc)(Args...);
R(T::*func)(Args...) const;
public:
MemberFunctionDecorator (R(*af)(Args...), R(T::*f)(Args...) const, memberf<R, Ts, Args...>... fs) : MemberFunctionDecorator<Pack<R, Args...>, Ts...>(af, fs...), argFunc(af), func(f) { }
R operator()(const T* t, Args&&... args) const { (*argFunc)(std::forward<Args>(args)...); return execute(t, std::forward<Args>(args)...); }
protected:
R execute (const T* t, Args&&... args) const {
MemberFunctionDecorator<Pack<R, Args...>, Ts...>::execute(t, std::forward<Args>(args)...); // More decorated lines to func that are added in the middle.
return (t->*func)(std::forward<Args>(args)...);
}
};
// Now illustrating the usage of MemberFunctionDecorator.
template <typename ReturnType, typename... Args> struct ArgPack;
template <typename T> void f(std::ostream& os) { os << T::tag << '\n'; }
template <typename T, typename... Ts>
MemberFunctionDecorator<ArgPack<void, std::ostream&>, T, Ts...> saveDecorator() { // Now we pass the particular member functions, including the std::ostream& argument and void return type.
return MemberFunctionDecorator<ArgPack<void, std::ostream&>, T, Ts...>(&f<T>, &T::saveParticular, &Ts::saveParticular...); // Cannot pass a (template) lambda function into the first argument.
} | {
"domain": "codereview.stackexchange",
"id": 43071,
"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, design-patterns, template, decorator-pattern",
"url": null
} |
c++, c++11, design-patterns, template, decorator-pattern
class Person {
std::string name;
public:
static const std::string tag;
virtual ~Person() = default;
Person (const std::string& n) : name(n) { }
virtual void save (std::ostream& os) const { saveDecorator<Person>()(this, os); }
void saveParticular (std::ostream& os) const { os << name << '\n'; }
};
const std::string Person::tag = "Person";
class Worker : public Person {
int ID;
public:
static const std::string tag;
Worker (const std::string& name, int i) : Person(name), ID(i) { }
virtual void save (std::ostream& os) const override { saveDecorator<Worker, Person>()(this, os); }
void saveParticular (std::ostream& os) const { os << ID << '\n'; }
};
const std::string Worker::tag = "Worker";
class Teacher : public Worker {
std::string school;
public:
static const std::string tag;
Teacher (const std::string& name, int ID, const std::string& s) : Worker(name, ID), school(s) { }
virtual void save (std::ostream& os) const override { saveDecorator<Teacher, Worker, Person>()(this, os); }
void saveParticular (std::ostream& os) const { os << school << '\n'; }
};
const std::string Teacher::tag = "Teacher";
int main() {
Person person("Mike");
Worker worker("Sam", 25);
Teacher teacher("Mary", 45, "Northern CI");
person.save(std::cout);
worker.save(std::cout);
teacher.save(std::cout);
}
Answer: Without knowing the context, it’s impossible to say whether this design is a good idea. It seems over-engineered, but….
I will point out that you could get the same effect much, much easier, by simply inverting which function is virtual, and which is not. Instead of save() being virtual and saveParticular() being non-virtual, do it the other way around. This idiom is called the non-virtual interface idiom.
class Person {
std::string name;
public:
virtual ~Person() = default;
Person (const std::string& n) : name(n) { } | {
"domain": "codereview.stackexchange",
"id": 43071,
"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, design-patterns, template, decorator-pattern",
"url": null
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.