text stringlengths 1 2.12k | source dict |
|---|---|
c, linux, kernel, string-processing
Possibly it's not found and
we set a NO_NEWLINE flag and set newline index to end of that buffer,
corresponding to a very long line.
Now we perform two copies to the result buffer: | {
"domain": "codereview.stackexchange",
"id": 44823,
"lm_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, linux, kernel, string-processing",
"url": null
} |
c, linux, kernel, string-processing
from current to either newline or end-of-current-buffer
if needed, from start-of-alternate-buffer to newline
Write a \0 at end of result buffer.
Now a (possibly truncated) line is ready for the consumer.
If NO_NEWLINE is set, continue to read buffers and scan for newlines.
Stop when you hit newline or EOF.
That way we can maintain the invariant that
upon entry current always points to the
start of line that will be returned to consumer,
as long as valid characters remain.
On many processors it will take multiple reads
to skip past the somewhat verbose "flags:" lines.
Update current to point just past the newline.
Return the result buffer.
Can you elaborate a bit on the sanity check you mentioned?
I was just advocating that we replace strchr(line, ':')
with the slightly more picky strstr(line, ": ").
Do I believe the colon will always be followed by SPACE?
Yes, I do, it's part of the cpuinfo spec.
But I'd like to express that in the code.
I feel like I could mock this edge-case by manually creating a file to test this behavior?
Yes, you could definitely arrange for the OP target code
to see a buffer which ends with ": " or with just ":",
and arrange for a Red test to turn Green.
how do you feel about the function returning a const char* instead of a char*?
I missed that. Good catch!
Yes, definitely mark it const. | {
"domain": "codereview.stackexchange",
"id": 44823,
"lm_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, linux, kernel, string-processing",
"url": null
} |
haskell
Title: Solve a letter digit substitution game in Haskell
Question: I am working on a Haskell problem from exercism, which is a learn-to-code website.
The problem statement is as follows.
Write a function to solve alphametics puzzles.
Alphametics is a puzzle
where letters in words are replaced with numbers.
For example SEND + MORE = MONEY:
S E N D
M O R E +
-----------
M O N E Y
Replacing these with valid numbers gives:
9 5 6 7
1 0 8 5 +
-----------
1 0 6 5 2
This is correct because every letter is replaced by a different number
and the words, translated into numbers, then make a valid sum.
Each letter must represent a different digit, and the leading digit of
a multi-digit number must not be zero.
Write a function to solve alphametics puzzles.
You can solve this exercise with a brute force algorithm, but this
will possibly have a poor runtime performance. Try to find a more
sophisticated solution. Hint: You could try the column-wise addition
algorithm that is usually taught in high school.
Here is my WIP solution. I would like to know how to shorten this up. I feel it's unnecessarily verbose.
module Alphametics (solve) where
import Data.List ((\\))
import Data.List.NonEmpty (NonEmpty)
import qualified Data.Char as C
import qualified Data.List as L
import qualified Data.List.NonEmpty as NE
import qualified Data.Maybe as MB
solve' :: NonEmpty String -> Maybe [(Char, Int)]
solve' terms = findFirstSolution . zipLettersAndDigits . filterLeadingZeroes . L.permutations $ [0 .. 9]
where
initials = L.nub . MB.catMaybes . NE.toList . NE.map MB.listToMaybe $ terms
nonInitials = L.nub (concat terms) \\ initials
letters = initials ++ nonInitials
n = length initials
findFirstSolution = L.find (`solves` terms)
zipLettersAndDigits = map (zip letters)
filterLeadingZeroes = filter noZerosPriorTo
noZerosPriorTo p = 0 `notElem` take n p | {
"domain": "codereview.stackexchange",
"id": 44824,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "haskell",
"url": null
} |
haskell
solve :: String -> Maybe [(Char, Int)]
solve puzzle = solve' =<< NE.nonEmpty terms
where
terms = filter (all C.isUpper) . words $ puzzle
solves :: [(Char, Int)] -> NonEmpty String -> Bool
solves cmap terms = (sum <$> mapM termToInt (NE.init terms)) == termToInt (NE.last terms)
where
termToInt :: [Char] -> Maybe Int
termToInt xs = fromDigits <$> mapM (`lookup` cmap) xs
fromDigits :: [Int] -> Int
fromDigits = L.foldl' (\n x -> n * 10 + x) 0
In particular, I'd like to avoid splitting the solve function into solve and solve', but I don't know how to inline solve' without just sticking it in a where clause, which isn't really any nicer. Seems like there should be a way to perform this bind without a separate function. Also, just general advice would be lovely, thanks!
Answer: There's no particular reason to want to not have a solve', except maybe that it's hard to give it a good name. If you're worried about clutter; putting it in a where clause is fine. solve already has a where, and there's no need to nest wheres, initials etc can be declared at the same level as solve'.
Each letter must represent a different digit, and the leading digit of a multi-digit number must not be zero. | {
"domain": "codereview.stackexchange",
"id": 44824,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "haskell",
"url": null
} |
haskell
There's an obnoxious edge case hidden here: If one of the terms is a single character, then that (leading!) character can be zero.
That's frustrating because already a lot of your complexity comes from trying to avoid solutions that involve illegal leading zeros.
If you're going to keep working on this solution, I would suggest packaging the illegal-leading-zeros test as it's own function, and applying it later in the logic, after solves.
The performance difference should be small either way, and I think it will read better.
Similarly, separate the business of parsing/validating the equation itself from the process of finding solutions. You're kinda already doing this with NonEmpty, but it's not clearly enforced that the constituent words will be non-empty, and it'd read clearer (and be easier to unpack arguments) if you had a designated data type for the equations.
I notice that Maybe is doing a lot of work. That's not ideal; if you get back Nothing, does that mean that the provided text wasn't a valid problem, or that no solution could be found? In the definition of solves, what would it mean for both sides of the == to be Nothing? (I don't actually know; I just think the situation smells bad.) I haven't thought too much about exactly how to fix it, but you have other options for representing failure; empty-list, Left, and error may help.
All that said, if you have a working brute-force solution, it's probably time to consider the final lines of the prompt, and start looking for something more performant. | {
"domain": "codereview.stackexchange",
"id": 44824,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "haskell",
"url": null
} |
c++, c++17, finance, c++20
Title: Fast OrderBook Implementation
Question: I'm creating a simple yet fast OrderBook, that only adds orders and matches them (no cancelling or modifications, etc.). I'm using partial template specialization to reduce branching in the hotpath, and I'm preallocating the price ladder to avoid expensive allocation operations (that and this being a lot more cache friendly are the reasons I chose this approach over something like a balanced BST or a heap). The printing of the orderbook after each order insertion is a requirement, and of course that dominates the runtime, but the order insertion and matching itself should be as low latency as possible.
This was tested on Clang 14 (on Ubuntu 22.04 LTS), and doesn't compile with GCC due to https://gcc.gnu.org/bugzilla/show_bug.cgi?id=85282.
Here's the first rough implementation (just wanted something implemented quickly, and I'm going to make improvements like using a conditional for processOrder instead of doing specialisation), and I thought I'd get some feedback on it and see what I can improve in terms of performance (and maybe some code quality issues too). I've included everything all in one file to make it easier to quickly run. Also error checking isn't needed, the orders will be formatted correctly with valid values.
#include <iostream>
#include <deque>
#include <vector>
#include <iomanip>
using namespace std; // remove this
struct Order
{
int id;
short price;
int quantity;
};
enum class Side
{
Buy,
Sell
};
class OrderBook
{
using book_t = vector<deque<Order>>;
private:
book_t buys;
book_t sells;
int topOfBuys = -1;
int bottomOfBuys = 65537;
int topOfSells = 65537;
int bottomOfSells = -1;
public:
OrderBook() : buys(65536), sells(65536) {} | {
"domain": "codereview.stackexchange",
"id": 44825,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++17, finance, c++20",
"url": null
} |
c++, c++17, finance, c++20
public:
OrderBook() : buys(65536), sells(65536) {}
void displayOrderBook()
{
cout << "+" << string(65, '-') << "+\n";
cout << "| BUY | SELL |\n";
cout << "| Id | Volume | Price | Price | Volume | Id |\n";
cout << "+----------+-------------+-------+-------+-------------+----------+\n";
vector<pair<Order, Order>> orders; // buy, sell
int sellIndex = 0, buyIndex = 0;
for (int i = topOfBuys; i >= bottomOfBuys; --i)
{
if (not buys[i].empty())
{
for (auto &order : buys[i])
{
if (buyIndex < orders.size())
orders[buyIndex++].first = order;
else
orders.push_back({order, Order{}});
}
}
}
for (int i = topOfSells; i <= bottomOfSells; ++i)
{
if (not sells[i].empty())
{
for (auto &order : sells[i])
{
if (sellIndex < orders.size())
orders[sellIndex++].second = order;
else
orders.push_back({Order{}, order});
}
}
}
auto displayField = [](const int value)
{
return value != 0 ? to_string(value) : "";
};
for (const auto &[buyOrder, sellOrder] : orders)
{
cout << "| " << setw(8) << displayField(buyOrder.id) << " | "
<< setw(11) << displayField(buyOrder.quantity) << " | "
<< setw(5) << displayField(buyOrder.price) << " | "
<< setw(5) << displayField(sellOrder.price) << " | "
<< setw(11) << displayField(sellOrder.quantity) << " | "
<< setw(8) << displayField(sellOrder.id) << " |\n";
} | {
"domain": "codereview.stackexchange",
"id": 44825,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++17, finance, c++20",
"url": null
} |
c++, c++17, finance, c++20
cout << "+" << string(65, '-') << "+\n";
}
string formatWithCommas(int value)
{
stringstream ss;
ss.imbue(locale(""));
ss << fixed << value;
return ss.str();
}
template <Side side>
void processOrder(Order &&order);
template <>
void processOrder<Side::Sell>(Order &&order)
{
if (order.price <= topOfBuys)
matchOrders<Side::Sell, Side::Buy>(move(order), buys, topOfBuys, bottomOfBuys);
else
addOrder<Side::Sell>(move(order));
displayOrderBook();
}
template <>
void processOrder<Side::Buy>(Order &&order)
{
if (order.price >= topOfSells)
matchOrders<Side::Buy, Side::Sell>(move(order), sells, topOfSells, bottomOfSells);
else
addOrder<Side::Buy>(move(order));
displayOrderBook();
}
template <Side orderSide, Side otherSide>
void matchOrders(Order &&order, book_t &otherBook, int &topOfOther, int &bottomOfOther)
{
while (compare<otherSide>() and order.quantity > 0)
{
auto &other = otherBook[topOfOther].front();
if (order.quantity < other.quantity)
{
cout << order.id << "," << other.id << "," << topOfOther << "," << order.quantity << '\n';
other.quantity -= order.quantity;
order.quantity = 0;
}
else
{
cout << order.id << "," << other.id << "," << topOfOther << "," << other.quantity << '\n';
order.quantity -= other.quantity;
otherBook[topOfOther].pop_front();
}
if (otherBook[topOfOther].empty())
findNext<otherSide>();
}
if (order.quantity > 0)
addOrder<orderSide>(move(order));
}
template <Side side>
inline bool compare(); | {
"domain": "codereview.stackexchange",
"id": 44825,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++17, finance, c++20",
"url": null
} |
c++, c++17, finance, c++20
template <Side side>
inline bool compare();
template <>
inline bool compare<Side::Buy>()
{
return topOfBuys >= bottomOfBuys;
}
template <>
inline bool compare<Side::Sell>()
{
return topOfSells <= bottomOfSells;
}
template <Side side>
inline void findNext();
template <>
inline void findNext<Side::Sell>()
{
while (topOfSells <= bottomOfSells and sells[topOfSells].empty())
{
++topOfSells;
}
if (topOfSells > bottomOfSells)
{
topOfSells = 65537;
bottomOfSells = -1;
}
}
template <>
inline void findNext<Side::Buy>()
{
while (topOfBuys >= bottomOfBuys and buys[topOfBuys].empty())
{
--topOfBuys;
}
if (topOfBuys < bottomOfBuys)
{
topOfBuys = -1;
bottomOfBuys = 65537;
}
}
template <Side side>
void addOrder(Order &&order);
template <>
void addOrder<Side::Sell>(Order &&order)
{
topOfSells = min(topOfSells, (int)order.price);
bottomOfSells = max(bottomOfSells, (int)order.price);
sells[order.price].push_back(move(order));
}
template <>
void addOrder<Side::Buy>(Order &&order)
{
topOfBuys = max(topOfBuys, (int)order.price);
bottomOfBuys = min(bottomOfBuys, (int)order.price);
buys[order.price].push_back(move(order));
}
}; | {
"domain": "codereview.stackexchange",
"id": 44825,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++17, finance, c++20",
"url": null
} |
c++, c++17, finance, c++20
int main()
{
OrderBook orderbook;
orderbook.processOrder<Side::Sell>(move(Order{1, 5103, 100}));
orderbook.processOrder<Side::Buy>(move(Order{2, 5103, 100000}));
orderbook.processOrder<Side::Buy>(move(Order{3, 5103, 100000}));
orderbook.processOrder<Side::Sell>(move(Order{4, 5103, 100}));
orderbook.processOrder<Side::Sell>(move(Order{5, 5104, 100}));
orderbook.processOrder<Side::Sell>(move(Order{6, 5103, 100}));
orderbook.processOrder<Side::Buy>(move(Order{7, 5105, 300}));
orderbook.processOrder<Side::Sell>(move(Order{8, 5105, 300}));
return 0;
}
``` | {
"domain": "codereview.stackexchange",
"id": 44825,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++17, finance, c++20",
"url": null
} |
c++, c++17, finance, c++20
Answer: Adding to pacmaninbw's review:
There's a hole in struct Order
There's a hole between price and quantity in struct Order. If you hadn't mentioned performance I would not have mentioned this, but there is a cost to this. Depending on the CPU architecture, the compiler might have to emit more instructions to deal with something smaller than an int. For example, because it can only load a whole 32-bit value from memory, and then needs to mask the 16 unused bits, because there is no guarantee that the whole is filled with zeroes. The simple solution is to just store price as an int here as well.
Naming things
You are creating new types using PascalCase, except for book_t. Why not write Book instead?
Also note that POSIX reserves all names ending in _t, so it's best not to create new identifiers with that suffix yourself in C or C++ code.
Handling buys and sells
pacmaninbw already mentioned that your templated processOrder() function is not great. Having a template that only has specializations defeats the purpose of making it a template to begin with. Let's look at some alternatives:
Use separate functions
You could just have untemplated processBuy() and processSell() functions.
Pass the Side as a regular function parameter
This is what pacmaninbw suggested. Since the member functions are defined in the class, calls to these function will be inlined, and the compiler can then specialize the function at the call site, giving you the same performance as with a template parameter.
Create distinct BuyOrder and SellOrder types
You can create separate types for buy orders and sell orders, for example:
struct BuyOrder: public Order
{
static constexpr Side side = Side::Buy;
};
struct SellOrder: public Order
{
static constexpr Side side = Side::Sell;
}; | {
"domain": "codereview.stackexchange",
"id": 44825,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++17, finance, c++20",
"url": null
} |
c++, c++17, finance, c++20
struct SellOrder: public Order
{
static constexpr Side side = Side::Sell;
};
Now you can do two things. First, you can template processOrder() again, and then use if constexpr to do things differently depending on whether you have a buy or sell order:
void processOrder(std::derived_from<Order> auto&& order>)
{
if constexpr (order.side == Side::Buy)
{
…
} else {
…
}
displayOrderBook();
}
Second, you can create a std::variant type:
using AnyOrder = std::variant<BuyOrder, SellOrder>;
This way you can pass either a BuyOrder or SellOrder to a function, without requiring the function to be a template:
void processOrder(AnyOrder&& order)
{
if (std::holds_alternative<BuyOrder>(order))
{
…
} else {
…
}
displayOrderBook();
}
I'm just showing std::holds_alternative<>() here for symmetry with the example above this one; you'd probably use std::visit() instead.
Make your code more generic
Regardless of how you deal with the difference between buy and sell orders, try to make your code more generic. Whenever you see you have to write specific code, avoid specializing the whole function, and instead first ask yourself if you can delegate that specialization to another function. For example, what if you could write:
template <Side side>
void processOrder(Order &&order)
{
if (priceMatches<side>(order))
matchOrders<side>(std::move(order));
else
addOrder<side>(std::move(order));
displayOrderBook();
}
Now you can create a templated priceMatches() function that checks order.price against topOfBuys or topOfSells, depending on the template argument. And let matchOrders derive otherSide from orderSide, and also let it decide which book to use.
Another way to avoid all the ifs that deal with Sides is to create an array to hold the books and their associated variables:
struct Book
{
std::vector<std::deque<Order>> orders;
int top;
int bottom;
}; | {
"domain": "codereview.stackexchange",
"id": 44825,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++17, finance, c++20",
"url": null
} |
c++, c++17, finance, c++20
std::array<Books, 2> books;
Now consider that you can index books using the template parameter side, like for example:
template <Side orderSide>
void matchOrders(Order &&order)
{
static constexpr Side otherSide = (orderSide == Side::Buy) ? Side::Sell : Side::Buy;
Book& otherBook = books[static_cast<int>(otherSide)];
int& topOfOther = otherBook.top;
int& bottomOfOther = otherBook.bottom;
…
}
Avoid unnecessary temporary storage
There is no need for the vector orders in displayOrderBook(). You can just have one loop which has two loop indices, one for the buys and one for the sells:
for (int i = topOfBuys, j = topOfSells; i >= bottomOfBuys && j >= bottomOfSells;)
{
// Find the next buy
while (i >= bottomOfBuys && buys[i].empty)
--i;
// Find the next sell
while (j >= bottomOfSells && sells[j].empty)
--j;
const auto& buyOrder = (i >= bottomOfBuys) ? buys[i] : Order{};
const auto& sellOrder = (i >= bottomOfSells) ? sells[i] : Order{};
std::cout << …;
} | {
"domain": "codereview.stackexchange",
"id": 44825,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++17, finance, c++20",
"url": null
} |
c++, c++17, finance, c++20
std::cout << …;
}
This saves you multiple expensive allocations each time you call displayOrderBook().
Use std::format()
Since you added the C++20 tag to the question, I strongly recommend you use std::format() instead of the old way of formatting output.
Is it really faster?
An array is only faster and more cache efficient if it's not full of empty spots. What if I add two orders, one with price 1 and with price 32767? Suddenly displayOrderBook() becomes very expensive!
Is a 16-bit integer enough for all possible prices? I'm sure there are things you can buy that cost more than ¤32767. If you want to make this a 32-bit integer, then your vectors can suddenly grow very large. To ensure your order book can scale, you probably have to abandon the idea of using a vector indexed by price.
You are right that a naive heap or balanced tree might be a lot less efficient. However, there are other data structures you can use that are more cache-efficient. Instead of binary heaps or trees, you could use \$n\$-ary heaps or trees, with \$n\$ chosen such that each node fits neatly in a cache line. | {
"domain": "codereview.stackexchange",
"id": 44825,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++17, finance, c++20",
"url": null
} |
c++, object-oriented, matrix, c++17
Title: Create classes for matrices, including inheritance
Question: I've been learning C++ on and off, and recently learnt about overloading and templates. I wanted to used these concepts to create classes about matrices using std::array.
Note that this has to be compiled using std=c++17 or newer, following a clarification involving constexpr.
#include <array>
#include <iostream>
template <std::size_t R, std::size_t C>
class Matrix {
protected:
std::array<std::array<double, C>, R> matrix;
public:
/// @brief sets all elements of the matrix to 0
Matrix() {
for (std::size_t row = 0; row < R; row++) {
for (std::size_t column = 0; column < C; column++) {
matrix[row][column] = 0;
}
}
}
/// @brief sets the matrix to the given matrix
/// @param matrix the input data
Matrix(std::array<std::array<double, C>, R> matrix) : matrix(matrix) {}
/// @brief adds the given matrix to the current matrix, element by element
/// @param matrix the input data
/// @return the sum of the two matrices
Matrix<R, C> operator+(Matrix<R, C> matrix) {
Matrix<R, C> returnMatrix;
for (std::size_t row = 0; row < R; row++) {
for (std::size_t column = 0; column < C; column++) {
returnMatrix[row][column] = this->matrix[row][column] + matrix[row][column];
}
}
return returnMatrix;
}
/// @brief subtracts the given matrix from the current matrix, element by element
/// @param matrix the input data
/// @return the difference of the two matrices
Matrix<R, C> operator-(Matrix<R, C> matrix) {
Matrix<R, C> returnMatrix;
for (std::size_t row = 0; row < R; row++) {
for (std::size_t column = 0; column < C; column++) {
returnMatrix[row][column] = this->matrix[row][column] - matrix[row][column];
}
}
return returnMatrix;
} | {
"domain": "codereview.stackexchange",
"id": 44826,
"lm_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++, object-oriented, matrix, c++17",
"url": null
} |
c++, object-oriented, matrix, c++17
return returnMatrix;
}
/// @brief multiplies the given matrix with the current matrix
/// @param matrix the input data
/// @return the product of the two matrices
/// @warning the number of columns of the first matrix must be equal to the number of rows of the second matrix. I'm unable to figure out a way to check this, since the number of rows and columns are template parameters
Matrix<R, C> operator*(Matrix<R, C> matrix) {
Matrix<R, C> returnMatrix;
for (std::size_t k = 0; k < R; k++) {
for (std::size_t i = 0; i < R; i++) {
for (std::size_t j = 0; j < C; j++) {
returnMatrix[i][j] += this->matrix[i][k] * matrix[k][j];
}
}
}
return returnMatrix;
}
/// @brief allows you to index a row of the matrix
/// @param row index of the row
/// @return the row of the matrix, as an array
std::array<double, C>& operator[](std::size_t row) {
return matrix[row];
}
/// @brief return the matrix
/// @return the `std::array<std::array>` object
std::array<std::array<double, C>, R> getMatrix() {
return matrix;
}
/// @brief returns the element at the given row and column
/// @param row index of the row
/// @param column index of the column
int getElement(std::size_t row, std::size_t column) {
return matrix[row][column];
}
/// @brief sets the matrix to the given matrix
/// @param matrix the input data
void setMatrix(std::array<std::array<double, C>, R> matrix) {
this->matrix = matrix;
}
/// @brief sets the element at the given row and column to the given value
/// @param row index of the row
/// @param column index of the column
void setElement(std::size_t row, std::size_t column, double value) {
matrix[row][column] = value;
} | {
"domain": "codereview.stackexchange",
"id": 44826,
"lm_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++, object-oriented, matrix, c++17",
"url": null
} |
c++, object-oriented, matrix, c++17
/// @brief prints the matrix to the console
void printMatrix() {
printf("\n[%dx%d] matrix\n", R, C);
for (std::size_t row = 0; row < R; row++) {
for (std::size_t column = 0; column < C; column++) {
printf("%.0f\t", matrix[row][column]);
}
printf("\n");
}
printf("\n");
}
};
/// @brief square matrix, a matrix with the same number of rows and columns
/// @tparam N number of rows and columns
template <std::size_t N>
class SquareMatrix : public Matrix<N, N> {
public:
/// @brief reuse the constructor of the base class
SquareMatrix() : Matrix<N, N>() {}
/// @brief sets the matrix to the given matrix. reuses the constructor
/// @param matrix the input data
SquareMatrix(std::array<std::array<double, N>, N> matrix) : Matrix<N, N>(matrix) {}
/// @brief extracts the submatrix of the given matrix, ignoring the given row and column
/// @param ignoreRow row to ignore
/// @param ignoreColumn column to ignore
/// @return `SquareMatrix<N - 1>` object, the submatrix
SquareMatrix<N - 1> subMatrix(std::size_t ignoreRow, std::size_t ignoreColumn) {
SquareMatrix<N - 1> returnMatrix;
int subMatrixRow = 0, subMatrixColumn = 0;
for (std::size_t matrixRow = 0; matrixRow < N; matrixRow++) {
for (std::size_t matrixColumn = 0; matrixColumn < N; matrixColumn++) {
if (matrixRow != ignoreRow && matrixColumn != ignoreColumn) {
returnMatrix[subMatrixRow][subMatrixColumn++] = this->matrix[matrixRow][matrixColumn];
if (subMatrixColumn == N - 1) {
subMatrixColumn = 0;
subMatrixRow++;
}
}
}
}
return returnMatrix;
} | {
"domain": "codereview.stackexchange",
"id": 44826,
"lm_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++, object-oriented, matrix, c++17",
"url": null
} |
c++, object-oriented, matrix, c++17
return returnMatrix;
}
/// @brief calculates the determinant of the matrix.
/// see Laplace expansion. https://en.wikipedia.org/wiki/Determinant#Laplace_expansion
/// @return the determinant of the matrix
double getDeterminant() {
double determinant = 0;
// base case 1
if constexpr (N == 1) {
determinant = this->matrix[0][0];
}
// base case 2
else if constexpr (N == 2) {
determinant = (this->matrix[0][0] * this->matrix[1][1]) - (this->matrix[0][1] * this->matrix[1][0]);
}
// recursive case
else if constexpr (N > 0) {
int sign = 1;
for (std::size_t dimension = 0; dimension < N; dimension++) {
// calculate cofactor and add to determinant
determinant += sign * this->matrix[0][dimension] * subMatrix(0, dimension).getDeterminant();
sign = -sign;
}
}
else {
throw std::invalid_argument("expected square matrix");
}
return determinant;
}
};
int main() {
static const std::size_t LENGTH = 4;
SquareMatrix<LENGTH> matrixOne({{{7, -2, 2, 1},
{3, 1, -5, 2},
{2, 2, -5, 3},
{3, -2, 5, 1}}});
SquareMatrix<LENGTH> matrixTwo({{{1, 2, 3, 4},
{5, 6, 7, 8},
{9, -8, 7, 6},
{5, 4, -3, -2}}});
matrixOne.printMatrix();
matrixTwo.printMatrix();
printf("\nmatrixOne + matrixTwo\n");
(matrixOne + matrixTwo).printMatrix();
printf("\nmatrixOne - matrixTwo\n");
(matrixOne - matrixTwo).printMatrix();
printf("\nmatrixOne * matrixTwo\n");
(matrixOne * matrixTwo).printMatrix(); | {
"domain": "codereview.stackexchange",
"id": 44826,
"lm_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++, object-oriented, matrix, c++17",
"url": null
} |
c++, object-oriented, matrix, c++17
printf("\nmatrixOne * matrixTwo\n");
(matrixOne * matrixTwo).printMatrix();
printf("determinant of matrixOne: %.0f\n", matrixOne.getDeterminant());
printf("determinant of matrixTwo: %.0f\n", matrixTwo.getDeterminant());
}
Program output
g++ ./determinant-inheritance.cpp -o determinant-inheritance -std=c++20 && ./determinant-inheritance
[4x4] matrix
7 -2 2 1
3 1 -5 2
2 2 -5 3
3 -2 5 1
[4x4] matrix
1 2 3 4
5 6 7 8
9 -8 7 6
5 4 -3 -2
matrixOne + matrixTwo
[4x4] matrix
8 0 5 5
8 7 2 10
11 -6 2 9
8 2 2 -1
matrixOne - matrixTwo
[4x4] matrix
6 -4 -1 -3
-2 -5 -12 -6
-7 10 -12 -3
-2 -6 8 3
matrixOne * matrixTwo
[4x4] matrix
20 -10 18 22
-27 60 -25 -14
-18 68 -24 -12
43 -42 27 24
determinant of matrixOne: 47
determinant of matrixTwo: -640
Answer: Avoid C functions
I see you are using printf() in your code. Consider avoiding this and using the C++ way of printing instead. The main disadvantage of printf() is that it is not type safe. The main advantage of printf() is perhaps the format string, but since C++20 there is std::format(), and in C++23 we will get the best of everything with std::print(). If you cannot use a newer C++ version yet, you can link with the {fmt} library to get the same functionality.
Note that with the "old" way of printing in C++, you could have written:
void printMatrix() {
std::cout << "\n[" << R << 'x' << C << "] matrix\n";
for (auto& row: matrix) {
for (auto& value: row) {
std::cout << std::setprecision(0) << value << '\t';
}
std::cout << '\n';
}
std::cout << '\n';
} | {
"domain": "codereview.stackexchange",
"id": 44826,
"lm_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++, object-oriented, matrix, c++17",
"url": null
} |
c++, object-oriented, matrix, c++17
std::cout << '\n';
}
std::cout << '\n';
}
Note that if you want to keep using C's printf(), you should #include <cstdio> instead of #include <iostream>.
Use I/O operator overloading to print
Wouldn't it be nice if you could print by write the following?
Matrix<…> matrix(…);
std::cout << matrix;
You can quite easily change your printMatrix() function into an overload of operator<<(std::ostream&). The main advantage is that you no longer are hardcoding where the output goes: you can then print to std::cerr, to a std::stringstream, a std::fstream and whatever else provides a std::ostream interface.
Avoid making unnecessary copies of matrices
While your code might be functionally correct, it makes copies of matrices in lots of places. For example, because operator+() takes the parameter matrix by value, whenever it is called a copy is made of that matrix. To avoid that, pass the input by const reference:
Matrix operator+(const Matrix& matrix) {
…
} | {
"domain": "codereview.stackexchange",
"id": 44826,
"lm_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++, object-oriented, matrix, c++17",
"url": null
} |
c++, object-oriented, matrix, c++17
You should not do the same for the return value; copy elision will take of that.
No need to repeat the template parameters inside the template itself
Inside the declaration of class Matrix you don't need to repeat the template parameters if they are the same as the object's, you can just write Matrix and it will be equivalent to Matrix<R, C>. Prefer the short form, there is less chance of making mistakes this way, and if you really do want different template parameters you can still do that, but it will then clearly stand out.
About matrix-matrix multiplications
Your operator*() only allows two matrices of the same size to be multiplied. However, in mathematics, you can multiply two matrices of different size, as long as the number of columns on the left hand matches the number of rows on the right hand of the multiplication. You can easily change your operator to do this. First, you know that the matrix on the right hand side should have the same number of rows as the left hand side has columns, that's just C. But then the right hand side can have it's own number of columns, so let's name that RHC. Then you can just write:
template<std::size_t RHC>
Matrix<R, RHC> operator*(const Matrix<C, RHC>& matrix) {
…
}
And you just have to change one of the for-loops to use RHC.
Consider writing out-of-class operators
Instead of writing the operators as class member functions, you can also make them out-of-class friend functions:
template<…>
class Matrix {
…
friend Matrix operator+(const Matrix& lhs, const Matrix& rhs);
…
};
template<std::size_t R, std::size_t C>
Matrix<R, C> operator+(const Matrix<R, C>& lhs, const Matrix<R, C>& rhs) {
Matrix<R, C> result;
…
result[row][column] = lhs[row][column] + rhs[row][column];
…
return result;
} | {
"domain": "codereview.stackexchange",
"id": 44826,
"lm_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++, object-oriented, matrix, c++17",
"url": null
} |
c++, object-oriented, matrix, c++17
You might not see the point of this, but it has several advantages. In particular, consider that you might want to allow multiplying a matrix by a scalar value. You could add an overload of the member function operator*():
Matrix operator*(double value) {…}
That would allow you to write:
Matrix<…> matrix(…);
auto matrix2 = matrix * 2;
But it would not allow you to write:
auto matrix2 = 2 * matrix;
And there is no way to achieve that with a member function. However, the friend operators get two parameters, so then you can do:
friend Matrix operator*(const Matrix& lhs, double rhs);
friend Matrix operator*(double lhs, const Matrix& rhs);
In this case, because the operation is commutative, you only have to fully implement one of them:
template<std::size_t R, std::size_t C>
friend Matrix<R, C> operator*(const Matrix<R, C>& lhs, double rhs) {
Matrix result = lhs;
for (auto& row: result)
for (auto& value: row)
value *= rhs;
return result;
}
Then the other can just call the first one with the arguments swapped:
template<std::size_t R, std::size_t C>
friend Matrix<R, C> operator*(double lhs, const Matrix<R, C>& rhs) {
return rhs * lhs;
}
Apart from the binary operators themselves, you can also make members like getDeterminant() friends instead:
friend double getDeterminant(const Matrix& matrix);
You would then need to call it like getDeterminant(matrix) instead of matrix.getDeterminant(), but that's similar to how you use std::abs() and other standard math functions.
Element access
You have getElement() and setElement() members, but have you noticed that standard containers like std::array and std::vector don't have such functions at all? They have overloads of operator[] and have a member function at() that allows read/write access to a given element. You can do the same:
double& at(std::size_t row, std::size_t column) {
return matrix[row][column];
} | {
"domain": "codereview.stackexchange",
"id": 44826,
"lm_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++, object-oriented, matrix, c++17",
"url": null
} |
c++, object-oriented, matrix, c++17
Because a reference is returned, the caller can then do:
matrix.at(1, 2) = 3;
Also note that your getElement() returned an int instead of a double.
You can also overload operator[]. Before C++23, it was not possible to pass more than one parameter inside the brackets, but you could have cheated by writing something like:
double& operator[](std::pair<std::size_t, std::size_t> index) {
return matrix[index.first][index.second];
}
And call it like:
matrix[{1, 2}] = 3;
Make member functions const where appropriate
Member functions themselves can be marked const to indicate that they won't modify any member variables. Consider writing:
const Matrix<…> matrix(…);
auto value = matrix.getElement(1, 2); // compile error!
This wouldn't compile, because getElement() is not marked const, so the compiler will not allow you to call it on a const object. The simple solution is to make getElement() const:
double getElement(std::size_t row, std::size_t column) const {
…
}
But that works here because this function returns by value, and never has to modify any members. But the above at() has a problem: if you want to be able to use it to write to an element, it needs to return a non-const reference. But that is not allowed if you apply it to a const object. You can however create a second overload for const objects:
double& at(std::size_t row, std::size_t column) {
return matrix[row][column];
}
const double& at(std::size_t row, std::size_t column) const {
return matrix[row][column];
} | {
"domain": "codereview.stackexchange",
"id": 44826,
"lm_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++, object-oriented, matrix, c++17",
"url": null
} |
c++, object-oriented, matrix, c++17
const double& at(std::size_t row, std::size_t column) const {
return matrix[row][column];
}
You'll note that the body of those functions are the same, which is annoying. There are two ways around it; having one call the other but using std::const_cast to cheat. Another way is to use C++23's explicit object parameter.
About inheritance
Inheritance is one way to create a SquareMatrix class. However, it has some drawbacks, and there are alternatives you could use. Consider for example making getDeterminant() an out-of-class function that takes a SquareMatrix as a parameter. Now I can write:
SquareMatrix<…> square;
auto det = getDeterminant(square);
But now consider I wrote:
Matrix<3, 3> square;
auto det = getDeterminant(square); // compile error
This fails to compile because getDeterminant() only works on SquareMatrixes, even though Matrix<3, 3> is also square. You could create an overload for getDeterminant() to take square Matrix objects as well, but that's more work and extra code, with more chance of bugs.
Instead of using inheritance, consider creating a type alias:
template<std::size_t N>
using SquareMatrix = Matrix<N, N>;
Your getDeterminant() function will then look like:
template<std::size_t N>
double getDeterminant(const SquareMatrix<N>& matrix) {…}
But SquareMatrix was just an alias, so I can pass in a Matrix<3, 3> and it will still work. If I pass in a Matrix<4, 5> it will fail to compile.
Another option would be to use static_assert(), SFINAE or C++20's concepts to ensure getDeterminant() only compiles for square matrices. For example:
template<std::size_t R, std::size_t C>
double getDeterminant(const Matrix<R, C>& matrix) {
static_assert(R == C, "The determinant is only defined for square matrices.");
…
}
Or with C++20:
template<std::size_t R, std::size_t C>
requires (R == C)
double getDeterminant(const Matrix<R, C>& matrix) {
…
} | {
"domain": "codereview.stackexchange",
"id": 44826,
"lm_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++, object-oriented, matrix, c++17",
"url": null
} |
c++, object-oriented, matrix, c++17
In this simple case you can also just make sure template deduction only works for square matrices:
template<std::size_t N>
double getDeterminant(const Matrix<N, N>& matrix) {…}
But in fact I already showed that, because this is equivalent to writing getDeterminant(const SquareMatrix<N>& matrix). | {
"domain": "codereview.stackexchange",
"id": 44826,
"lm_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++, object-oriented, matrix, c++17",
"url": null
} |
python, minecraft
Title: How can I make my mini-game simpler and more efficient?
Question: I've recently started to learn Python and the task was to create a "hot or cold" game. They gave me the basic structure for the code and so far so good. But the bonus objective is to find a way to display how long it takes the player to find the block or even limit the amount of time they have to play the game.
I came up with basic ideas of what I want the player to see:
30 seconds to find the block
15 seconds left
5 second left countdown
Too late
After several trials it's now working but somehow this looks a bit chaotic to me.
Is there another simple way to make this code more readable/efficient?
Thanks a lot!
P.S: If found in time, the result is (timer-1) because the function timer += 1 starts at the very beginning of the loop and therefore adds an extra second to the timer. I'm aware this can be written in a better way...
from mcpi.minecraft import Minecraft
mc = Minecraft.create()
import math
import time
import random
destX = random.randint(600, 700)
destZ = random.randint(210,310)
destY = mc.getHeight(destX, destZ)
block = 57
mc.setBlock(destX, destY, destZ, block)
mc.postToChat("Block set!")
timer = 0
mc.postToChat("You have 30 seconds to find the diamond block!")
while True:
time.sleep(1)
timer += 1
pos= x,y,z = mc.player.getPos()
distance = math.sqrt((x - destX) **2 + (z - destZ) **2)
if timer == 15:
mc.postToChat("15 seconds left")
elif 25 <= timer < 30:
mc.postToChat(30-timer)
elif timer == 30:
mc.postToChat("Too late!")
break | {
"domain": "codereview.stackexchange",
"id": 44827,
"lm_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, minecraft",
"url": null
} |
python, minecraft
elif timer == 30:
mc.postToChat("Too late!")
break
elif timer != 30:
if distance > 100:
mc.postToChat("Freezing")
elif distance > 50:
mc.postToChat("Cold")
elif distance > 25:
mc.postToChat("Warm")
elif distance > 12:
mc.postToChat("Boiling")
elif 3 < distance < 12:
mc.postToChat("On fire!")
elif int(distance) in range(0,3):
mc.postToChat("Found it in " + str(timer-1) + " seconds!")
break
Answer: Nice little game. Simple, fun. I like it.
simpler and more efficient?
I'm not sure there's a lot of improvement to be had, here.
Given that our frame rate is 1 FPS, it's not like
we need to re-write in C++ to make it hum.
The big high-level critique would be: Extract Helper!
That is, find chunks of code that go together,
and break them out as separate functions.
That's fine, you'll get to def soon, I have confidence.
You could also use lint tools like
ruff or
black,
but that's a minor concern ATM.
Overall, you have chosen identifiers that are
clear and self-explanatory. | {
"domain": "codereview.stackexchange",
"id": 44827,
"lm_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, minecraft",
"url": null
} |
python, minecraft
random location
You have some crystal-clear code for picking the "needle" destination
in the haystack.
Pep-8
asks for names like dest_x rather than destX -- no biggie.
It would make sense to extract these three lines into a small
helper function.
Sometimes the needle is in an "easy" location,
it's in plain view from far away.
If you wanted to make the algorithm a little fancier,
you might do something called
rejection sampling.
Suppose we want to throw random darts at circular target.
Easy: uniformly pick random x on the interval -1 .. 1,
similarly random y.
Compute radius r to central bullseye with
pythagoras.
And if r > 1, we reject the point as not being within
the unit circle, we go on to keep sampling new points.
In your case, we might pick a random (x, z) point and
write a function which examines the neighborhood and asks:
is the point "easy"?
Is it in the middle of a flat plain?
Or is it down a well or atop a mountain, hard to get near?
So you might keep rolling random numbers until an "interesting"
needle point is generated.
Putting the rest of the init code inside a function would
also be useful. Sooner or later you're going to want to write
unit tests
which will need to import this file,
and we want no side effects during that process,
such as the "30 seconds!" announcement.
Not something you need to worry about just yet.
accumulated timing errors
time.sleep(1)
timer += 1 | {
"domain": "codereview.stackexchange",
"id": 44827,
"lm_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, minecraft",
"url": null
} |
python, minecraft
accumulated timing errors
time.sleep(1)
timer += 1
Ok, here's a bit of a nerdy digression,
which you might just ignore for now.
tl;dr: No changes recommended ATM.
Please understand that if we look at the guarantees it makes,
the sleep is actually sleeping for 1 + epsilon seconds.
There might be other tasks scheduled on your computer,
and the sleep() is eligible to wake up after 1.0 seconds,
but it might take a little longer for the OS to get around
to finishing up with another task and then scheduling your task.
Plus it takes you more than zero seconds to
compute a message and send it.
So there is an error term here, which accumulates on each iteration.
Imagine this game lasted for some minutes, and it was important
to get the player to the train station on time before a
scheduled departure. We'd be sad for errors to accumulate
and arrive just as the minecraft train pulled out of the station.
A standard approach to dealing with such scheduling uncertainty
is to see how long until next deadline,
typically less than 1 second,
and request that much delay:
t0 = time.time()
while True:
timer += 1
time.sleep(t0 + timer - time.time())
The current exercise certainly doesn't require that level of fidelity.
Kudos for the x, y, z tuple unpack
when getting position of player, very nice.
If you had run any linters over this code you probably would have
noticed that pos is unused and may be safely deleted.
consistent comparisons
We have two things going on within this loop,
and I recommend you break out two helpers:
def report_on_time()
def report_on_distance() | {
"domain": "codereview.stackexchange",
"id": 44827,
"lm_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, minecraft",
"url": null
} |
python, minecraft
def report_on_time()
def report_on_distance()
I like the 25 <= timer < 30 expression,
and I like how the timer tests are organized in sequence.
I'm a little concerned about one aspect of game play.
In the final five seconds, it appears we send a countdown
and we don't send hot/cold advice, which seems bad
for the poor panicked player who is wandering around blindly.
When I look at the distance tests it seems we want
a helper like this:
def distance_description(distance):
if distance > 100:
return "Freezing"
elif distance > 50:
return "Cold"
elif distance > 25:
return "Warm"
elif ...
The the loop could just do mc.postToChat(distance_description(distance)).
covering all cases
Let's focus on the end of that distance description.
elif distance > 12:
mc.postToChat("Boiling")
elif 3 < distance < 12:
mc.postToChat("On fire!")
elif int(distance) in range(0,3):
mc.postToChat("Found it in " + str(timer-1) + " seconds!")
Above I complimented your 25 <= timer < 30 chained comparison
as being appropriate and expressive.
But here I'm going to criticize the 3 < distance < 12
expression as being out-of-place, inconsistent
with the previous logic.
It would have been enough to say
elif distance > 3:
given that other cases were already dealt
with by the clauses above.
elif int(distance) in range(0,3):
Ok, two criticisms of that line.
It's not consistent with the previous clauses, for no reason.
And worse, it means elif 0 >= distance > 3:.
Which might be fine.
But hey, what happened to 3?!?
When distance is exactly 3 we offer the player no advice at all.
(This sometimes is masked by the "final five seconds" effect noted above.)
mc.postToChat("Found it in " + str(timer-1) + " seconds!") | {
"domain": "codereview.stackexchange",
"id": 44827,
"lm_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, minecraft",
"url": null
} |
python, minecraft
mc.postToChat("Found it in " + str(timer-1) + " seconds!")
Relying on timer is not so bad.
But if we cared about accumulated sleep timing error,
or wanted to report the result in tenths of a second
for tie-breaking on some leader-board, then asking for the current
time()
would make sense.
Plus we'd want to sleep much less than one second
for each time through the loop.
You might choose to update at a higher rate,
say FPS = 10 ten frames per second.
Sleep for ~ 100 msec each time through the loop,
and produce a combined time and distance message,
outputting it with
if prev_msg != current_msg:
mc.postToChat(current_msg)
prev_msg = current_msg
Higher frame rates offer a better opportunity
for breaking leader-board tie scores.
This code mostly accomplishes its design goals,
and suggests avenues for exploration.
I would be willing to delegate or accept
maintenance tasks on this codebase. | {
"domain": "codereview.stackexchange",
"id": 44827,
"lm_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, minecraft",
"url": null
} |
python, beginner, python-3.x
Title: Python 3 script that draws animals using basic functions
Question: I'm new to Python and only started learning a couple months ago. I get that this is a really unsophisticated code and I'm a newbie, but are there any blatant issues with it that I can improve upon? I just kind of threw everything I know together to see if I'm cut out for this kind of thing.
Also I'm a first time poster so I do apologize in advance if something is not said with etiquette.
# Attempts to respond to all possible inputs
# This block just asks the user's name
print('Hello!\nMy name is Monty!')
print("\nWhat's your name?")
user_name = input() # I want to eventually import some sort of 'autocorrect' library if that exists
print(f'\nHi {user_name.title()}!')
print('Nice to meet you.\n')
# This block asks the user's fav color
favorite_color = input('What is your favorite color or colors?\n')
print('\n'+favorite_color[0].upper() + favorite_color[1:].lower(), 'just happens to be my favorite too!')
print('Amazing!\n')
# This block contains lists for later use
yes_list = ['yes', 'Yes', 'y', 'Y', 'yeah', 'Yeah', 'ye', 'Ye', 'yes please', 'yes, please', 'sure', 'Sure',
'of course', 'of course!', 'definitely', 'Definitely']
no_list = ['no', 'No', 'n', 'N', 'nah', 'Nah', 'nope', 'Nope', 'no thanks',
'No thanks', 'No, thanks', 'No, thank you', 'no thank you.', 'no, thank you']
dog_list = ['dog', 'Dog', 'the dog', 'The dog', 'doggie', 'Doggie', 'a dog']
cat_list = ['cat', 'Cat', 'the cat', 'The cat', 'kittie', 'Kittie']
mouse_list = ['mouse', 'Mouse', ' the mouse', 'The mouse', 'mousy', 'Mousy']
draw_list = ['draw', 'Draw', 'DRAW', 'please draw', 'Please draw', 'PLEASE DRAW',
'draw please', 'Draw please', 'DRAW PLEASE', 'draw, please', 'Draw, please']
emptyAnimal_list = []
newEmptyAnimal_list = []
animalsNotViewed_list = []
animalListContents = ['> dog drawing', '> cat drawing', '> mouse drawing']
are_ya_sure = ['No']
separator = '' | {
"domain": "codereview.stackexchange",
"id": 44828,
"lm_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, python-3.x",
"url": null
} |
python, beginner, python-3.x
# This block asks the user if they want the program to draw
print('I can draw a dog, a cat, or a mouse, ya know!')
print('Do you want me to draw one?')
start = 0
while start == 0: # Primary while loop
drawing_decision = input()
if drawing_decision in dog_list or drawing_decision in cat_list or drawing_decision in mouse_list: # User must say something in yes or no list first
print("\nYes or no please! Try again.")
continue # Brings to the top of primary while loop
elif drawing_decision not in dog_list and drawing_decision not in cat_list and drawing_decision not in mouse_list\
and drawing_decision not in yes_list and drawing_decision not in no_list: # If user types another animal, it will reject
print('\nI can only draw a dog, cat, or mouse!')
if drawing_decision in yes_list: # If user responds correctly, enter secondary while loop
animal_selection = 0
while animal_selection == 0:
print("\nWhich one do you want me to draw?")
animal_selection = input()
if animal_selection in dog_list: # If user responds dog, print dog
print('\nHere I go!\nBam:')
print(''' ㅤ / ̄ ̄ヽ_
/^ヽ ・ ●
|# | __ノ
`―-)=( / ̄\/ ̄\
/ㅤ ) l | |
c( ノ \ /
_」 LL_ \ /
(__)_)''')
print("It's Snoopy!\n")
print('Do you want me to draw any other one?')
emptyAnimal_list.append('> dog drawing') # Append to empty list for later
other_animals = input() # Do you want to draw another one?
if other_animals in yes_list:
animal_selection = 0
elif other_animals in no_list: # If not, thank them and list drawings viewed | {
"domain": "codereview.stackexchange",
"id": 44828,
"lm_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, python-3.x",
"url": null
} |
python, beginner, python-3.x
elif other_animals in no_list: # If not, thank them and list drawings viewed
if '> dog drawing' in emptyAnimal_list and '> cat drawing' in emptyAnimal_list \
and '> mouse drawing' in emptyAnimal_list:
print('\nI hope you enjoyed my 3 drawings!')
print("They're not the best, but they're the only 3 I can draw, for I am a lowly automaton!")
emptyAnimal_list.append('> dog drawing')
break
else:
print('\nI hope you enjoyed my:\n')
for x in emptyAnimal_list:
if x not in newEmptyAnimal_list:
newEmptyAnimal_list.append(x)
print('\n'.join(newEmptyAnimal_list))
print(f"\nI'm able to draw 3 but at least you saw {len(newEmptyAnimal_list)} of them!")
for x in animalListContents:
if x not in newEmptyAnimal_list:
animalsNotViewed_list.append(x)
print("I hope you're able to see my:\n")
print('\n'.join(animalsNotViewed_list),'\n')
print('Next time!')
elif other_animals in dog_list or other_animals in cat_list or other_animals in mouse_list: # If user enters an accepted animal before yes or no, reprimand and continue
print("Yes or no next time! But go ahead:")
animal_selection = 0
else: # If user asks to draw an unaccepted animal
animal_selection = 1
print('I can only draw a dog, cat, or mouse!')
while animal_selection == 1:
animal_selection = 0
elif animal_selection in cat_list: # If user responds cat, print cat | {
"domain": "codereview.stackexchange",
"id": 44828,
"lm_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, python-3.x",
"url": null
} |
python, beginner, python-3.x
elif animal_selection in cat_list: # If user responds cat, print cat
print('\nHere I go!\nBam:')
print(''' /> フ
| _ _|
/` ミ_xノ
/ |
/ ヽ ノ
│ | | |
/ ̄| | | |
( ̄ヽ__ヽ_)__)
\二)''')
print("Meow\n")
print('Do you want me to draw any other one?')
emptyAnimal_list.append('> cat drawing') # Append to empty list for later
other_animals = input() # Do you want to draw another one?
if other_animals in yes_list:
animal_selection = 0
elif other_animals in no_list: # If not, thank them and list drawings viewed
if '> dog drawing' in emptyAnimal_list and '> cat drawing' in emptyAnimal_list \
and '> mouse drawing' in emptyAnimal_list:
print('\nI hope you enjoyed my 3 drawings!')
print("They're not the best, but they're the only 3 I can draw, for I am a lowly automaton!")
emptyAnimal_list.append('> cat drawing')
break
else:
print('\nI hope you enjoyed my:\n')
for x in emptyAnimal_list:
if x not in newEmptyAnimal_list:
newEmptyAnimal_list.append(x)
print('\n'.join(newEmptyAnimal_list))
print(f"\nI'm able to draw 3 but at least you saw {len(newEmptyAnimal_list)} of them!")
for x in animalListContents:
if x not in newEmptyAnimal_list:
animalsNotViewed_list.append(x)
print("I hope you're able to see my:\n") | {
"domain": "codereview.stackexchange",
"id": 44828,
"lm_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, python-3.x",
"url": null
} |
python, beginner, python-3.x
print("I hope you're able to see my:\n")
print('\n'.join(animalsNotViewed_list),'\n')
print('Next time!')
elif other_animals in dog_list or other_animals in cat_list or other_animals in mouse_list: # If user enters an accepted animal before yes or no, reprimand and continue
print("Yes or no next time! But go ahead:")
animal_selection = 0
else: # If user asks to draw an unaccepted animal
animal_selection = 1
print('I can only draw a dog, cat, or mouse!')
while animal_selection == 1:
animal_selection = 0
elif animal_selection in mouse_list: # If user responds mouse, print mouse
print('\nHere I go!\nBam:')
print(r''' .-"""-.
/ \
.-"""-.-`.-.-.</ _
/ _,-\ ()()_/:)
\ / , ` `|
'-..-| \-.,___, /
\ `-.__/ /
`-.__.-'`''')
print("It's Mickey!\n")
print('Do you want me to draw any other one?')
emptyAnimal_list.append('> mouse drawing') # Append to empty list for later
other_animals = input() # Do you want to draw another one?
if other_animals in yes_list:
animal_selection = 0
elif other_animals in no_list: # If not, thank them and list drawings viewed
if '> dog drawing' in emptyAnimal_list and '> cat drawing' in emptyAnimal_list \
and '> mouse drawing' in emptyAnimal_list:
print('\nI hope you enjoyed my 3 drawings!')
print("They're not the best, but they're the only 3 I can draw, for I am a lowly automaton!")
emptyAnimal_list.append('> mouse drawing') | {
"domain": "codereview.stackexchange",
"id": 44828,
"lm_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, python-3.x",
"url": null
} |
python, beginner, python-3.x
emptyAnimal_list.append('> mouse drawing')
break
else:
print('\nI hope you enjoyed my:\n')
for x in emptyAnimal_list:
if x not in newEmptyAnimal_list:
newEmptyAnimal_list.append(x)
print('\n'.join(newEmptyAnimal_list))
print(f"\nI'm able to draw 3 but at least you saw {len(newEmptyAnimal_list)} of them!")
for x in animalListContents:
if x not in newEmptyAnimal_list:
animalsNotViewed_list.append(x)
print("I hope you're able to see my:\n")
print('\n'.join(animalsNotViewed_list),'\n')
print('Next time!')
elif other_animals in dog_list or other_animals in cat_list or other_animals in mouse_list: # If user enters an accepted animal before yes or no, reprimand and continue
print("Yes or no next time! But go ahead:")
animal_selection = 0
else: # If user asks to draw an unaccepted animal
animal_selection = 1
print('I can only draw a dog, cat, or mouse!')
while animal_selection == 1:
animal_selection = 0
elif animal_selection in no_list: # If user says no during 'which drawing' question
print("\nAre you sure you don't want to see any of my drawings?")
confirmation = 0
while confirmation == 0:
confirmation = input()
if confirmation in yes_list: # Exits this block
print(f'\nSorry you feel that way {user_name}!')
break
elif confirmation in no_list: # Returns to animal selection | {
"domain": "codereview.stackexchange",
"id": 44828,
"lm_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, python-3.x",
"url": null
} |
python, beginner, python-3.x
elif confirmation in no_list: # Returns to animal selection
print('\nOK!')
animal_selection = 0
break
else: # Asks exit confirmation question again
print("\nI'm not sure I understood. Do you want to leave or not?")
confirmation = 0
else: # If user asks to draw an unaccepted animal
animal_selection = 1
print('I can only draw a dog, cat, or mouse!')
while animal_selection == 1:
animal_selection = 0
print('\nGreat meeting you', user_name.title() + '!') # If user says no during additional drawing question
elif drawing_decision in no_list: # If user says no during first question regarding drawing
no_draw = 1
while no_draw == 1:
if no_draw == 1:
are_ya_sure.append('?')
print(separator.join(are_ya_sure))
print('\nAll ya gotta do is say "yes."')
break
no_draw = 1 | {
"domain": "codereview.stackexchange",
"id": 44828,
"lm_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, python-3.x",
"url": null
} |
python, beginner, python-3.x
Answer: A good go for a beginner, but it could do with a little tidying up.
Functions
While you may not have learned them yet, functions are essential to working with larger codes and breaking down structures. Here you have called them "blocks", but really they should be functions and written as such. You can write a function as follows:
# This block just asks the user's name
print('Hello!\nMy name is Monty!')
print("\nWhat's your name?")
user_name = input() # I want to eventually import some sort of 'autocorrect' library if that exists
print(f'\nHi {user_name.title()}!')
print('Nice to meet you.\n')
becomes
def print_introduction() -> str: # We can say what type the function returns
"""
This function greets the user and asks their name
Returns: their name
"""
print('Hello!\nMy name is Monty!')
user_name = input("What's your name? ")
print(f'\nHi {user_name.title()}!')
print('Nice to meet you.\n')
return user_name.title()
The indentetation delimits the function, string at the top (docstring) becomes the help (run this in Python and try help(print_introduction)), and this function returns the name in a standard format for later use if we want.
We can call (run) it with:
print_introduction() # Discards the returned name
user = print_introduction() # Stores the name in `user`
print(f"Oh! I guess you really are called {user}.")
Simpler Constants
You can simplify a lot of your constants down. Take yes_list:
yes_list = ['yes', 'Yes', 'y', 'Y', 'yeah', 'Yeah', 'ye', 'Ye', 'yes please', 'yes, please', 'sure', 'Sure',
'of course', 'of course!', 'definitely', 'Definitely'] | {
"domain": "codereview.stackexchange",
"id": 44828,
"lm_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, python-3.x",
"url": null
} |
python, beginner, python-3.x
It has a lot of manual case-insensitivity which you really don't need. You have already used str.upper(), str.lower() and str.title() so you know they exist. We can simplify it down to just:
# I have switched this to a tuple here
# Lists are used for things which might change as they are mutable
# Tuples are used for things which won't change as they are fixed. We can't add/remove or change the elements of a tuple
yes_list = ('yes' 'y', 'yeah', 'ye', 'yes please', 'yes, please', 'sure', 'of course', 'of course!', 'definitely')
if some_user_input.lower() in yes_list:
...
We still have some duplication though. Perhaps we just want to strip all punctuation from user input. Perhaps it's time for another function with arguments.
def preprocess_input(input_str: str) -> str:
"""
Removes all punctuation and downcases input_str
Returns: processed string
"""
output_str = "".join(letter for letter in input_str if letter.isalpha() or letter.isspace())
return output_str.lower()
yes_list = ('yes' 'y', 'yeah', 'ye', 'yes please', 'please', 'sure', 'of course', 'definitely')
some_user_input = "y.;eS;."
processed_user_input = preprocess_input(some_user_input)
if processed_user_input in yes_list:
...
Now we might not want this so flexible, but the beauty of a function is that you can write it once, use it everywhere and if you decide it's not quite right, you only have to change it once!
Say we actually wanted to collapse multiple spaces we just need to add one line to our function (output_str = " ".join(output_str.split())) and it's updated everywhere!
Simpler Logic
You do a lot of setting a variable to 0 and looping until it's not 0 anymore:
start = 0
while start == 0: # Primary while loop
Now start is never changed in your code. Do you actually want an infinite loop? Make it clear:
while True:
In other cases where the variable does change, you probably want to use a boolean (True or False)
confirmation = False
while not confirmation:
... | {
"domain": "codereview.stackexchange",
"id": 44828,
"lm_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, python-3.x",
"url": null
} |
python, beginner, python-3.x
In most cases you don't need the variable at all and you do seem to know about break, so use it with an infinite loop instead.
You have several unnecessary logic blocks:
animal_selection = 1
print('I can only draw a dog, cat, or mouse!')
while animal_selection == 1:
animal_selection = 0
This entire block is equivalent to:
print('I can only draw a dog, cat, or mouse!')
animal_selection = 0
With a lot of extra noise.
no_draw = 1
while no_draw == 1:
if no_draw == 1:
are_ya_sure.append('?')
print(separator.join(are_ya_sure))
print('\nAll ya gotta do is say "yes."')
break
no_draw = 1
is equivalent to:
no_draw = 1
are_ya_sure.append('?')
print(separator.join(are_ya_sure))
print('\nAll ya gotta do is say "yes."')
As the conditions are always True
Note here that are_ya_sure doesn't need to be a list, you can append to a str:
x = "Are you sure"
for _ in range(10):
x += "?"
print(x)
Building lists
To build lists, we don't really need to have them declared ahead of time. Python has what are called list comprehensions which allow us to write:
even_numbers = []
for number in range(10):
if number % 2 == 0:
even_numbers.append(number)
as simply:
even_numbers = [number for number in range(10) if number % 2 == 0]
In your case, the block:
newEmptyAnimal_list = []
for x in emptyAnimal_list:
if x not in newEmptyAnimal_list:
newEmptyAnimal_list.append(x)
Is trying to construct a list with no duplicates. We call this a set and we can do this simply as:
newEmptyAnimal_list = set(emptyAnimal_list)
Note, however, that a set is a different type to list (just as an int is not a float even though they both represent numbers), but we can convert it back to a list by doing:
newEmptyAnimal_list = list(set(emptyAnimal_list)) | {
"domain": "codereview.stackexchange",
"id": 44828,
"lm_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, python-3.x",
"url": null
} |
python, beginner, python-3.x
though generally this isn't usually necessary once you're used to using different types.
Consistency
You have a lot of newlines (\n) in various places in your strings; at the front, back, the middle. You also switch between using ' and " to delimit your strings. While not essential, sticking to one thing consistently makes it easier to modify your code in the future and work out why things aren't working.
Your variables are also a mixture of lowerCamelCase and snake_case. Pick one! PEP-8 recommends using UPPER_SNAKE for (global) constants, lower_snake for most other things.
Summary
I'm not going to write the whole thing for you, but I want to give you a bit of a framework to base the next version on:
YES_LIST = ( ... )
NO_LIST = ( ... )
...
def preprocess_input(input_str: str) -> str:
" As above "
...
def get_yes_no(prompt: str) -> bool:
...
def get_animal_to_draw() -> int:
...
def print_introduction() -> None:
" As above "
...
def draw_cat():
def draw_mouse():
def draw_dog():
...
def print_drawn_list_response(drawn_animals: set) -> None:
" Incomplete "
print("You've seen my {', '.join(drawn_animals)}. I can still draw ...")
def main():
drawn_animals = set()
user = print_introduction()
while len(drawn_animals) != 3:
if not drawn_animals: # Empty list/set is `False`
response = get_yes_no("Would you like me to draw an animal?")
else:
response = get_yes_no("Would you like me to draw another?")
if response:
to_draw = get_animal_to_draw()
if to_draw == "mouse":
draw_mouse()
elif ...
...
drawn_animals.add(to_draw)
print_drawn_list_response(drawn_animals)
else:
break
print(f"Great meeting you, {user}!")
# Will be a bit mysterious for now, but good practice to do
# See other questions as to why
if __name__ == "__main__":
main() | {
"domain": "codereview.stackexchange",
"id": 44828,
"lm_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, python-3.x",
"url": null
} |
python, beginner
Title: Python, loop trought in txt and print future login data
Question: I would like my program to check what account I am currently logged in to (it works, I entered it (login4) in a variable for testing)
and when it reaches the end of txt I want it to go back to the beginning. It also saves the current position in case the program is closed.
my txt file:
login1:password1
login2:password2
login3:password3
login4:password4
login5:password5
and my code:
import pickle
import os
username = "login4"
nextline = 0
accs = []
if os.path.exists("conf.pkl") == True:
with open('conf.pkl', 'rb') as f:
nextline = pickle.load(f)
else:
nextline = 0
##First start program
##print(nextline)
with open('logins.txt', 'r') as f:
lines = f.readlines()
for line in lines:
if line.find(username) != -1:
actualindex = lines.index(line)
if actualindex != len(lines)-1:
nextline = actualindex+1
with open('conf.pkl', 'wb') as f:
pickle.dump(nextline, f)
else:
nextline = 0
with open('conf.pkl', 'wb') as f:
pickle.dump(nextline, f)
for logins in lines:
login, password = logins.replace("\n", "").split(":")
accs.append([login,password])
print(accs[nextline][0], accs[nextline][1])
The code works as I would expect.
When it gets to login5, then it goes to login1.
My Question: Is everything written correctly or is it too complicated and could it be done more simply? I tried the best I can :) | {
"domain": "codereview.stackexchange",
"id": 44829,
"lm_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: What's fine?
It's great that you made a program that works. You have a level of understanding of the language and its libraries that allows you to solve problems.
For example, the usage of with ... as ...: is excellent.
Also, the use of variable names in plural and singular in for line in lines: is wonderful.
And, most recognizable: you are asking for feedback! This tells me that you are willing to learn. This is a good attitude.
Learning and improving needs time. Don't simply take the final output of this answer. Read everything and understand it. It's a long answer. (And maybe you see why such questions and answers don't fit on Stack Overflow).
Improvements when first reading
Let me read the code from top to bottom (since it is not split in classes or functions) and tell you what I would change.
accs = [] that name is not helpful when I first read the code.
if os.path.exists("conf.pkl") == True: the True check is redundant. exists() returns a boolean, which is true or false and you compare that boolean against True just to find out that it was true. This is called cargo cult programming. Simply write if os.path.exists("conf.pkl"):. See how that reads? If the file exists, then ...
else: nextline = 0 and ##First start program. These three lines do nothing. nextline is already 0.
##print(nextline) was probably for debugging purposes. Remove it. Get familiar in using a debugger and don't do println-debugging like in the 1990s.
if line.find(username) != -1: This line checks whether username is part of the line. The pythonic way of expressing this would be if username in line:.
actualindex = lines.index(line)
if actualindex != len(lines)-1:
nextline = actualindex+1
with open('conf.pkl', 'wb') as f:
pickle.dump(nextline, f)
else:
nextline = 0
with open('conf.pkl', 'wb') as f:
pickle.dump(nextline, f) | {
"domain": "codereview.stackexchange",
"id": 44829,
"lm_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
You have duplicate code here. Since the duplicate code is the last piece of code in each branch of the if-statement, you can simply write it after the branch and it will be executed in both cases, like so:
actualindex = lines.index(line)
if actualindex != len(lines)-1:
nextline = actualindex+1
else:
nextline = 0
with open('conf.pkl', 'wb') as f:
pickle.dump(nextline, f)
Be careful with the variable name f for this file. You have already used f for the input file.
with open('conf.pkl', 'wb') as configfile:
pickle.dump(nextline, configfile)
Now, let's look at this code:
actualindex = lines.index(line)
if actualindex != len(lines)-1:
nextline = actualindex+1
else:
nextline = 0
If you want numbers to wrap around and restart from 0, you can use the modulo function:
nextline = (lines.index(line) + 1) % len(lines)
The part logins.replace("\n", "") is not needed. Since you read the file using .readlines(), there are no more line breaks in a single line.
Applying all these changes, we get this code:
import pickle
import os
username = "login1"
nextline = 0
accs = []
if os.path.exists("conf.pkl"):
with open('conf.pkl', 'rb') as f:
nextline = pickle.load(f)
with open('logins.txt', 'r') as f:
lines = f.readlines()
for line in lines:
if username in line:
actualindex = lines.index(line) % len(lines)
with open('conf.pkl', 'wb') as configfile:
pickle.dump(nextline, configfile)
for logins in lines:
login, password = logins.split(":")
accs.append([login, password])
print(accs[nextline][0], accs[nextline][1]) | {
"domain": "codereview.stackexchange",
"id": 44829,
"lm_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
print(accs[nextline][0], accs[nextline][1])
I hope you could follow all the points and how your program is shorter and has less quirks.
One thing I do not understand yet is why you assign nextline at the very beginning from the contents of conf.pkl. It will be overwritten in any case. I assume that your program "works", but I have the feeling that there's something else to it and it's not complete yet. Probably you want to get rid of the line username = "login4" in a next step. I'll ignore that for now.
Restructuring on a higher level
With reading the code, I have now understood what it does and I can confirm that it works. Well done, and you probably get all points in an exam or so. But, you want to become an even better programmer, right? So let's look at the code again.
A lot of code can be spilt into 3 pieces: 1. receiving input, 2. processing and 3. providing output. Your program is interleaving 1 and 2. Your program can benefit if we split that.
You are reading a file which has a defined structure. Reading such a file according its structure is called parsing. You are doing this here:
with open('logins.txt', 'r') as f:
lines = f.readlines()
and several lines later here:
for logins in lines:
login, password = logins.split(":")
accs.append([login, password])
Do you see it? The first piece of code says: "the data is line-based". The second part says "the data is separated by colons". Let's move this closer together and fill accs earlier.
with open('logins.txt', 'r') as f:
lines = f.readlines()
for line in lines:
login, password = line.split(":")
accs.append([login, password]) | {
"domain": "codereview.stackexchange",
"id": 44829,
"lm_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
Next, rename login to username, because login is more like the combination of both.
From this point on, the whole file has been read and accs contains the login data. We no longer need the file f. The login data has been parsed fully. We can put a checkmark on step 1, which was receiving input.
Let's rename accs to logins.
Now we're much better prepared for step 2, processing the data, because the have the data in a nice structure. Basically, the logic is the same, but we no longer work on lines, but on logins instead:
for login in logins:
if login[0] == username:
nextline = (logins.index(login) + 1) % len(logins)
with open('conf.pkl', 'wb') as configfile:
pickle.dump(nextline, configfile)
Here's the complete program after this step:
import pickle
import os
username = "login5"
nextline = 0
logins = []
# Ignored for a moment
if os.path.exists("conf.pkl"):
with open('conf.pkl', 'rb') as f:
nextline = pickle.load(f)
# Step 1: Input
with open('logins.txt', 'r') as f:
lines = f.readlines()
for line in lines:
username, password = line.split(":")
logins.append([username, password])
# Step 2: Processing
for login in logins:
if login[0] == username:
nextline = (logins.index(login) + 1) % len(logins)
with open('conf.pkl', 'wb') as configfile:
pickle.dump(nextline, configfile)
# Step 3: Output
print(logins[nextline][0], logins[nextline][1]) | {
"domain": "codereview.stackexchange",
"id": 44829,
"lm_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
# Step 3: Output
print(logins[nextline][0], logins[nextline][1])
Splitting the steps is a major move towards maintainability. Once you know that the input step is correct, you can make modifications to the processing step without breaking something of the input step. This was not the case before.
Giving it more structure
There comments in the code above tell someone that you respected the input, processing, output principle. Let's do better and make these functions.
The first one is simple:
def read_logins():
logins = []
with open('logins.txt', 'r') as f:
lines = f.readlines()
for line in lines:
username, password = line.split(":")
logins.append([username, password])
return logins
Note how the global variable logins moved into the function.
The second one is also simple, except for finding a name which honestly describes what the function does:
def get_next_login_and_remember_the_line_in_the_config_file(logins, username):
nextline = 0
for login in logins:
if login[0] == username:
nextline = (logins.index(login) + 1) % len(logins)
with open('conf.pkl', 'wb') as configfile:
pickle.dump(nextline, configfile)
return nextline
Again, notice how the global variable nextline moved into the function.
Since the output is just one line of code, I'll leave that for now.
Moving the code into functions breaks our code and we need to adapt for that:
logins = read_logins()
nextline = get_next_login_and_remember_the_line_in_the_config_file(logins, username)
# Step 3: Output
print(logins[nextline][0], logins[nextline][1])
Now, let's create a typical Python main "method":
if __name__ == "__main__":
logins = read_logins()
nextline = get_next_login_and_remember_the_line_in_the_config_file(logins, username)
# Step 3: Output
print(logins[nextline][0], logins[nextline][1]) | {
"domain": "codereview.stackexchange",
"id": 44829,
"lm_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
Awesome. Your code now has some structure. Someone can decide whether or not to read a function. Typically, I skip over the functions first and look at the main "method", so see what the code does at a high level. In very short time I can now see:
it reads logins
it does something complicated to it
it provides the output
Getting this overview was not possible with the original code.
Information hiding
Let's think again. The code in the main "method" prints the next username and password. Does it care about the line index? No. Should the output method know about the data structure and be aware that username is at index 0 and password is at index 1? Also not.
Hiding internal information is a common thing to do. It enables you changing your implementation without the need of someone else adapting to those changes later.
Let's fix this: instead of returning the index withreturn nextline, we return the username and password directly. "Give me the next username and next password" will be the API from now on.
nextlogin = logins[nextline]
return nextlogin[0], nextlogin[1]
With this change, we can adapt the main "method" to
if __name__ == "__main__":
logins = read_logins()
nextusername, nextpassword = get_next_login_and_remember_the_line_in_the_config_file(logins, username)
print(nextusername, nextpassword)
Final result
import pickle
import os
def read_logins():
logins = []
with open('logins.txt', 'r') as f:
lines = f.readlines()
for line in lines:
username, password = line.split(":")
logins.append([username, password])
return logins | {
"domain": "codereview.stackexchange",
"id": 44829,
"lm_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
def get_next_login_and_remember_the_line_in_the_config_file(logins, username):
nextline = 0
for login in logins:
if login[0] == username:
nextline = (logins.index(login) + 1) % len(logins)
with open('conf.pkl', 'wb') as configfile:
pickle.dump(nextline, configfile)
nextlogin = logins[nextline]
return nextlogin[0], nextlogin[1]
if __name__ == "__main__":
# Ignored for a moment
if os.path.exists("conf.pkl"):
with open('conf.pkl', 'rb') as f:
nextline = pickle.load(f)
logins = read_logins()
username = "login5"
nextusername, nextpassword = get_next_login_and_remember_the_line_in_the_config_file(logins, username)
print(nextusername, nextpassword)
I still think there's something up with that conf.pkl file. Maybe you want to integrate that into the code so that it's actually used.
At the moment this unused feature makes the method name get_next_login_and_remember_the_line_in_the_config_file so long and complicated.
Once you integrated that, you can then come back and ask for a code review again.
Hacking it
I was a tester once in my life. And while you say "it works", I can also see how it doesn't work. It's a skill to switch between the developer view and the tester or hacker view. Once your program works, ask yourself: how would someone make it break and misuse it. Some thoughts for you:
what happens if the file logins.txt does not exist?
what happens, if the username or password contains a :?
what happens if the password contains the username? Compare this in the your original version and the version we have now. Did we accidentally fix a bug while changing the code? | {
"domain": "codereview.stackexchange",
"id": 44829,
"lm_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
Next up learning
As for the duplicate file f, a decent Python IDE, like PyCharm, would have told you. Use tools to your advantage and let your brain work less.
As mentioned before, I see indications of "println debugging". I imagine that it would be beneficial to you to learn How to debug small programs.
Have a look into unit tests. Especially the : hacking case makes a nice unit test.
Thanks
Thank you for providing the code and not being afraid of feedback. It may look like a lot - and yes, it is. This does not mean that you are stupid. I give this feedback not to discourage you or demotivate you. You don't need to do all this perfectly next time.
Pick those parts of the feedback that you understood. Integrate those into your next code. Ask for feedback again and improve again. Informatics has so many topics and so many technology that it's required to learn all life long.
Read your original code in 3 years and you'll probably say "this was horrible" - and at the same time, be happy that you write much better code then.
I finished my studies in 2003. And yet I'm a beginner on so many topics. I still get downvotes on Stack Overflow with 20 years of experience - just because something is new to me and I'm trying to understand. Do I care? Those downvotes mean nothing. I know that I'm on the right track, even when someone else thinks it's a stupid question. | {
"domain": "codereview.stackexchange",
"id": 44829,
"lm_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
} |
javascript, game, html, css, hangman
Title: Hangman Game in HTML + CSS + JS
Question: I recently developed a hangman game with HTML, CSS and JavaScript and I would like to get your feedback and tips to improve it. The goal of the game is to guess a secret word before 6 incorrect guesses are completed.
I would like feedback on how I can improve the readability, efficiency and overall structure of the code. I am also open to suggestions on coding practices and standards I should follow.
Game screenshot:
Code:
const BLANKS_TAG = document.getElementById("current-word");
const VIRTUAL_KEYS = document.getElementById("virtual-keys");
const HINT_BUTTON = document.getElementById("hint-button");
const NEW_WORD_BUTTON = document.getElementById("new-word-button");
const HANGMAN_IMAGE = document.getElementById("hangman-image");
const MAX_TRIALS = 6;
let trials = MAX_TRIALS;
let hintUsed;
let blanks;
let words;
let secretWord;
let secretWordArray;
/**
* Updates the hangman image based on the number of attempts remaining.
*/
function updateHangmanImage() {
HANGMAN_IMAGE.src = `img/${MAX_TRIALS - trials}.png`;
}
/**
* Updates the blanks with the correctly guessed letter and marks the
* corresponding span element as correct.
* @param {string} LETTER - The letter to guess.
* @returns {boolean} Returns true if it's a good guess, false otherwise.
*/
function guessAndUpdateBlanks(LETTER) {
const SPANS = BLANKS_TAG.querySelectorAll("span");
let isGoodGuess = false;
let lastCorrectSpan = null;
for (const [I, CHAR] of secretWordArray.entries()) {
if (CHAR === LETTER) {
isGoodGuess = true;
blanks[I] = LETTER;
lastCorrectSpan = SPANS[I];
}
}
if (lastCorrectSpan) lastCorrectSpan.classList.remove("correct");
if (isGoodGuess) return true;
else return false;
} | {
"domain": "codereview.stackexchange",
"id": 44830,
"lm_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, game, html, css, hangman",
"url": null
} |
javascript, game, html, css, hangman
if (isGoodGuess) return true;
else return false;
}
/**
* Replaces the guessed letters in the string of blanks and updates the hangman image if the guess is incorrect.
* @param {boolean} IS_GOOD_GUESS - Indicates if the guess is correct.
* @param {string} LETTER - The guessed letter.
*/
function replaceGuessedLetters(IS_GOOD_GUESS, LETTER) {
if (IS_GOOD_GUESS) {
const BLANKS_STRING = blanks.join(" ");
const UPDATED_BLANKS_STRING = BLANKS_STRING.replace(
new RegExp(LETTER, "gi"),
`<span class="correct">${LETTER}</span>`
);
BLANKS_TAG.innerHTML = UPDATED_BLANKS_STRING;
} else {
trials--;
updateHangmanImage();
}
}
/**
* Provides a hint by disabling a number of letters that are not in the secret word.
*/
function hint() {
HINT_BUTTON.style.visibility = "hidden";
hintUsed = true;
const VIRTUAL_KEYS_CHILDREN = Array.from(
VIRTUAL_KEYS.querySelectorAll(".btn:not(.disabled)")
);
const MAX_LETTERS_TO_SHOW = Math.floor(Math.random() * 6) + 1;
const INDEXES = [];
while (INDEXES.length < MAX_LETTERS_TO_SHOW) {
const RANDOM_INDEX = Math.floor(
Math.random() * VIRTUAL_KEYS_CHILDREN.length
);
const BUTTON = VIRTUAL_KEYS_CHILDREN[RANDOM_INDEX];
const LETTER = BUTTON.getAttribute("data-value");
if (!INDEXES.includes(RANDOM_INDEX) && !secretWordArray.includes(LETTER)) {
BUTTON.classList.add("disabled");
INDEXES.push(RANDOM_INDEX);
}
}
}
/**
* Checks the game result and displays the secret word accordingly.
*/
function checkGameResult() {
const BLANKS_STRING = blanks.join("");
BLANKS_TAG.textContent = secretWord;
NEW_WORD_BUTTON.style.visibility = "visible";
if (BLANKS_STRING === secretWord) BLANKS_TAG.classList.add("correct");
else BLANKS_TAG.classList.add("incorrect");
} | {
"domain": "codereview.stackexchange",
"id": 44830,
"lm_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, game, html, css, hangman",
"url": null
} |
javascript, game, html, css, hangman
/**
* Initialize the game and choose a secret word at random.
*/
function initializeGame() {
NEW_WORD_BUTTON.style.visibility = "hidden";
BLANKS_TAG.classList.remove("correct", "incorrect");
VIRTUAL_KEYS.querySelectorAll(".btn").forEach((BUTTON) => {
BUTTON.classList.remove("disabled");
});
secretWord = words[Math.floor(Math.random() * words.length)];
trials = MAX_TRIALS;
blanks = Array(secretWord.length).fill("_");
secretWordArray = secretWord.split("");
hintUsed = false;
BLANKS_TAG.textContent = blanks.join(" ");
updateHangmanImage();
}
/**
* Manages the game event when a virtual key is clicked.
* @param {Event} event - The click event object.
*/
function play(event) {
if (trials === 0 || !blanks.includes("_")) return;
const BUTTON = event.target;
const LETTER = BUTTON.getAttribute("data-value");
const IS_GOOD_GUESS = guessAndUpdateBlanks(LETTER);
replaceGuessedLetters(IS_GOOD_GUESS, LETTER);
BUTTON.classList.add("disabled");
if (trials === 1 && !hintUsed) HINT_BUTTON.style.visibility = "visible";
if (!trials || !blanks.includes("_")) checkGameResult();
}
fetch("./words.txt")
.then((response) => response.text())
.then((data) => {
words = data.split(" ");
initializeGame();
})
.catch((error) => {
console.error(`Error reading word file: ${error}`);
});
document.addEventListener("click", (event) => {
const TARGET = event.target;
if (TARGET === NEW_WORD_BUTTON) {
initializeGame();
} else if (TARGET.parentNode === VIRTUAL_KEYS) {
play(event);
} else if (TARGET === HINT_BUTTON) {
hint();
}
});
body {
max-width: 100vw;
max-height: 100vh;
}
header {
margin-top: 20px;
margin-bottom: 20px;
}
h1 {
text-align: center;
}
.game-stage {
min-height: 350px;
max-height: 350px;
display: flex;
align-items: center;
justify-content: center;
} | {
"domain": "codereview.stackexchange",
"id": 44830,
"lm_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, game, html, css, hangman",
"url": null
} |
javascript, game, html, css, hangman
.game-current-word {
min-height: 50px;
max-height: 50px;
display: flex;
justify-content: center;
font-size: 22px;
font-weight: bold;
}
.virtual-keyboard {
min-height: 80px;
max-height: 80px;
max-width: 100vw;
}
.virtual-keys {
max-width: 600px;
display: flex;
justify-content: center;
align-items: center;
flex-wrap: wrap;
margin: 15px auto;
}
.btn {
background: none;
border: 0;
background-color: #0066cc;
box-shadow: 2px 2px 1px #036;
color: #f3ffff;
cursor: pointer;
font: inherit;
font-weight: bold;
line-height: normal;
overflow: visible;
width: 35px;
height: 35px;
border-radius: 5px;
display: flex;
align-items: center;
justify-content: space-evenly;
padding: 0 10px;
margin: 5px;
}
.hint-button,
.new-word-button {
width: 40px;
font-size: 12px;
visibility: hidden;
}
.disabled {
background-color: #fff;
color: #000;
pointer-events: none;
cursor: not-allowed;
}
.correct {
color: green;
font-size: 25px;
}
.incorrect {
color: red;
font-size: 25px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>Hangman game</title>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" type="text/css" href="assets/normalize.css">
<link rel="stylesheet" type="text/css" href="assets/style.css" />
<script src="assets/index.js" defer></script>
</head>
<body>
<header><h1>Hangman game</h1></header>
<section class="game-stage">
<button type="button" class="btn hint-button" id="hint-button">Hint?</button>
<img id="hangman-image"/>
<button type="button" class="btn new-word-button" id="new-word-button">New Word</button>
</section>
<section class="game-current-word">
<p id="current-word"></p>
</section> | {
"domain": "codereview.stackexchange",
"id": 44830,
"lm_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, game, html, css, hangman",
"url": null
} |
javascript, game, html, css, hangman
<section class="game-current-word">
<p id="current-word"></p>
</section>
<section class="virtual-keyboard">
<div class="virtual-keys" id="virtual-keys">
<button type="button" class="btn" data-value="a">A</button>
<button type="button" class="btn" data-value="b">B</button>
<button type="button" class="btn" data-value="c">C</button>
<button type="button" class="btn" data-value="d">D</button>
<button type="button" class="btn" data-value="e">E</button>
<button type="button" class="btn" data-value="f">F</button>
<button type="button" class="btn" data-value="g">G</button>
<button type="button" class="btn" data-value="h">H</button>
<button type="button" class="btn" data-value="i">I</button>
<button type="button" class="btn" data-value="j">J</button>
<button type="button" class="btn" data-value="k">K</button>
<button type="button" class="btn" data-value="l">L</button>
<button type="button" class="btn" data-value="m">M</button>
<button type="button" class="btn" data-value="n">N</button>
<button type="button" class="btn" data-value="o">O</button>
<button type="button" class="btn" data-value="p">P</button>
<button type="button" class="btn" data-value="q">Q</button>
<button type="button" class="btn" data-value="r">R</button>
<button type="button" class="btn" data-value="s">S</button>
<button type="button" class="btn" data-value="t">T</button>
<button type="button" class="btn" data-value="u">U</button>
<button type="button" class="btn" data-value="v">V</button>
<button type="button" class="btn" data-value="w">W</button>
<button type="button" class="btn" data-value="x">X</button>
<button type="button" class="btn" data-value="y">Y</button>
<button type="button" class="btn" data-value="z">Z</button>
</div>
</section>
</body>
</html> | {
"domain": "codereview.stackexchange",
"id": 44830,
"lm_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, game, html, css, hangman",
"url": null
} |
javascript, game, html, css, hangman
Github repository: https://github.com/xSyrax123/hangman
Thank you in advance for your help and constructive comments. | {
"domain": "codereview.stackexchange",
"id": 44830,
"lm_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, game, html, css, hangman",
"url": null
} |
javascript, game, html, css, hangman
Answer: JS
It feels a tad weird to me seeing stuff that isn't top-level constants named in ALL_CAPS like that. To be clear, I'm not saying that naming function parameters and local const variables that way is wrong, write how you like, I just find it a bit unusual
Instead of a disabled class, I'd use the element attribute with the same name. That by itself keeps it from triggering events without needing the pointer-events css, and it also makes sure we disable other ways of clicking the button (like, say, keyboard navigation. Try using the tab key to highlight a button, then pressing the space bar a few times). For styling disabled elements, we don't need a class, but can instead use the :disabled selector
guessAndUpdateBlanks
The logic behind whatever is going on with this function and BLANKS_TAG makes very little sense to me. Fortunately, as we immediately move on to replaceGuessedLetters once we're done here, and that function completely replaces the contents of BLANKS_TAG, none of it actually matters. So I say let's just remove that stuff, leaving this function responsible for updating blanks only
Also, low-hanging fruit, but if (isGoodGuess) return true; else return false; just reduces to return isGoodGuess
replaceGuessedLetters
The name feels misleading. If this function's job is only to replace guessed letters, it would do nothing in the event of a bad guess, but this does not seem to be the case. Renaming it to clarify its function could help, but I'd consider splitting it into two handleGoodGuess() and handleBadGuess() functions
hint | {
"domain": "codereview.stackexchange",
"id": 44830,
"lm_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, game, html, css, hangman",
"url": null
} |
javascript, game, html, css, hangman
hint
The loop does not exit until we've found a certain number of un-guessed letters that are not in the word. This is a problem if the word is something like "subdermatoglyphic", because we might run out of such letters before we've disabled enough of them, and then we'll just keep looping forever. An approach that only loops a fixed number of times, guaranteeing a unique item is disabled each pass (if one exists), could be one way to avoid this. An implementation of that might look a bit like the following:
const CANDIDATES_FOR_DISABLING = new Set(Array.from(document.querySelectorAll("#virtual-keys > button:enabled")).filter(BTN => ! secretWordArray.includes(BTN.getAttribute("data-value")))); | {
"domain": "codereview.stackexchange",
"id": 44830,
"lm_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, game, html, css, hangman",
"url": null
} |
javascript, game, html, css, hangman
for (let i = 0; CANDIDATES_FOR_DISABLING.size > 0 && i < MAX_LETTERS_TO_SHOW; ++i) {
const BUTTON = Arrays.from(CANDIDATES_FOR_DISABLING.values())[Math.floor(Math.random() * CANDIDATES_FOR_DISABLING.size)];
BUTTON.setAttribute("disabled", "");
CANDIDATES_FOR_DISABLING.delete(BUTTON);
}
HTML
The buttons that make up the virtual keyboard feel a bit repetetive. I'd be tempted to try and generate them programmatically. Perhaps with something like:
for (const CHAR of ALPHABET) {
const BUTTON = document.createElement("button");
BUTTON.setAttribute("data-value", CHAR.toLowerCase());
BUTTON.innerText = CHAR.toUpperCase();
BUTTON.addEventListener("click", EVT => play(EVT));
VIRTUAL_KEYS.append(BUTTON);
}
I also don't see the point of the btn class. It looks like we apply it to all button elements. So why not just query for button-type elements instead of elements with the btn class? The .btn rule in the CSS could just as easily be a button rule, no?
Finally, the "current word" and "hint button" elements already have IDs, so assigning unique classes to them as well feels kind of pointless when it seems like we could just use the IDs instead | {
"domain": "codereview.stackexchange",
"id": 44830,
"lm_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, game, html, css, hangman",
"url": null
} |
json, rust, web-scraping
Title: Enum to deserialize HTML sizes from JSON with serde
Question: I added an enum for my webscraper to deserialize data from a JSON field that represents an HTML image size, which can either be an unsigned int like 1080 or a string like "100%":
use serde::Deserialize;
use std::fmt::{Display, Formatter};
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum HtmlSize {
String(String),
Int(u64),
}
impl Display for HtmlSize {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
Self::String(string) => write!(f, r#""{}""#, string),
Self::Int(int) => write!(f, "{}", int),
}
}
}
impl<'de> Deserialize<'de> for HtmlSize {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
deserializer.deserialize_any(HtmlSizeVisitor)
}
}
struct HtmlSizeVisitor;
impl<'de> serde::de::Visitor<'de> for HtmlSizeVisitor {
type Value = HtmlSize;
fn expecting(&self, formatter: &mut Formatter) -> std::fmt::Result {
write!(
formatter,
"an unsigned integer or a string representing a width"
)
}
fn visit_u64<E: serde::de::Error>(self, n: u64) -> Result<HtmlSize, E> {
Ok(HtmlSize::Int(n))
}
fn visit_str<E: serde::de::Error>(self, string: &str) -> Result<HtmlSize, E> {
Ok(HtmlSize::String(string.to_string()))
}
}
Example usage:
#[derive(Clone, Debug, Deserialize, Eq, PartialEq)]
pub struct ImageInfo {
id: String,
alt: String,
height: HtmlSize,
src: String,
width: HtmlSize,
caption: String,
credit: String,
}
I did not find anything readily available like this, so I implemented the above HtmlSize with its corresponding visitor. Is this a sensible implementation or did I reinvent the wheel? Can the implementation be improved? | {
"domain": "codereview.stackexchange",
"id": 44831,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "json, rust, web-scraping",
"url": null
} |
json, rust, web-scraping
Answer: You don't actually need to implement your own logic, you can use #[serde(untagged):
#[derive(Clone, Debug, Eq, PartialEq, Deserialize)]
#[serde(untagged)]
pub enum HtmlSize {
String(String),
Int(u64),
}
#[serde(untagged)] will deserialize into which enum variant matches the incoming data. | {
"domain": "codereview.stackexchange",
"id": 44831,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "json, rust, web-scraping",
"url": null
} |
c++, reinventing-the-wheel, c++20
Title: Constexpr flat_multimap
Question: About the Reasoning
I wrote a flat_multimap because it was slightly more efficient to read/write from disk (contiguous memory block) and because it would keep the logarithmic efficiency from a tree (using binary search). I tried to keep to the std::multimap standard, but there were several operations from std::vector which I couldn't help but implement (capacity, reserve, resize). I figured these would make sense to implement because they made sense to have in a sized and continuous container. There were also some methods from std::multimap that I didn't really think made sense to implement (emplace(Args&&...), insert(node_type&&)) because for emplace you can't really construct the element in place, you're going to have to move it around to sort it, and for insert, I wasn't really sure how I would implement it in tandem with extract.
The Code
#include <functional>
#include <algorithm>
#include <iterator>
#include <utility>
#include <vector> | {
"domain": "codereview.stackexchange",
"id": 44832,
"lm_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++, reinventing-the-wheel, c++20",
"url": null
} |
c++, reinventing-the-wheel, c++20
template <typename K, typename T, typename C = std::less<K>,
class A = std::allocator<std::pair<K, T>>>
requires std::predicate<C, K, K>
class flat_multimap {
public:
typedef std::pair<K, T> value_type;
typedef T mapped_type;
typedef K key_type;
typedef C key_compare;
typedef std::vector<value_type, A>::size_type size_type;
typedef std::vector<value_type, A>::difference_type difference_type;
typedef std::vector<value_type, A>::iterator iterator;
typedef std::vector<value_type, A>::const_iterator const_iterator;
typedef value_type& reference;
typedef const value_type& const_reference;
typedef std::allocator_traits<A>::pointer pointer;
typedef std::allocator_traits<A>::const_pointer const_pointer;
typedef std::reverse_iterator<iterator> reverse_iterator;
typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
typedef std::vector<value_type, A>::allocator_type allocator_type;
private:
std::vector<value_type, A> buffer;
C comparator;
public:
constexpr flat_multimap() : buffer(), comparator() {
};
explicit constexpr flat_multimap(const A& allocator)
: buffer(allocator), comparator() {
};
explicit constexpr flat_multimap(const C& comparator,
const A& allocator = A())
: buffer(allocator), comparator(comparator) {
};
constexpr flat_multimap(const flat_multimap& other) noexcept
: buffer(other.buffer), comparator(other.comparator) {
}
constexpr flat_multimap(flat_multimap&& other) noexcept
: buffer(std::move(other.buffer)),
comparator(std::move(other.comparator)) {
}
constexpr flat_multimap& operator=(const flat_multimap& other) noexcept {
return *this = flat_multimap(other);
}
constexpr flat_multimap& operator=(flat_multimap&& other) noexcept {
std::swap(buffer, other.buffer);
std::swap(comparator, other.comparator); | {
"domain": "codereview.stackexchange",
"id": 44832,
"lm_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++, reinventing-the-wheel, c++20",
"url": null
} |
c++, reinventing-the-wheel, c++20
std::swap(buffer, other.buffer);
std::swap(comparator, other.comparator);
return *this;
}
constexpr ~flat_multimap() {
}
constexpr allocator_type get_allocator() const noexcept {
return buffer.get_allocator();
}
constexpr size_type size() const noexcept {
return buffer.size();
}
constexpr size_type max_size() const noexcept {
return buffer.max_size();
}
constexpr size_type capacity() const noexcept {
return buffer.capacity();
}
constexpr void resize(size_type count) {
buffer.resize(count);
}
constexpr void reserve(size_type new_cap) {
buffer.reserve(new_cap);
}
constexpr void shrink_to_fit() {
buffer.shrink_to_fit();
}
constexpr bool empty() const noexcept {
return buffer.empty();
}
constexpr void clear() noexcept {
buffer.clear();
}
constexpr pointer data() noexcept {
return buffer.data();
}
constexpr const_pointer data() const noexcept {
return buffer.data();
}
constexpr iterator insert(const value_type& value) {
return buffer.insert(
std::upper_bound(
cbegin(), cend(), value,
[](const value_type& left, const value_type& right) {
return C()(left.first, right.first);
}),
value);
}
constexpr iterator insert(value_type&& value) {
const_iterator destination = std::upper_bound(
cbegin(), cend(), value,
[](const value_type& left, const value_type& right) {
return C()(left.first, right.first);
});
return buffer.insert(destination, std::move(value));
}
constexpr size_type erase(const key_type& key) {
const auto [first, last] = equal_range(key);
size_type dist = std::distance(first, last);
buffer.erase(first, last);
return dist;
} | {
"domain": "codereview.stackexchange",
"id": 44832,
"lm_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++, reinventing-the-wheel, c++20",
"url": null
} |
c++, reinventing-the-wheel, c++20
buffer.erase(first, last);
return dist;
}
constexpr size_type count(const key_type& key) const {
const auto [first, last] = equal_range(key);
return std::distance(first, last);
}
constexpr bool contains(const key_type& key) const {
const_iterator first = lower_bound(key);
return (!(first == buffer.cend()) and !(comparator(key, first->first)));
}
constexpr std::pair<iterator, iterator> equal_range(const key_type& key) {
return std::make_pair(lower_bound(key), upper_bound(key));
}
constexpr std::pair<const_iterator, const_iterator> equal_range(
const key_type& key) const {
return std::make_pair(lower_bound(key), upper_bound(key));
}
constexpr iterator lower_bound(const key_type& key) {
return std::lower_bound(begin(), end(), key,
[this](const value_type& left, const key_type& right) {
return comparator(left.first, right);
});
}
constexpr const_iterator lower_bound(const key_type& key) const {
return std::lower_bound(cbegin(), cend(), key,
[this](const value_type& left, const key_type& right) {
return comparator(left.first, right);
});
}
constexpr iterator upper_bound(const key_type& key) {
return std::upper_bound(
begin(), end(), key,
[this](const key_type& left, const value_type& right) {
return comparator(left, right.first);
});
}
constexpr const_iterator upper_bound(const key_type& key) const {
return std::upper_bound(
cbegin(), cend(), key,
[this](const key_type& left, const value_type& right) {
return comparator(left, right.first);
});
}
constexpr void merge(flat_multimap<K, T, C, A>& source) {
std::vector<value_type, A> vec(size() + source.size(), | {
"domain": "codereview.stackexchange",
"id": 44832,
"lm_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++, reinventing-the-wheel, c++20",
"url": null
} |
c++, reinventing-the-wheel, c++20
std::vector<value_type, A> vec(size() + source.size(),
buffer.get_allocator());
std::swap(buffer, vec);
std::merge(vec.cbegin(), vec.cend(), source.buffer.cbegin(),
source.buffer.cend(), buffer.begin(),
[this](const value_type& left, const value_type& right) {
return comparator(left.first, right.first);
});
source.clear();
}
constexpr void merge(flat_multimap<K, T, C, A>&& source) {
std::vector<value_type, A> vec(size() + source.size(),
buffer.get_allocator());
std::swap(buffer, vec);
std::merge(vec.cbegin(), vec.cend(), source.buffer.cbegin(),
source.buffer.cend(), buffer.begin(),
[this](const value_type& left, const value_type& right) {
return comparator(left.first, right.first);
});
source.clear();
}
constexpr iterator begin() noexcept {
return buffer.begin();
}
constexpr const_iterator begin() const noexcept {
return buffer.begin();
}
constexpr const_iterator cbegin() const noexcept {
return buffer.cbegin();
}
constexpr iterator end() noexcept {
return buffer.end();
}
constexpr const_iterator end() const noexcept {
return buffer.end();
}
constexpr const_iterator cend() const noexcept {
return buffer.cend();
}
constexpr reverse_iterator rbegin() noexcept {
return buffer.rbegin();
}
constexpr const_reverse_iterator rbegin() const noexcept {
return buffer.rbegin();
}
constexpr const_reverse_iterator crbegin() const noexcept {
return buffer.crbegin();
}
constexpr reverse_iterator rend() noexcept {
return buffer.rend();
}
constexpr const_reverse_iterator rend() const noexcept { | {
"domain": "codereview.stackexchange",
"id": 44832,
"lm_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++, reinventing-the-wheel, c++20",
"url": null
} |
c++, reinventing-the-wheel, c++20
return buffer.rend();
}
constexpr const_reverse_iterator rend() const noexcept {
return buffer.rend();
}
constexpr const_reverse_iterator crend() const noexcept {
return buffer.crend();
}
}; | {
"domain": "codereview.stackexchange",
"id": 44832,
"lm_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++, reinventing-the-wheel, c++20",
"url": null
} |
c++, reinventing-the-wheel, c++20
Concerns & Questions
In a lot of places, I have to compare a key of an entry to an entry, in which case I call the comparator by accessing the key of the entry. Could there be a more efficient way to do this?
An extension of the above point, could I implement emplace(Args&&...) to construct the key, and use something like std::upper_bound to call emplace on the vector buffer with the full set of arguments?
Do I need to implement the Rule of Five here, because I'm not actually managing any memory myself?
Should I implement the remainder of the std::multimap constructors?
Curiosities
I noticed while implementing merge that std::inplace_merge isn't constexpr, so I ended up using std::merge instead. Does anyone know why it isn't constexpr?
Answer: Try to match std::flat_multimap's interface
You already went quite far to make it look like a similar container from the standard library, but since we already know std::flat_multimap is going to be in C++23, it would be good if you could match its interface:
Add emplace()
There were also some methods from std::multimap that I didn't really think made sense to implement (emplace(Args&&...), insert(node_type&&)) because for emplace you can't really construct the element in place, you're going to have to move it around to sort it, and for insert, I wasn't really sure how I would implement it in tandem with extract. | {
"domain": "codereview.stackexchange",
"id": 44832,
"lm_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++, reinventing-the-wheel, c++20",
"url": null
} |
c++, reinventing-the-wheel, c++20
I would implement this even if it doesn't give you the same performance benefit it has in std::multimap; it still is useful to be able to forward arguments directly to the constructor instead of having the caller create a temporary object. Also, consider code that is currently using a regular std::multimap, and you wnat to convert it to flat_multimap for some reason, then it would be great if you didn't have to find and modify all existing calls to emplace().
Make the underlying container type a template parameter
It's great that you at least provided a way for the user to supply their own allocator, but even better would be to make it possible to change the underlying container type completely. For example, a std::deque could be used, which is a little bit slower to access, but has stable pointers, can hold non-movable types, and has much less overhead when calling resize().
std::flat_multimap also uses two containers: one for the keys and one for the values, which is more cache-friendly. Another benefit is that it's simpler to call the comparator.
Handle non-key_type keys
Suppose key_type is some large struct. Normally you would only compare one key_type to another key_type. However, it's not that rare to have a type A that actually be compared to a type B. Now suppose that I want to check if there is an entry in the map whose key matches some value that has a type different than key_type. Because you only have one contains() function that only accepts a const key_type& parameter, the compiler now has to create a temporary key_type from that value. This might be expensive.
The STL containers actually have overloads (starting at least for some member functions in C++14) that take arbitrary key types, so they can pass the provided values directly to the comparator without forcing any implicit conversions. So for example, in addition to your existing contains() you should:
template <typename K>
constexpr bool contains(const K& key) const { | {
"domain": "codereview.stackexchange",
"id": 44832,
"lm_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++, reinventing-the-wheel, c++20",
"url": null
} |
c++, reinventing-the-wheel, c++20
template <typename K>
constexpr bool contains(const K& key) const {
const_iterator first = lower_bound(key);
return !(first == buffer.cend()) and !(comparator(key, first->first));
} | {
"domain": "codereview.stackexchange",
"id": 44832,
"lm_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++, reinventing-the-wheel, c++20",
"url": null
} |
c++, reinventing-the-wheel, c++20
The same goes for all functions that take a key_type parameter.
Implement the rest of the constructors and member functions
Should I implement the remainder of the std::multimap constructors?
Yes, if you want this to be a drop-in replacement you should definitely do that, and also check for other missing member functions.
Remove or default the special member functions where possible
Do I need to implement the Rule of Five here, because I'm not actually managing any memory myself? | {
"domain": "codereview.stackexchange",
"id": 44832,
"lm_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++, reinventing-the-wheel, c++20",
"url": null
} |
c++, reinventing-the-wheel, c++20
Do I need to implement the Rule of Five here, because I'm not actually managing any memory myself?
You have implemented your own destructor and copy/move constructors/assignment operators, but they do exactly the same thing as what the compiler would generate itself. I would just remove all of them, this way you will also follow the rule of zero.
Be careful with noexcept
If you mark a member function noexcept, but something it does could actually throw, then instead the program will abort, with no possibility for the caller to catch the error. So you should only do this if you are absolutely sure nothing can throw.
Consider your copy constructor for example: it makes a copy of the underlying std::vector. But std::vector's own copy constructor is not noexcept, and it's easy to see why: it will allocate memory, and memory allocation can fail with std::bad_alloc.
I would remove noexcept from all the constructors and assignment operators. If you allow custom containers to be used, then you could consider using noexcept(…) with a parameter to pass through the noexceptness of the underlying operations. Note that most containers have noexcept move constructors and move assignment operators, but not all of them, so it would be safe for std::vector, but not if you allow arbitrary underlying containers.
Use comparator instead of C()
The comparator is an object that might have state. So you should always use the comparator function instead of creating a default-constructed temporary C() like you did in insert().
If you don't see why, consider:
template<typename K>
struct AscOrDescComparator {
bool descending{};
bool operator<(const K& lhs, const K& rhs) {
if (descending)
return lhs > rhs;
else
return lhs < rhs;
}
};
auto map = flat_multimap<int, int>(AscOrDescComparator<int>{true});
map.insert(…); // uses C(), which is ascending
map.count(…); // uses comparator, which is descending
About std::inplace_merge | {
"domain": "codereview.stackexchange",
"id": 44832,
"lm_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++, reinventing-the-wheel, c++20",
"url": null
} |
c++, reinventing-the-wheel, c++20
About std::inplace_merge
I noticed while implementing merge that std::inplace_merge isn't constexpr, so I ended up using std::merge instead. Does anyone know why it isn't constexpr?
The problem is that std::inplace_merge allocates a temporary buffer. Since C++20 you can use new in limit ways in constexpr contexts, and I would assume that the temporary buffer would be compatible with that. If there is no other reason why it couldn't be possible, then it might just be that the C++ standards committee hasn't come around to declare this constexpr yet.
Prefer using instead of typedef
This is just a minor issue, but I recommend you use using decalarations instead of typedefs. using more clearly separates the type from the name, which is especially important if you want to create aliases for arrays and function pointers. | {
"domain": "codereview.stackexchange",
"id": 44832,
"lm_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++, reinventing-the-wheel, c++20",
"url": null
} |
python-3.x, numpy, null
Title: Calculate length of continuous gaps
Question: So, I have a list with some nan values, out of which some are continuous. e.g, list = [1, 2, 3, np.nan, np.nan, 6, 7, np.nan, 9, np.nan,np.nan,np.nan, 12] For some necessary reason, I'd want to get the length of individual continuous gaps.
def find_continuous_gaps(data):
gap_starts = []
gap_lengths = []
current_gap_start = np.nan
for i, value in enumerate(data):
if value is np.nan:
if current_gap_start is np.nan:
current_gap_start = i
else:
if current_gap_start is not np.nan:
gap_starts.append(current_gap_start)
gap_lengths.append(i - current_gap_start)
current_gap_start = np.nan
if current_gap_start is not np.nan:
gap_starts.append(current_gap_start)
gap_lengths.append(len(data) - current_gap_start)
return gap_starts, gap_lengths
# Example usage
data = [1, 2, 3, np.nan, np.nan, 6, 7, np.nan, 9, np.nan, np.nan, np.nan, 12]
gap_starts, gap_lengths = find_continuous_gaps(data)
gap_sum = sum_individual_gaps(gap_lengths)
print("Gap starts:", gap_starts)
print("Gap lengths:", gap_lengths)
print("Sum of individual gaps:", gap_sum)
results:
Gap starts: [3, 7, 9]
Gap lengths: [2, 1, 3]
Sum of individual gaps: 6
Although it does the job, is there an elegant simpler way for this. Any help is appreciated.
Answer: You're already using Numpy, but unfortunately you aren't using it as intended. Either this was a shortcut to get a NaN (which, in a program that doesn't otherwise use Numpy, should be done via float('nan')); or you need to delete all of your code and vectorise. For small input the benefit is dubious; for large input this will probably be faster.
import numpy as np
data = np.array([1, 2, 3, np.nan, np.nan, 6, 7, np.nan, 9, np.nan, np.nan, np.nan, 12])
is_nan = np.isnan(data)
differential = np.diff(is_nan.astype(int)) | {
"domain": "codereview.stackexchange",
"id": 44833,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python-3.x, numpy, null",
"url": null
} |
python-3.x, numpy, null
is_gap_start = differential == 1
is_gap_end = differential == -1
gap_starts = 1 + is_gap_start.nonzero()[0]
gap_ends = 1 + is_gap_end.nonzero()[0]
gap_lengths = gap_ends - gap_starts
gap_sum = is_nan.sum() | {
"domain": "codereview.stackexchange",
"id": 44833,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python-3.x, numpy, null",
"url": null
} |
beginner, sql, sql-server, t-sql
Title: Is there a more concise way to write this query in SQL Server?
Question: I'm playing with data from a Time Use survey as a beginner SQL user.
Gender is represented as 1's (Male) and 2's (Female), and the age of each participant is listed. I would like to divide them into age brackets with a total count, and see how many are male/female within each bracket.
What I have is this:
SELECT count(Age) as 'Total',
CASE
WHEN Age<=19 THEN 'Teen'
WHEN Age >=20 and Age<=29 THEN '20s'
WHEN Age>=30 and Age<=39 THEN '30s'
WHEN Age>=40 and Age<=49 THEN '40s'
WHEN Age>=50 and Age<=59 THEN '50s'
WHEN Age>=60 and Age<=69 THEN '60s'
WHEN Age>=70 and Age<=79 THEN '70s'
WHEN Age>=80 and Age<=89 THEN '80s'
END as 'Age',
CASE
WHEN Sex=1 THEN 'Male'
WHEN Sex=2 THEN 'Female'
END as 'Gender'
from TimeUse_Summary
Group by CASE
WHEN Age<=19 THEN 'Teen'
WHEN Age >=20 and Age<=29 THEN '20s'
WHEN Age>=30 and Age<=39 THEN '30s'
WHEN Age>=40 and Age<=49 THEN '40s'
WHEN Age>=50 and Age<=59 THEN '50s'
WHEN Age>=60 and Age<=69 THEN '60s'
WHEN Age>=70 and Age<=79 THEN '70s'
WHEN Age>=80 and Age<=89 THEN '80s'
END, Sex
order by Age
The result is exactly what I'm looking for:
|Total |Age |Gender|
|:------|:-----|------|
|173 |Teen |Male |
|175 |Teen |Female|
|438 |20s |Male |
|468 |20s |Female|
|etc. |
Should I be condensing the CASE statements somehow?
Answer: I agree with you that we could
DRY
up those CASE statements a bit.
The core issue is we would like to report against
a relation that does not exist yet, so we must synthesize it.
Several approaches spring to mind:
CASE expressions, as you described
add an age_bracket column, which would be denormalized
create a temporary reporting table, which again is denormalization
create the same relation as a VIEW report (a named query)
create a CTE relation | {
"domain": "codereview.stackexchange",
"id": 44834,
"lm_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, sql, sql-server, t-sql",
"url": null
} |
beginner, sql, sql-server, t-sql
There is almost no difference between those last two options.
If you look at SELECT statements out in the wild, common table expressions
tend to crop up more often than queries based on CREATE VIEW.
Me, personally?
I tend to prefer a VIEW, mostly because they compose with JOINs very nicely.
And you can conveniently SELECT * from it during debugging,
instantly replace it with an improved edit, and
then go on to mention its name in some giant JOIN
that was already mostly working.
There are CTE examples all over SO, so I will expand on item 4.
DROP VIEW IF EXISTS
time_use_bracket;
CREATE VIEW time_use_bracket AS
SELECT
CASE
WHEN Age<=19 THEN 'Teen'
WHEN Age>=20 and Age<=29 THEN '20s'
WHEN Age>=30 and Age<=39 THEN '30s'
WHEN Age>=40 and Age<=49 THEN '40s'
WHEN Age>=50 and Age<=59 THEN '50s'
WHEN Age>=60 and Age<=69 THEN '60s'
WHEN Age>=70 and Age<=79 THEN '70s'
WHEN Age>=80 and Age<=89 THEN '80s'
END AS age_bracket,
Age AS age,
CASE
WHEN Sex=1 THEN 'Male'
WHEN Sex=2 THEN 'Female'
END AS gender
FROM TimeUse_Summary
;
SELECT
COUNT(*) AS total,
age_bracket,
gender
FROM time_use_bracket
GROUP BY age_bracket, gender
ORDER BY MIN(age)
;
You read from the INT Age column, and synthesize
a new VARCHAR column which, confusingly, is named Age.
Recommend you choose a distinct name for it.
As an orthogonal issue, the CASE statement you supply
is a bit tediously long and repetitive.
Consider exploiting the % modulo operator to
do much of the heavy lifting. | {
"domain": "codereview.stackexchange",
"id": 44834,
"lm_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, sql, sql-server, t-sql",
"url": null
} |
python
Title: Aggregating psycopg2 Errors under a Context Manager
Question: I have various functions which attempt to insert into a PostgreSQL database. In an attempt to remove redundancy for common errors that I was occurring I have created a context manager.
Solution
from contextlib import contextmanager
import psycopg2
class DomainSpecificException(Exception):
...
@contextmanager
def raise_on_insert(table_name: str) -> None:
try:
yield
except psycopg2.errors.InFailedSqlTransaction:
raise DomainSpecificException(
description=(
f'Failed to insert into: {table_name} because InFailedSqlTransaction, this is usually a sign that the upstream connection has spoiled.'
)
)
except psycopg2.errors.NotNullViolation:
raise DomainSpecificException(
description=(
f'Failed to insert into: {table_name} because NotNullViolation for column.'
)
)
except psycopg2.errors.UniqueViolation:
raise DomainSpecificException(
description=(
f'Failed to insert into: {table_name} because UniqueViolation for column'
),
)
except psycopg2.errors.ForeignKeyViolation:
raise DomainSpecificException(
description=(
f'Failed to insert into: {table_name} because ForeignKeyViolation for column'
)
)
Usage
with raise_on_insert(table_name='table_1'):
... # Insert into db
Edit
I have improved the code as follows:
from contextlib import contextmanager
from psycopg2.errors import InFailedSqlTransaction, NotNullViolation, UniqueViolation, ForeignKeyViolation
INSERT_EXCEPTIONS: tuple[Exception, ...] = (
InFailedSqlTransaction,
NotNullViolation,
UniqueViolation,
ForeignKeyViolation
)
class DomainSpecificException(Exception):
pass | {
"domain": "codereview.stackexchange",
"id": 44835,
"lm_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
class DomainSpecificException(Exception):
pass
@contextmanager
def raise_on_insert(table_name: str) -> None:
try:
yield
except INSERT_EXCEPTIONS as err:
raise DomainSpecificException(description=f'Failed to insert into: {table_name} because {type(err).__name__}')
Answer: We have two implementations here, one better than the other. Cool.
Kudos on annotating and passing mypy lint.
And defining app-specific exceptions is very helpful
to callers who want coarse- or fine-grained try / catches.
In the 1st implementation, my chief critique is
DRY,
it just seems a bit chatty. No biggie.
I do appreciate that the InFailedSqlTransaction case is
trying hard to be helpful, to offer a diagnostic error
that helps some poor maintainer figure out the root cause and the fix.
I still have some minor reservations, but they show up in both implementations. | {
"domain": "codereview.stackexchange",
"id": 44835,
"lm_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
The 2nd implementation is very nice.
Short, sweet, clear code.
Here is one concern.
I don't know the right answer here, I will just voice the concern.
Maybe four exceptions is the right number?
But maybe other bad things can go wrong?
I'm just wondering if psycopg2 maybe offers some umbrella exception
that you would also like to throw in there.
Taking a step back, it's not clear from these source documents
exactly what your error handling objectives are.
The code I'm reading mostly seems focused on exposing
details to a handler that's not very far up the call stack
which can maybe recover / ignore / retry when a low-level
bad thing happens, so the high-level business goal still
ends up getting accomplished.
We're missing some review context here.
I would have loved the opportunity to read calling code that has a try,
or unit tests which provoke each of the four exceptions.
Summarize this as: "do we need to exhaustively cover all failure modes?"
Here's another concern.
The description parameter is helpful to humans.
I'm sad that we didn't wrap the original err exception.
That is, we've discarded traceback details like the
function and source line number that triggered the DB error.
Maybe a single exception type makes sense, because
all your callers have similar try / except behavior?
But consider creating four child exception classes,
so callers can catch just "the one thing" they know
how to recover from, if they want to.
Final concern is very minor.
We offer a maintainer a little less diagnostic
advice in the InFailedSqlTransaction case.
Maybe remedy that by tacking on a # comment in that list of four.
This code achieves its design objectives.
I would be willing to delegate or accept maintenance
tasks on this codebase. | {
"domain": "codereview.stackexchange",
"id": 44835,
"lm_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
} |
rust, xml
Title: types.xml XML file merger
Question: A friend of mine and me are running a modded DayZ server.
One of the common tasks when adding mods that include new items is to update the server's types.xml file (example).
My mate did this by hand until now, but asked me to write a program so that he can automate this annoying task. So I wrote the below library and program to merge two such XML files.
The target is that a base XML file is extended by an extension XML file that may override types in the original file:
Cargo.toml
[package]
name = "typesxml"
version = "0.1.3"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
clap = { "version" = "4.2.6", features = ["derive"] }
quick-xml = { version = "0.28.2", features = ["serialize"] }
serde = { version = "1.0.164", features = ["derive"] }
src/lib.rs
use serde::ser::Error;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fmt::{Display, Formatter};
use std::ops::Add;
use std::str::FromStr;
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct Types {
#[serde(rename = "type")]
types: Vec<Type>,
}
impl Add for Types {
type Output = Self;
fn add(self, rhs: Self) -> Self::Output {
let mut map = HashMap::from(&self);
map.extend(HashMap::from(&rhs));
let mut types: Vec<Type> = map.into_values().cloned().collect();
types.sort_by(|lhs, rhs| lhs.name.cmp(&rhs.name));
Self { types }
}
}
impl Display for Types {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
quick_xml::se::to_writer(f, self).map_err(std::fmt::Error::custom)
}
}
impl<'a> From<&'a Types> for HashMap<&'a str, &'a Type> {
fn from(types: &'a Types) -> Self {
types
.types
.iter()
.map(|typ| (typ.name.as_str(), typ))
.collect()
}
}
impl FromStr for Types {
type Err = quick_xml::de::DeError; | {
"domain": "codereview.stackexchange",
"id": 44836,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "rust, xml",
"url": null
} |
rust, xml
impl FromStr for Types {
type Err = quick_xml::de::DeError;
fn from_str(xml: &str) -> Result<Self, Self::Err> {
quick_xml::de::from_str(xml)
}
}
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct Type {
#[serde(rename = "@name")]
name: String,
nominal: u8,
lifetime: u32,
restock: u32,
min: u8,
quantmin: i64,
quantmax: i64,
cost: u32,
flags: Flags,
category: Option<Named>,
usage: Option<Vec<Named>>,
value: Option<Vec<Named>>,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct Flags {
#[serde(rename = "@count_in_cargo")]
count_in_cargo: u64,
#[serde(rename = "@count_in_hoarder")]
count_in_hoarder: u64,
#[serde(rename = "@count_in_map")]
count_in_map: u64,
#[serde(rename = "@count_in_player")]
count_in_player: u64,
#[serde(rename = "@crafted")]
crafted: u64,
#[serde(rename = "@deloot")]
deloot: u64,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct Named {
#[serde(rename = "@name")]
name: String,
}
src/bin/mergetypesxml.rs
use clap::Parser;
use std::fs::{read_to_string, write};
use std::process::exit;
use std::str::FromStr;
use typesxml::Types;
const DESCRIPTION: &str = "Merge types.xml files for DayZ servers.";
#[derive(Parser, Debug)]
#[command(author, version, about, long_about = DESCRIPTION)]
struct Args {
#[arg(index = 1)]
base: String,
#[arg(index = 2)]
extension: String,
#[arg(long, short)]
output: Option<String>,
}
fn main() {
let args = Args::parse();
let merger = types_from_file(&args.base) + types_from_file(&args.extension);
if let Some(file) = args.output {
write(file, merger.to_string()).unwrap_or_else(|error| {
eprintln!("{}", error);
exit(3);
})
} else {
println!("{}", merger);
}
} | {
"domain": "codereview.stackexchange",
"id": 44836,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "rust, xml",
"url": null
} |
rust, xml
fn types_from_file(filename: &str) -> Types {
Types::from_str(&read_to_string(filename).unwrap_or_else(|error| {
eprintln!("{}\n{}", filename, error);
exit(1);
}))
.unwrap_or_else(|error| {
eprintln!("{} in {}", error, filename);
exit(2);
})
}
How may I improve the program?
Answer: Why is this split into a library and a program? The task is pretty simple, so there doesn't seem any reason for the split.
You've been pretty excessive in implementing traits: Add, Display, FromStr, From. They don't really help you, because you aren't using any functions that need those traits and they are each only invoked in one (maybe two) places. The code would be easier to follow if they were just functions you could call. These seems to be specialized bits of your algorithm and not the sort of general functionality that implementing these traits would suggest.
As for your merging algorithm, I'd probably do sort/dedup like so:
let mut types = self.types;
types.extend(rhs.types);
types.sort_by(|lhs, rhs| lhs.name.cmp(&rhs.name));
types.dedup_by(|lhs, rhs| lhs.name.cmp(&rhs.name));
Self { types } | {
"domain": "codereview.stackexchange",
"id": 44836,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "rust, xml",
"url": null
} |
python
Title: A set of message broadcasters and a broadcast manager
Question: I'm designing an application that will broadcast messages to various heterogeneous systems. Slack, JIRA, Database to name a few. Users can pass their various configurations using a yaml file.
While this works fine, it seems verbose and somewhat excessive. Each run only ever needs a single instance of each, so having a manager and all these classes feels like a lot.
Is there a better or more refined way to do this?
I've set it up like so:
from abc import ABC, abstractmethod
class Broadcaster(ABC):
@abstractmethod
def broadcast(self, message, **kwargs):
pass
class SlackBroadcaster(Broadcaster):
def __init__(self, channel: str):
self.channel = channel
def broadcast(self, message):
print(f"This is a slack message: {message}")
class DatabaseBroadcaster(Broadcaster):
def __init__(self, connection: str):
self.connection = connection
def broadcast(self, message):
print(f"This is a database message: {message}")
Since users can have multiple broadcasters, I've added a manager class to handle that:
import enum
import typing as ta
class MessageType(enum.Enum):
""" Possible broadcasters"""
SLACK = "slack"
DATABASE = "database"
class BroadcasterManager:
def __init__(self):
self.broadcaster_types = {
MessageType.DATABASE: DatabaseBroadcaster,
MessageType.SLACK: SlackBroadcaster,
}
self.broadcasters = set()
def create_broadcaster(self, broadcaster_type: MessageType, **kwargs):
assert broadcaster_type in self.broadcaster_types, 'Illegal broadcaster type'
return self.broadcaster_types[broadcaster_type](**kwargs)
def add_broadcaster(self, broadcaster_type, **kwargs):
self.broadcasters.add(
self.create_broadcaster(broadcaster_type, **kwargs)) | {
"domain": "codereview.stackexchange",
"id": 44837,
"lm_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
def broadcast(self, messages: ta.List[str]):
for broadcaster in self.broadcasters:
for message in messages:
broadcaster.broadcast(message)
Answer: There seems to be some review context missing.
I didn't see any callers, didn't see any unit tests.
What you presented seems nice enough.
seems verbose and somewhat excessive.
Yeah, it feels a bit java-esque.
Each run only ever needs a single instance of each, so having a manager and all these classes feels like a lot.
Oohhhh, well there's an interesting detail.
I am taking a "run" to be "bash forked a python interpreter,
which briefly ran the script and soon exited".
Python script startup / imports can be expensive, can cost more than 1 second.
Be sure to avoid importing a Slack module that's never used
by a database broadcast, immediately followed by the child process exiting.
Is there a better or more refined way to do this?
Here's two alternatives that relate to long-lived processes.
You might leave this script running for hours on end, listening for requests, and thereby amortize the one-time startup cost of several imports.
You might make this script only know how to submit broadcast requests to kafka
or similar pub/sub channels,
which slack and database daemons are listening on.
Honestly, I don't see that add_broadcaster()
is bringing a whole lot of value-add to the table.
Consider removing it from the Public API.
class SlackBroadcaster(Broadcaster):
def __init__(self, channel: str):
...
class DatabaseBroadcaster(Broadcaster):
def __init__(self, connection: str):
Let's focus on the channel and connection parameters.
Consider putting a *, bare star before them.
It appears to me that Author's Intent is caller
should specify those parameters with explicit keywords.
Adding a star would clarify that for the caller,
forcing them to use that calling convention.
That way they arrive via **kwargs. | {
"domain": "codereview.stackexchange",
"id": 44837,
"lm_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
assert broadcaster_type in self.broadcaster_types, 'Illegal broadcaster type'
Good, this is helpful.
Suppose the assert triggers.
What's the next thing a maintenance engineer is going to want to know?
Recommend you use this for the 2nd argument:
f'Illegal broadcaster type: {broadcaster_type}' | {
"domain": "codereview.stackexchange",
"id": 44837,
"lm_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, performance, numpy, cython
Title: basic Hartee-Fock program to compute the total energies and some properties of a molecule
Question: I am trying to write a basic Hartee-Fock program that computes the total energies and some properties of a molecule given as an input. The code uses Cython to statically compile the computationally expensive parts, and there is a basic parallelization implemented using mpi4py. However, the code is still very slow for all practical applications.
The code is currently hosted at GitHub, including a sample input for a water molecule.
Any suggestions on how this can be improved, especially execution time, are much appreciated.
Note: I am largely self-taught in Python. So any pointers to where I can learn better coding practices are also appreciated.
driver code
from numpy import array, float32, int32, zeros, pi, exp, dot, savetxt, diag, trace
from numpy.linalg import norm, eigh, solve
from math import ceil, sqrt, log
from scipy.special import factorial2, comb
from sys import argv
from itertools import combinations_with_replacement, combinations
from mpi4py import MPI
from plank.routines.oneelectron import overlapcgtos, kineticcgtos
from plank.routines.twoelectron import nuclearcgtos, ericgtos
from plank.routines.hatreefock import computecorehamiltonian, canonicalorthogonalization, computehamiltonian
from plank.routines.hatreefock import restrictedhatreefock, restrictedhatreefockDIIS, totalenergy
from plank.routines.hatreefock import diisorthogonalization
from yaml import safe_load
with open("periodicTable.yaml") as periodic:
periodictable = safe_load(periodic)
periodicTable = {y: x[y] for x in periodictable for y in x}
def getatom(atomname):
return periodicTable[atomname] | {
"domain": "codereview.stackexchange",
"id": 44838,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, numpy, cython",
"url": null
} |
python, performance, numpy, cython
def getatom(atomname):
return periodicTable[atomname]
def nuclearenergy(atomobjects):
atompairs = list(combinations(atomobjects,2))
nuclearenergy = 0.0
for atompair in atompairs:
center1 = atompair[0].center
charge1 = atompair[0].charge
center2 = atompair[1].center
charge2 = atompair[1].charge
distance = norm(center1-center2)
energy = charge1*charge2/distance
nuclearenergy = nuclearenergy+energy
return nuclearenergy
def overlap(basisobjects):
overlaps = []
for basisobjecttuple in basisobjects:
result = overlapcgtos(basisobjecttuple[0], basisobjecttuple[1])
overlaps.append((result, basisobjecttuple[0].basisindex, basisobjecttuple[1].basisindex))
return overlaps
def kinetic(basisobjects):
kineticintegrals = []
for basisobjecttuple in basisobjects:
result = kineticcgtos(basisobjecttuple[0], basisobjecttuple[1])
kineticintegrals.append((result, basisobjecttuple[0].basisindex, basisobjecttuple[1].basisindex))
return kineticintegrals
def nuclear(basisobjects, atomobjects):
eniintegrals = []
for basisobjecttuple in basisobjects:
result = nuclearcgtos(basisobjecttuple[0], basisobjecttuple[1], atomobjects)
eniintegrals.append((result, basisobjecttuple[0].basisindex, basisobjecttuple[1].basisindex))
return eniintegrals
def electronic(basisobjects):
eriintegrals = []
for basisobjectquartet in basisobjects:
result = ericgtos(basisobjectquartet[0], basisobjectquartet[1], basisobjectquartet[2], basisobjectquartet[3])
eriintegrals.append((result, basisobjectquartet[0].basisindex, basisobjectquartet[1].basisindex, basisobjectquartet[2].basisindex, basisobjectquartet[3].basisindex))
return eriintegrals | {
"domain": "codereview.stackexchange",
"id": 44838,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, numpy, cython",
"url": null
} |
python, performance, numpy, cython
def integralEngine(molecule, basisobjects, dimensions, calctype="overlap"):
results = []
if calctype == "overlap":
rank = comm.Get_rank()
nprocs = comm.Get_size()
shellpairs = list(combinations_with_replacement(basisobjects, 2))
nshellpairs = len(shellpairs)
nshellpair = ceil(nshellpairs/nprocs)
shellpairi = rank*nshellpair
shellpairf = (rank+1)*nshellpair
overlapresults = overlap(shellpairs[shellpairi:shellpairf])
if rank != 0:
comm.send(overlapresults, dest=0)
else:
for result in overlapresults:
results.append(result)
for proc in range(1, nprocs):
overlapresults = comm.recv(source=proc)
for result in overlapresults:
results.append(result)
if rank == 0:
molecule.overlapmat = zeros((dimensions, dimensions))
for data in results:
molecule.overlapmat[data[1], data[2]] = data[0]
molecule.overlapmat[data[2], data[1]] = data[0]
molecule.overlapmat = comm.bcast(molecule.overlapmat, root=0)
if calctype == "kinetic":
rank = comm.Get_rank()
nprocs = comm.Get_size()
shellpairs = list(combinations_with_replacement(basisobjects, 2))
nshellpairs = len(shellpairs)
nshellpair = ceil(nshellpairs/nprocs)
shellpairi = rank*nshellpair
shellpairf = (rank+1)*nshellpair
kineticresults = kinetic(shellpairs[shellpairi:shellpairf]) | {
"domain": "codereview.stackexchange",
"id": 44838,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, numpy, cython",
"url": null
} |
python, performance, numpy, cython
if rank != 0:
comm.send(kineticresults, dest=0)
else:
for result in kineticresults:
results.append(result)
for proc in range(1, nprocs):
kineticresults = comm.recv(source=proc)
for result in kineticresults:
results.append(result)
if rank == 0:
molecule.kineticmat = zeros((dimensions, dimensions))
for data in results:
molecule.kineticmat[data[1], data[2]] = data[0]
molecule.kineticmat[data[2], data[1]] = data[0]
molecule.kineticmat = comm.bcast(molecule.kineticmat, root=0)
if calctype == "eni":
rank = comm.Get_rank()
nprocs = comm.Get_size()
shellpairs = list(combinations_with_replacement(basisobjects, 2))
atomobjects = [x for x in molecule.geometry]
nshellpairs = len(shellpairs)
nshellpair = ceil(nshellpairs/nprocs)
shellpairi = rank*nshellpair
shellpairf = (rank+1)*nshellpair
eniresults = nuclear(shellpairs[shellpairi:shellpairf], atomobjects)
if rank != 0:
comm.send(eniresults, dest=0)
else:
for result in eniresults:
results.append(result)
for proc in range(1, nprocs):
eniresults = comm.recv(source=proc)
for result in eniresults:
results.append(result)
if rank == 0:
molecule.enimat = zeros((dimensions, dimensions))
for data in results:
molecule.enimat[data[1], data[2]] = data[0]
molecule.enimat[data[2], data[1]] = data[0]
molecule.enimat = comm.bcast(molecule.enimat, root=0) | {
"domain": "codereview.stackexchange",
"id": 44838,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, numpy, cython",
"url": null
} |
python, performance, numpy, cython
molecule.enimat = comm.bcast(molecule.enimat, root=0)
if calctype == "eri":
rank = comm.Get_rank()
nprocs = comm.Get_size()
shellquartets = []
for basisobjectA in basisObjects:
for basisobjectB in basisObjects:
for basisobjectC in basisObjects:
for basisobjectD in basisObjects:
index1 = basisobjectA.basisindex
index2 = basisobjectB.basisindex
index3 = basisobjectC.basisindex
index4 = basisobjectD.basisindex
index12 = (index1*(index1+1)//2)+index2
index34 = (index3*(index3+1)//2)+index4
if index12 >= index34:
shellquartets.append((basisobjectA, basisobjectB, basisobjectC, basisobjectD))
nshellquartets = len(shellquartets)
nshellquartet = ceil(nshellquartets/nprocs)
shellpairi = rank*nshellquartet
shellpairf = (rank+1)*nshellquartet
eriresults = electronic(shellquartets[shellpairi:shellpairf])
if rank != 0:
comm.send(eriresults, dest=0)
else:
for result in eriresults:
results.append(result)
for proc in range(1, nprocs):
eriresults = comm.recv(source=proc)
for result in eriresults:
results.append(result) | {
"domain": "codereview.stackexchange",
"id": 44838,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, numpy, cython",
"url": null
} |
python, performance, numpy, cython
if rank == 0:
molecule.erimat = zeros((dimensions, dimensions, dimensions, dimensions))
for result in results:
molecule.erimat[result[1], result[2], result[3], result[4]] = result[0]
molecule.erimat[result[3], result[4], result[1], result[2]] = result[0]
molecule.erimat[result[2], result[1], result[4], result[3]] = result[0]
molecule.erimat[result[4], result[3], result[2], result[1]] = result[0]
molecule.erimat[result[2], result[1], result[3], result[4]] = result[0]
molecule.erimat[result[4], result[3], result[1], result[2]] = result[0]
molecule.erimat[result[1], result[2], result[4], result[3]] = result[0]
molecule.erimat[result[3], result[4], result[2], result[1]] = result[0]
molecule.erimat = comm.bcast(molecule.erimat, root=0) | {
"domain": "codereview.stackexchange",
"id": 44838,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, numpy, cython",
"url": null
} |
python, performance, numpy, cython
molecule.erimat = comm.bcast(molecule.erimat, root=0)
def scfEngine(molecule, dimensions):
density = zeros((dimensions, dimensions))
orthomat = canonicalorthogonalization(molecule.overlapmat)
diisortho = diisorthogonalization(molecule.overlapmat)
core = computecorehamiltonian(molecule.kineticmat, molecule.enimat)
for iteration in range(1, molecule.maxiterations):
if iteration <= 2 or molecule.DIIS == False:
orthofock, fock, hamiltonian, orbitals, coeffs, density, rmsdensity, maxdensity = restrictedhatreefock(molecule.nelectrons, core, diisortho, density, molecule.erimat)
molenergy = totalenergy(molecule.nuclearenergy, fock, density, core)
print("{:10.0f}{:20.5f}{:20.5f}{:20.5f}".format(iteration, molenergy, log(rmsdensity), log(maxdensity)))
if iteration > 2 and molecule.DIIS == True:
orthofock, fock, hamiltonian, orbitals, coeffs, density, rmsdensity, maxdensity = restrictedhatreefockDIIS(molecule, molecule.nelectrons, core, diisortho, density, molecule.erimat)
molenergy = totalenergy(molecule.nuclearenergy, fock, density, core)
print("{:10.0f}{:20.5f}{:20.5f}{:20.5f}".format(iteration, molenergy, log(rmsdensity), log(maxdensity)))
if log(rmsdensity) <= -20.0 and log(maxdensity) <= -20.0:
molecule.scfstatus = True
molecule.density = density
molecule.fock = fock
molecule.orbitals = orbitals
molecule.coeffs = coeffs
print("SCF CONVERGENCE ACHIEVED IN {:10.0f} ITERATIONS".format(iteration))
break
class Basis(object):
""" docstring for Basis | {
"domain": "codereview.stackexchange",
"id": 44838,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, numpy, cython",
"url": null
} |
python, performance, numpy, cython
class Basis(object):
""" docstring for Basis
Basis class constructs one basis object of type (s,p,d or f) depending on the basis set
passed to the code. The generation of basis object happens during the construction of the
atom object in the class Atom, with the list of basis objects tied to the atom object.
"""
def __init__(self, shell, exponents, coefficients, center):
super(Basis, self).__init__()
self.shell = array(shell)
self.exponents = array(exponents)
self.coefficients = array(coefficients)
self.normcoeffs = zeros(self.coefficients.size)
self.center = array(center)
self.basisindex = 0
self.normalizepGTO()
def normalizepGTO(self):
ll, mm, nn = self.shell
totalangmomentum = sum(self.shell)
prefactorpGTO = pow(2, 2*totalangmomentum)*pow(2, 1.5)/factorial2(2*ll-1)/factorial2(2*mm-1)/factorial2(2*nn-1)/pow(pi, 1.5)
for index, exponent in enumerate(self.exponents):
self.normcoeffs[index] = sqrt(pow(exponent, totalangmomentum)*pow(exponent, 1.5)*prefactorpGTO)
prefactorcGTO = pow(pi, 1.5)*factorial2(2*ll-1)*factorial2(2*mm-1)*factorial2(2*nn-1)/pow(2.0, totalangmomentum)
normalfactor = 0.0
for index1, coefficient1 in enumerate(self.coefficients):
for index2, coefficient2 in enumerate(self.coefficients):
t_normalfactor = (self.normcoeffs[index1]*self.normcoeffs[index2]*self.coefficients[index1]*self.coefficients[index2])/(pow(self.exponents[index1]+self.exponents[index2], totalangmomentum+1.5))
normalfactor = normalfactor + t_normalfactor
normalfactor = prefactorcGTO*normalfactor
normalfactor = pow(normalfactor, -0.5) | {
"domain": "codereview.stackexchange",
"id": 44838,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, numpy, cython",
"url": null
} |
python, performance, numpy, cython
for index, coefficient in enumerate(self.coefficients):
self.coefficients[index] = self.coefficients[index]*normalfactor
class Atom(object):
"""docstring for Atom."""
def __init__(self, atomname, center, charge, basisset='sto-3g'):
super(Atom, self).__init__()
self.atomname = atomname
self.center = array(center)*1.8897259886
self.basisset = basisset
self.shells = []
self.charge = charge
self.readBasis()
def readBasis(self):
self.basisfile = "./basis/"+self.atomname+"."+self.basisset+".gbs"
with open(self.basisfile) as target:
basisdata = target.readlines()
headerline = basisdata[0].split()[0]
_atomname = headerline
assert (_atomname == self.atomname), "Wrong basis set"
for lnumber, line in enumerate(basisdata[1:]):
if "S" in line and "P" not in line:
nprims = int(line.split()[1])
pgtodata = [x.replace('D', 'E').split() for x in basisdata[lnumber+2:lnumber+2+nprims]]
exponents = [float(x[0]) for x in pgtodata]
coefficients = [float(x[1]) for x in pgtodata]
shell00 = [0, 0, 0]
self.shells.append(Basis(shell00, exponents, coefficients, self.center)) | {
"domain": "codereview.stackexchange",
"id": 44838,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, numpy, cython",
"url": null
} |
python, performance, numpy, cython
if "P" in line:
nprims = int(line.split()[1])
pgtodata = [x.replace('D', 'E').split() for x in basisdata[lnumber+2:lnumber+2+nprims]]
coefficient1 = [float(x[1]) for x in pgtodata]
coefficient2 = [float(x[2]) for x in pgtodata]
exponents = [float(x[0]) for x in pgtodata]
shell00 = [0, 0, 0]
self.shells.append(Basis(shell00, exponents, coefficient1, self.center))
shell11 = [1, 0, 0]
self.shells.append(Basis(shell11, exponents, coefficient2, self.center))
shell12 = [0, 1, 0]
self.shells.append(Basis(shell12, exponents, coefficient2, self.center))
shell13 = [0, 0, 1]
self.shells.append(Basis(shell13, exponents, coefficient2, self.center)) | {
"domain": "codereview.stackexchange",
"id": 44838,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, numpy, cython",
"url": null
} |
python, performance, numpy, cython
if "D" in line and "+" not in line:
nprims = int(line.split()[1])
pgtodata = [x.replace('D', 'E').split() for x in basisdata[lnumber+2:lnumber+2+nprims]]
exponents = [float(x[0]) for x in pgtodata]
coefficients = [float(x[1]) for x in pgtodata]
shell20 = [2, 0, 0]
self.shells.append(Basis(shell20, exponents, coefficients, self.center))
shell21 = [1, 1, 0]
self.shells.append(Basis(shell21, exponents, coefficients, self.center))
shell22 = [1, 0, 1]
self.shells.append(Basis(shell22, exponents, coefficients, self.center))
shell23 = [0, 2, 0]
self.shells.append(Basis(shell23, exponents, coefficients, self.center))
shell24 = [0, 1, 1]
self.shells.append(Basis(shell24, exponents, coefficients, self.center))
shell25 = [0, 0, 2]
self.shells.append(Basis(shell25, exponents, coefficients, self.center))
class Geometry(object):
"""docstring for Geometry.""" | {
"domain": "codereview.stackexchange",
"id": 44838,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, numpy, cython",
"url": null
} |
python, performance, numpy, cython
class Geometry(object):
"""docstring for Geometry."""
def __init__(self, inputfile):
super(Geometry, self).__init__()
self.inputfile = inputfile
self.charge = 0
self.natoms = 0
self.nelectrons = 0
self.calctype = 'energy'
self.basisset = 'sto-3g'
self.geometry = []
self.atomobjects = []
self.density = []
self.scfstatus = False
self.maxiterations = 100
self.readgeometry()
self.overlapmat = []
self.kineticmat = []
self.enimat = []
self.erimat = []
self.nuclearenergy = 0.0
self.totalenergy = 0.0
self.diisfock = []
self.diiserror = []
self.DIIS | {
"domain": "codereview.stackexchange",
"id": 44838,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, numpy, cython",
"url": null
} |
python, performance, numpy, cython
def readgeometry(self):
with open(self.inputfile) as file:
inputdata = file.readlines()
calcbasis = inputdata[0].split()
self.calctype = calcbasis[0]
self.basisset = calcbasis[1]
chargemul = inputdata[1].split()
self.charge = int(chargemul[0])
multiplicity = int(chargemul[1])
try:
assert multiplicity == 1, "[ERROR] : Only closed-shell singlets are currently supported."
except AssertionError as Message:
exit(Message)
natoms = int(inputdata[2].split()[0])
coorddata = [x for x in inputdata[3:3+natoms]]
for atom in coorddata:
atomdata = atom.split()
atomname = atomdata[0]
charge = getatom(atomname)
coords = [float(x) for x in atomdata[1:]]
self.nelectrons += charge
self.geometry.append(Atom(atomname, coords, charge, self.basisset))
iterdiisline = inputdata[-1].split()
if iterdiisline != []:
self.maxiterations = int(iterdiisline[0])
self.DIIS = True if (iterdiisline[1] == 'T') else False
inputfilename = argv[1]
logfilename = inputfilename[:-4]+".log"
molecule = Geometry(inputfilename)
comm = MPI.COMM_WORLD
atomObjects = [x for x in molecule.geometry]
basisObjects = [y for x in atomObjects for y in x.shells]
nbasisObjects = len(basisObjects)
for counter, x in enumerate(basisObjects):
x.basisindex = counter | {
"domain": "codereview.stackexchange",
"id": 44838,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, numpy, cython",
"url": null
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.