text
stringlengths
1
2.12k
source
dict
c++, performance, reinventing-the-wheel, cryptography, c++20 #include <string> #include <array> #include <vector> namespace pstl::cryptography::hashing { class md5 { public: static std::string digest(std::string str); protected: md5() = delete; ~md5() = delete; private: constexpr static std::array<uint32_t, 64> make_k_array(); static std::vector<char> padder(std::string str); static void init(); private: static const std::array<uint32_t, 64> k_array; static const std::array<uint32_t, 64> s_array; inline static std::array<uint64_t, 16> m_array; inline static uint32_t a0 = 0x67452301; inline static uint32_t b0 = 0xefcdab89; inline static uint32_t c0 = 0x98badcfe; inline static uint32_t d0 = 0x10325476; }; } pstl_hashes.cpp #include <iostream> #include <array> #include <string> #include <cmath> #include <vector> #include <format> #include "pstl_cryptography.h" const std::array<uint32_t, 64> pstl::cryptography::hashing::md5::s_array = { 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21 }; constexpr std::array<uint32_t, 64> pstl::cryptography::hashing::md5::make_k_array() { std::array<uint32_t, 64> output; for (int i = 0; i < output.max_size(); i++) output[i] = std::floor(0x100000000 * std::abs(std::sin(i + 1))); return output; } const std::array<uint32_t, 64> pstl::cryptography::hashing::md5::k_array = pstl::cryptography::hashing::md5::make_k_array();
{ "domain": "codereview.stackexchange", "id": 43887, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, performance, reinventing-the-wheel, cryptography, c++20", "url": null }
c++, performance, reinventing-the-wheel, cryptography, c++20 std::vector<char> pstl::cryptography::hashing::md5::padder(std::string str) { std::vector<char> padded(str.begin(), str.end()); union length_pad { uint64_t whole; uint8_t parts[8]; } length; length.whole = padded.size() * 8; padded.emplace_back(0x80); int extra_over_chunks = (padded.size() % 64); int zero_pad = extra_over_chunks < 56 ? 56 - extra_over_chunks : 56 - extra_over_chunks + 64; for (int i = 0; i < zero_pad; i++) padded.emplace_back(0x00); for (auto& length_byte : length.parts) padded.emplace_back(length_byte); return padded; } void pstl::cryptography::hashing::md5::init() { a0 = 0x67452301; b0 = 0xefcdab89; c0 = 0x98badcfe; d0 = 0x10325476; } // Based on RFC 1321 // https://www.ietf.org/rfc/rfc1321.txt // 1992 std::string pstl::cryptography::hashing::md5::digest(std::string str) { init(); std::vector<char> padded_message = padder(str); uint32_t num_chunks = padded_message.size() / 64; for (int i = 0; i < num_chunks; i++) { uint32_t A = a0; uint32_t B = b0; uint32_t C = c0; uint32_t D = d0; union chunk { char in_chars[64]; uint32_t in_ints[16]; } current_chunk; for (int k = 0; k < 64; k++) current_chunk.in_chars[k] = padded_message[k + i * 64]; for (int k = 0; k < 16; k++) m_array[k] = current_chunk.in_ints[k];
{ "domain": "codereview.stackexchange", "id": 43887, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, performance, reinventing-the-wheel, cryptography, c++20", "url": null }
c++, performance, reinventing-the-wheel, cryptography, c++20 for (int j = 0; j < 64; j++) { uint32_t F, g; if (j < 16) { F = (B & C) | ((~B) & D); g = j; } else if (j < 32) { F = (B & D) | (C & (~D)); g = (5 * j + 1) % 16; } else if (j < 48) { F = B ^ C ^ D; g = (3 * j + 5) % 16; } else if (j < 64) { F = C ^ (B | (~D)); g = (7 * j) % 16; } F = F + A + m_array[g] + k_array[j]; A = D; D = C; C = B; B = B + std::rotl(F, s_array[j]); } a0 += A; b0 += B; c0 += C; d0 += D; } std::string output; for (auto var : { &a0, &b0, &c0, &d0 }) { *var = (((*var) >> 24) | (((*var) & 0x00FF0000) >> 8) | (((*var) & 0x0000FF00) << 8) | ((*var) << 24)); output += std::format("{:08x}", *var); } return output; } main.cpp #include <iostream> #include "pstl_cryptography.h" int main() { std::cout << pstl::cryptography::hashing::md5::digest("") << std::endl; std::cout << pstl::cryptography::hashing::md5::digest("a") << std::endl; std::cout << pstl::cryptography::hashing::md5::digest("message digest") << std::endl; std::cout << pstl::cryptography::hashing::md5::digest("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789") << std::endl; } Answer: First Look: In these two functions: static std::string digest(std::string str); static std::vector<char> padder(std::string str); You are passing the str by value. So you are making a copy of the string. Which of course uses memory management which is slow. Pass by const reference. static std::string digest(std::string const& str); static std::vector<char> padder(std::string const& str);
{ "domain": "codereview.stackexchange", "id": 43887, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, performance, reinventing-the-wheel, cryptography, c++20", "url": null }
c++, performance, reinventing-the-wheel, cryptography, c++20 This will prevent a copy and prevent you modifying the original. You make an additional copy of string here. std::vector<char> padded(str.begin(), str.end()); That seems like an inefficiency to me. The whole reason for padder() function seems redundant. If you have gone past the end of the data you know then you calculate the padding value in place. Couple of other places where there seems to be redundant copying. for (int k = 0; k < 64; k++) current_chunk.in_chars[k] = padded_message[k + i * 64]; for (int k = 0; k < 16; k++) m_array[k] = current_chunk.in_ints[k]; Second Loop You are deleting the constructor and destructor! protected: md5() = delete; ~md5() = delete; All the public functions are static (as are the members). So looks like you have a bunch of free functions and some shared state between them. If that's what you want (free functions with no state (i.e. not object)) just use a namespace namespace md5 { std::string digest(std::string str); namespace implementation_details { // Put other stuff in here. } } But after reading this. You do store some state. Which makes your code unuseful unless you totally serialize all usage of your MD5 code (otherwise they will interact). So I would keep the class design, but distinguish shared state (the const stuff) and the state that belongs to the the hash of the current bit of string. class md5 { public: std::string digest(std::string str); private: // Private Static State. // Used by all instances. static std::array<uint32_t, 64> make_k_array(); static const std::array<uint32_t, 64> k_array; static const std::array<uint32_t, 64> s_array;
{ "domain": "codereview.stackexchange", "id": 43887, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, performance, reinventing-the-wheel, cryptography, c++20", "url": null }
c++, performance, reinventing-the-wheel, cryptography, c++20 // State used by each instance. // Don't need an init() as you initialize the object here. std::array<uint64_t, 16> m_array; uint32_t a0 = 0x67452301; uint32_t b0 = 0xefcdab89; uint32_t c0 = 0x98badcfe; uint32_t d0 = 0x10325476; static std::vector<char> padder(std::string str); }; Third Look: Minor grumbles: Actually trying to compile it. Should have mentioned you need C++20 to compile it. You have a missing header: #include <bit> I get a compiler error for this: constexpr static std::array<uint32_t, 64> make_k_array(); It's complaining this is not a constexpr function. So I just deleted the constexpr part. Not that worried about it (probably my old compiler). Bad Design: The digest should not return a string: static std::string digest(std::string str); The return value is simply a 128 bit integer. OK you can put that 128 bit integer into 16 byte string for ease of use. But you don't; you encode that 128 bit into a string of hash digits. That seems like a waste of time. It's a 128 bit integer treat it as such. Yes, convert it to hex for display to a human but that conversion to hex digits is not part of the algorithm. using Hash = std::array<unsigned char, 16>; Hash digest(std::string const& str); std::ostream& operator<<(std::ostream& str, Hash const& data) { for (auto const& v: data) { str << std::format("{:08x}", v); } return str; }
{ "domain": "codereview.stackexchange", "id": 43887, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, performance, reinventing-the-wheel, cryptography, c++20", "url": null }
python, performance, python-3.x, algorithm, binary-search Title: Increase efficiency of stick cutting algorithm Question: I have this typical code interview type problem. Suppose you have a stick of length n. You make X cuts in the stick at places x1, x2, x3 and so on. For every cut in X cuts you need to print the length of current longest piece. Here is my current code: def get_index_binary_search(list_thing,index, j): start = 0 end = j while start<= end: mid = (start+end)//2 if list_thing[mid]==index: return mid elif list_thing[mid]<index: start = mid + 1 else: end = mid - 1 return end + 1 n, m = [int(x) for x in str(input()).split()] sticks = [0,n] # the whole stick without cuts cuts = [int(x) for x in str(input()).split()] #biggestrange = [0,n] minimum_range = 0 maximum_range = n maximum = n for j in range(m): cut = cuts[j] i = get_index_binary_search(sticks, cut, j) sticks.insert(i,cut) if minimum_range<cut and cut<maximum_range: # we need to calculate the biggest range again maximum = 0 for counter in range(len(sticks)-1): value = sticks[counter+1]-sticks[counter] #print(value) if value > maximum: maximum = value minimum_range = sticks[counter] maximum_range = sticks[counter+1] print(maximum) The code works but I do not know of a more efficient way to solve this problem and my code doesn't run in the required time frame. How do I improve it? Thanks in advance for the help!
{ "domain": "codereview.stackexchange", "id": 43888, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, python-3.x, algorithm, binary-search", "url": null }
python, performance, python-3.x, algorithm, binary-search Answer: Two reviewers advised how to avoid establishing the length of current longest piece from scratch, as that promises worst case run time at least quadratic in the number m of cuts. In greybeard's proposal, there is hand-waving about how to establish the stick cut - using bisect.insort() results in O(m²). janos' proposal skimps over BST implementation (including remove, predecessor&successor, insert optional. And remove the piece from the heap - I think heap use uncalled for.) - Lets try to mock up something somewhat plausible in a job interview context. Assume cuts are unique (and between 0 and n, exclusive). Let print the length of current longest piece mean after the cut. Processing from the final configuration looks promising - If the customer (in professional coding, there is one - here: interviewer) wanted to specify cuts one by one, the task specification would have to be refined. One insight is that deleting from a "doubly linked" list is cheap given the node: After ascendantly ordering the cuts, make a node for each linked with its neighbours as lengths and keep a dict sticks mapping cut to node. Establish the greatest length longest. For every cut in reverse input order append longest to a list after remove cut from lengths This increases the length of the stick starting at the predecessor end to cut's end: update longest where necessary
{ "domain": "codereview.stackexchange", "id": 43888, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, python-3.x, algorithm, binary-search", "url": null }
python, performance, python-3.x, algorithm, binary-search print reversed after For the hell of doubly linked list library support, object disorientation and naked code: def longest_after(length, cuts): """ Starting with a stick of length length, return an iterable of the lengths of the longest stick after each cut in cuts. """ ordered = [0] + sorted(cuts) + [length] # to avoid special casing [i+-1] sticks = {key: index for index, key in enumerate(ordered)} if ordered[1] < 0 or length < ordered[-2] or len(sticks) < len(ordered): pass # ToDo: handle error pred = list(range(-1, len(cuts) + 1)) # predecessor? succ = [i + 2 for i in pred] # list(range(1, len(cuts) + 3)) # from 3.10: itertools.pairwise(ordered) lengths = [-1] + [end - start for end, start in zip(ordered[1:], ordered)] longest = max(lengths) after = [longest] # the first cut would append longest = length before 1st cut: unwanted for cut in reversed(cuts[1:]): index = sticks[cut] p = pred[index] # pred_index? s = succ[index] merged = lengths[s] + lengths[index] lengths[s] = merged if longest < merged: longest = merged succ[p] = s pred[s] = p after.append(longest) return reversed(after)
{ "domain": "codereview.stackexchange", "id": 43888, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, python-3.x, algorithm, binary-search", "url": null }
python, performance, python-3.x, numpy, memory-optimization Title: Create a forecast matrix from time series samples Question: I would like to create a matrix of delay from a time series. For example, given y = [y_0, y_1, y_2, ..., y_N] and W = 5 I need to create this matrix: | 0 | 0 | 0 | 0 | 0 | | 0 | 0 | 0 | 0 | y_0 | | 0 | 0 | 0 | y_0 | y_1 | | ... | | | | | | y_{N-4} | y_{N-3} | y_{N-2} | y_{N-1} | y_N | I know that function timeseries_dataset_from_array from TensorFlow does approximatively the same thing when well configured, but I would like to avoid using TensorFlow. This is my current function to perform this task: def get_warm_up_matrix(_data: ndarray, W: int) -> ndarray: """ Return a warm-up matrix If _data = [y_1, y_2, ..., y_N] The output matrix W will be W = +---------+-----+---------+---------+-----+ | 0 | ... | 0 | 0 | 0 | | 0 | ... | 0 | 0 | y_1 | | 0 | ... | 0 | y_1 | y_2 | | ... | ... | ... | ... | ... | | y_1 | ... | y_{W-2} | y_{W-1} | y_W | | ... | ... | ... | ... | ... | | y_{N-W} | ... | y_{N-2} | y_{N-1} | y_N | +---------+-----+---------+---------+-----+ :param _data: :param W: :return: """ N = len(_data) warm_up = np.zeros((N, W), dtype=_data.dtype) raw_data_with_zeros = np.concatenate((np.zeros(W, dtype=_data.dtype), _data), dtype=_data.dtype) for k in range(W, N + W): warm_up[k - W, :] = raw_data_with_zeros[k - W:k] return warm_up It works well, but it's quite slow since the concatenate operation and the for loop take time to be performed. It also takes a lot of memory since the data have to be duplicated in memory before filling the matrix. Can I make it faster and more memory-friendly?
{ "domain": "codereview.stackexchange", "id": 43889, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, python-3.x, numpy, memory-optimization", "url": null }
python, performance, python-3.x, numpy, memory-optimization Answer: Yes, Numpy already has a built-in sliding window method (though it's perhaps a little obscure). This should indeed be memory-friendly, occupying about (W + N) and not W(W + N) due to it being a view. Also, about your own code: don't underscore _data and don't capitalise w. Delete the boilerplate section of your docstring, and prefix ndarray with np in your typehints. Suggested import numpy as np def get_warm_up_matrix(data: np.ndarray, w: int) -> np.ndarray: """ Return a warm-up matrix If data = [y_1, y_2, ..., y_N] The output matrix W will be W = +---------+-----+---------+---------+-----+ | 0 | ... | 0 | 0 | 0 | | 0 | ... | 0 | 0 | y_1 | | 0 | ... | 0 | y_1 | y_2 | | ... | ... | ... | ... | ... | | y_1 | ... | y_{W-2} | y_{W-1} | y_W | | ... | ... | ... | ... | ... | | y_{N-W} | ... | y_{N-2} | y_{N-1} | y_N | +---------+-----+---------+---------+-----+ """ padded = np.zeros(shape=len(data) + w, dtype=data.dtype) padded[w:] = data return np.lib.stride_tricks.sliding_window_view(x=padded, window_shape=w) print(get_warm_up_matrix(data=np.arange(1, 11), w=4)) Output [[ 0 0 0 0] [ 0 0 0 1] [ 0 0 1 2] [ 0 1 2 3] [ 1 2 3 4] [ 2 3 4 5] [ 3 4 5 6] [ 4 5 6 7] [ 5 6 7 8] [ 6 7 8 9] [ 7 8 9 10]]
{ "domain": "codereview.stackexchange", "id": 43889, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, python-3.x, numpy, memory-optimization", "url": null }
algorithm, php, sorting Title: Sort array of associative arrays by the key of the subarrays Question: I am trying to sort an array of associative arrays in reverse order by the key of the subarrays. I solved it with a bubble sort algorithm which worked just fine in my test. I was wondering if there is a better way, maybe a standard PHP method which I am not aware of. $list = array( array(0 => "F"), array(1 => "E"), array(60 => "B"), array(20 => "C"), array(14 => "D"), array(100 => "A"), ); $tmp = []; for($x = 0; $x < sizeof($list); $x++) { for($i = 0; $i < sizeof($list); $i++) { if (!isset($list[$i + 1])) { continue; } $nextVal = key($list[$i + 1]); $currentVal = key($list[$i]); if ($nextVal > $currentVal) { $tmp = $list[$i]; $list[$i] = $list[$i + 1]; $list[$i + 1] = $tmp; } } } Test it on onlinephp.io Output: AFTER: array(6) { [0]=> array(1) { [100]=> string(1) "A" } [1]=> array(1) { [60]=> string(1) "B" } [2]=> array(1) { [20]=> string(1) "C" } [3]=> array(1) { [14]=> string(1) "D" } [4]=> array(1) { [1]=> string(1) "E" } [5]=> array(1) { [0]=> string(1) "F" } } Answer: Short of simplifying your input array structure, using functional sorting will be most direct with array_multisort() which is fed an array of keys to sort in a descending fashion. Code: (Demo) array_multisort(array_map('key', $list), SORT_DESC, $list); var_export($list);
{ "domain": "codereview.stackexchange", "id": 43890, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "algorithm, php, sorting", "url": null }
algorithm, php, sorting This is a good idea because key() will only be called n times, which will be less than if key() was called twice for every iteration inside of usort() (which is n log n). Furthermore, it is much easier to read because it explicitly mentions SORT_DESC, but then you (the developer) need to understand that only the last argument inside the sorting function is actually modified. Comparatively, usort() is less expressive/intuitive to the novice developer because you must be aware of the 3-way comparison operator's behavior as well as why $a and $b are written where they are. If your application's business logic guarantees that the keys within each row will be unique, then you can safely flatten your array and just call krsort() as mentioned elsewhere on this page.
{ "domain": "codereview.stackexchange", "id": 43890, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "algorithm, php, sorting", "url": null }
python, statistics, simulation Title: Estimate an average duration of every game state in a football match given implied goals for home and away teams Question: What my program does I'm trying to estimate for how many minutes in average a football(soccer) match will be in different game states depending on implied goals of both teams. Problem domain For our purposes there are three possible game states: Home team is ahead, e.g. 1-0 Both teams are drawing, e.g. 2-2 Away team is ahead, e.g. 0-2 And implied goals means how many goals teams are expected to score in average, for example 1.80 for home team and 1.45 for away team. For simplicity we may assume that: Teams' scoring rate doesn't depend on the current scoreline The probability to score is equal regardless of the part of the game If one team scored in a given minute, it doesn't affect the probability of the other team to score in the same minute A typical football match consists of 90 minutes of regular time and usually 1 minute of injury time in the first half and 4 minutes in the second half, which gives us 95 minutes in total. Chosen approach I use the following algorithm to accomplish this task: For each team calculate probability to score in a given minute. For each team make a bitmap with length of match duration in minutes (95 in our example) where 1 indicates that a team scored in a given minute of the match and 0 indicates it didn't score. Calculate cumulative score of a team by a particular minute of the match. By comparing cumulative scores of both teams, count the duration of each game state. Repeat this for the required number of trials. Calculate average duration of each game state.
{ "domain": "codereview.stackexchange", "id": 43891, "lm_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, statistics, simulation", "url": null }
python, statistics, simulation My questions I'm interested in what are the alternatives to my solution both conceptually and implementation wise. Even though I'm aware that my program can be speed up by orders of magnitude via incorporating numpy, it is not that relevant in this particular case since it takes only a few seconds to run and it isn't supposed to be invoked a large number of times in a quick succession. Code from dataclasses import dataclass import random from statistics import mean from numpy import cumsum MATCH_LENGTH = 95 TRIALS = 100_000 @dataclass class MatchGameState: """ Represents for how many minutes of a particular game: - home team was ahead - teams were drawing - away team was ahead """ home_ahead: int draw: int away_ahead: int MatchGameStates = list[MatchGameState] def mean_game_state(home_implied_goals: float, away_implied_goals: float, match_length: int=MATCH_LENGTH, trials: int=TRIALS) -> tuple[float, float, float]: """ Given match length in minutes and implied goals for home and away teams, calculates for how many minutes per match in average home team will be ahead, there will be a draw and away team will be ahead. """ random.seed() sims = [single_match_game_state(home_implied_goals, away_implied_goals, match_length) for _ in range(trials)] home_ahead_mean = round(mean(s.home_ahead for s in sims), 2) draw_mean = round(mean(s.draw for s in sims), 2) away_ahead_mean = round(mean(s.away_ahead for s in sims), 2) return home_ahead_mean, draw_mean, away_ahead_mean
{ "domain": "codereview.stackexchange", "id": 43891, "lm_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, statistics, simulation", "url": null }
python, statistics, simulation def single_match_game_state(home_implied_goals: float, away_implied_goals: float, match_length: int=95) -> MatchGameState: """ Given match length in minutes and implied goals for home and away teams, simulates teams scoring minute by minute for a particular game. Returns MatchGameState for the game. """ # Probability to score in a given minute home_goals_per_min = home_implied_goals / match_length away_goals_per_min = away_implied_goals / match_length # For every minute in a game, 1 if a team scored in that minute, 0 otherwise home_outcomes = [random.random() for _ in range(match_length)] away_outcomes = [random.random() for _ in range(match_length)] home_goals_by_minute = [int(home_outcome < home_goals_per_min) for home_outcome in home_outcomes] away_goals_by_minute = [int(away_outcome < away_goals_per_min) for away_outcome in away_outcomes] # How many goals a team scored by a particular minute of the game home_cumulative_goals = cumsum(home_goals_by_minute) away_cumulative_goals = cumsum(away_goals_by_minute) home_ahead, draw, away_ahead = 0, 0, 0 for home_cumulative_score, away_cumulative_score in zip(home_cumulative_goals, away_cumulative_goals): if home_cumulative_score > away_cumulative_score: home_ahead += 1 elif home_cumulative_score == away_cumulative_score: draw += 1 else: away_ahead += 1 assert home_ahead + draw + away_ahead == match_length return MatchGameState(home_ahead, draw, away_ahead) if __name__ == '__main__': print(mean_game_state(2.15, 1.20))
{ "domain": "codereview.stackexchange", "id": 43891, "lm_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, statistics, simulation", "url": null }
python, statistics, simulation if __name__ == '__main__': print(mean_game_state(2.15, 1.20)) Answer: It's clear that you've been working at generic Python quality, and from that perspective this code is half-decent. Where it falls over is Numpy use. In one sense, well-written Numpy code doesn't look very much like what we imagine to be Pythonic code. Your dataclass must go away, and your "single_" method must go away. The operations from "single_" must be pulled out to "mean_" and vectorised over the number of trials. References to the built-in math and random libraries will go away. With this done, you can run the code in much less time, and/or run many more trials. Even if you were to skip vectorisation (which you shouldn't), the other minor things you could change: Insufficient inter-function spacing for PEP8; you need two blank lines. MatchGameStates is unused so delete it. int=MATCH_LENGTH is also non-PEP8-compliant and needs spacing. random.seed() is not the responsibility of mean_game_state; it's a top-level program concern whether the results should be repeatable or not. Similarly, round is a display concern and shouldn't be baked into your business logic function. MatchGameState, rather than a dataclass, is simpler as a NamedTuple. Even without Numpy, the home_ahead, draw and away_ahead variables can be calculated with sum() on generators. Suggested import numpy as np from numpy.random import default_rng MATCH_LENGTH = 95 TRIALS = 100_000 rand = default_rng() def mean_game_state( home_implied_goals: float, away_implied_goals: float, match_length_minutes: int = MATCH_LENGTH, trials: int = TRIALS, ) -> tuple[float, float, float]: """ Given match length in minutes and implied goals for home and away teams, calculates for how many minutes per match in average home team will be ahead, there will be a draw and away team will be ahead. """ implied_goals = np.array((home_implied_goals, away_implied_goals))
{ "domain": "codereview.stackexchange", "id": 43891, "lm_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, statistics, simulation", "url": null }
python, statistics, simulation implied_goals = np.array((home_implied_goals, away_implied_goals)) # Probability to score in a given minute goals_per_min = implied_goals / match_length_minutes # For every minute in a game, 1 if a team scored in that minute, 0 otherwise outcomes = rand.uniform(size=(trials, match_length_minutes, 2)) goals_by_minute = outcomes < goals_per_min # How many goals a team scored by a particular minute of the game home_cumulative_goals, away_cumulative_goals = goals_by_minute.cumsum(axis=1).T diff = home_cumulative_goals - away_cumulative_goals home_ahead = np.count_nonzero(diff > 0, axis=0) away_ahead = np.count_nonzero(diff < 0, axis=0) draw = np.count_nonzero(diff == 0, axis=0) return home_ahead.mean(), draw.mean(), away_ahead.mean() if __name__ == '__main__': print(mean_game_state(home_implied_goals=2.15, away_implied_goals=1.20))
{ "domain": "codereview.stackexchange", "id": 43891, "lm_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, statistics, simulation", "url": null }
javascript, jquery, array, asynchronous, ajax Title: SetTimeout to populate Javascript Object while a function looped AJAX requests to get data Question: I wrote some code that will get the name and data of a node or multiple of nodes and put them in an object (seriesData) so I can use said object for a chart (renderChart). I used setTimeout() so seriesData can populate before rendering the chart. Everything works as intended. Is there a better pattern to handle this? I read up on Promises but am not sure how to implement in a looped AJAX within getData() or is even needed. const seriesData = { name: [], data: [], }; function getNodeList() { let nodeList = []; $.ajax({ type: 'GET', url: '/masternode', success: function (result) { let nodes = $(result).find('ID'); let addresses = $(result).find('Address'); for (let i = 0; i < nodes.length; i++) { let node = $(nodes[i]).text(); let address = $(addresses[i]).text(); nodeList.push({ node: node, address: address }); } getData(nodeList, seriesData); setTimeout(renderChart, 50); }, }); } function getData(nodeList, seriesData) { for (let i = 0; i < nodeList.length; i++) { let ipAddress = nodeList[i].address; $.ajax({ type: 'GET', url: '/' + ipAddress, success: function (result) { let sData = $(result).find('Data').text(); seriesData.name.push(ipAddress); seriesData.data.push(sData); }, }); } } // Omitted chart options // ... function renderChart() { chart.render(); }
{ "domain": "codereview.stackexchange", "id": 43892, "lm_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, jquery, array, asynchronous, ajax", "url": null }
javascript, jquery, array, asynchronous, ajax // Omitted chart options // ... function renderChart() { chart.render(); } Answer: Initial Review thoughts Before addressing the main question I’d like to address a few points first. Variable declaration style It is nice that seriesData is declared with const, since it never gets reassigned. Some variables within the functions like nodeList, nodes, addresses and ipAddress also are never reassigned so they could also be declared with const. This helps avoid accidental re-assignment and other bugs. ES-6 Object declaration The object pushed into nodeList in the loop uses plain object syntax: nodeList.push({ node: node, address: address }); The shorthand property definition notation can be used to eliminate the keys, since they are the same name as the variables used for the values: nodeList.push({ node, address }); Single use variables The variable ipAddress is only used once. Instead of url: '/' + ipAddress, unless that variable was used for debugging, it can be eliminated: url: '/' + nodeList[i].address, The same is true for node and addressed, but if those were eliminated then the ES-6 shorthand syntax could not be utilized. Main Question The main question posed here is “Is there a better pattern to handle this?” I would first ask if the API supports returning data for multiple nodes in a single endpoint. If this was possible then there would be no need to make multiple requests, improving network efficiency and eliminating the risk of network connection issues, service interruptions for others, etc. One could ask a question like “How to know when all the ajax calls in a loop are completed?” And there are similar questions asked on stack overflow - for example: How to know when all the ajax calls in JQuery each loop are completed?. As the accepted answer suggests, the jQuery utility function jQuery.when() can be used to execute a callback function when promises are completed. Note that $.ajax() returns a jqXHR object and
{ "domain": "codereview.stackexchange", "id": 43892, "lm_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, jquery, array, asynchronous, ajax", "url": null }
javascript, jquery, array, asynchronous, ajax The jqXHR objects returned by $.ajax() as of jQuery 1.5 implement the Promise interface, giving them all the properties, methods, and behavior of a Promise (see Deferred object for more information). By putting the return values from calling $.ajax() into an array, that array can be passed in a call to $.when() so renderChart() can then be called after all of the requests have completed. See the example below for a demonstration. It uses the convenience method $.get() instead of $.ajax() to skip passing type: 'GET',. As the log may show- the requests often finish in an order that is not sequential. const seriesData = { name: [], data: [], }; let count = 0; const progressBar = $('progress'); function getNodeList() { $('#log').append($('<div>').html(`fetching list of ships from API`)); $.ajax({ type: 'GET', url: 'https://swapi.dev/api/vehicles/', success: function(ships) { if ((typeof ships !== 'object') || !ships.hasOwnProperty('results')) { console.error('invalid response', ships) return; } progressBar.val(++count); $('#log').append($('<div>').html(`got list of ships from API`)); getData(ships.results.slice(0, 5).map(ship => ship.url), seriesData); }, }); } function getData(nodeList, seriesData) { const promises = nodeList.map((url, i) => $.get({ url, success: function(ship) { seriesData.name.push(ship.name); seriesData.data.push(ship.length); progressBar.val(++count); $('#log').append($('<div>').html(`${i+1} added ${ship.name} with length: ${ship.length}m`)); }, }) ); $.when(...promises).then(function(result) { renderChart(); }); } // Omitted chart options // ... getNodeList()
{ "domain": "codereview.stackexchange", "id": 43892, "lm_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, jquery, array, asynchronous, ajax", "url": null }
javascript, jquery, array, asynchronous, ajax // Omitted chart options // ... getNodeList() function renderChart() { Chart.defaults.global.legend.display = false; const config = { type: 'bar', data: { labels: seriesData.name, datasets: [{ data: seriesData.data, label: 'Ship Length', backgroundColor: 'red', borderColor: 'green', fill: false }] }, options: { title: { display: true, text: 'Ship Lengths' }, scales: { xAxes: [{ display: true, scaleLabel: { display: true, labelString: 'Ship' } }], yAxes: [{ display: true, scaleLabel: { display: true, labelString: 'Length (meters)' } }] } } }; const ctx = document.getElementById('canvas').getContext('2d'); new Chart(ctx, config); } #loading_container { display: flex; flex-direction: row; } #loading_container > progress { flex: auto; } #loading_container > span { width: 9rem; } #log { font-size: x-small; } <script src="//www.chartjs.org/dist/2.7.2/Chart.bundle.js"></script> <script src="//www.chartjs.org/samples/latest/utils.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="loading_container"> <span>Loading Progress:</span> <progress max="6" value="0"></progress> </div> <span id="log"></span> <div> <canvas id="canvas"></canvas> </div> If one wasn't using jQuery, the generic method Promise.all() could be used to execute a callback when promises are completed.
{ "domain": "codereview.stackexchange", "id": 43892, "lm_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, jquery, array, asynchronous, ajax", "url": null }
python, combinatorics Title: Print all "balanced" sequences of 'A' and 'B' Question: the aim of the code below is to print all balanced sequences with equal number of 'A' and 'B'. A sequence is balanced if every prefix of length \$\geqslant 4\$ is balanced. A prefix is balanced if the ratio of 'A' in this prefix is between 0.4 and 0.6 inclusive. For example, ['A', 'B', 'B', 'A', 'A', 'B', 'A', 'B'] is balanced because: Prefix Ratio of 'A' ['A', 'B', 'B', 'A'] 2/4 = 0.5 ['A', 'B', 'B', 'A', 'A'] 3/5 = 0.6 ['A', 'B', 'B', 'A', 'A', 'B'] 3/6 = 0.5 ['A', 'B', 'B', 'A', 'A', 'B', 'A'] 4/7 = 0.57 ['A', 'B', 'B', 'A', 'A', 'B', 'A', 'B'] 4/8 = 0.5 On the other hand, ['A', 'B', 'B', 'A', 'A', 'A', 'B', 'B'] is not balanced, because the ratio of 'A' in the prefix ['A', 'B', 'B', 'A', 'A', 'A'] is 4/6 = 0.67, which is too high. The code: from itertools import combinations n = 8 MIN_RATIO = 0.4 for c in combinations(range(n), n // 2): is_balanced = True for prefix_len in range(4, n): prefix_ratio = sum([1 if i < prefix_len else 0 for i in c]) / prefix_len if not (MIN_RATIO <= prefix_ratio <= 1 - MIN_RATIO): is_balanced = False break if is_balanced: res = ['A' if i in c else 'B' for i in range(n)] print(res) The idea here is that there are \$\binom{n}{n/2}\$ ways to place the \$\frac{n}{2}\$ 'A's in a sequence of length \$n\$; the other \$\frac{n}{2}\$ places will be occupied by the 'B's. (\$n\$ is assumed to be even.) Each one of the \$\binom{n}{n/2}\$ ways is tested for being balanced, and if so - a suitable sequence of 'A' and 'B' is generated and printed. I'm not sure whether my code is readable enough, or whether there are a simpler and/or more elegant algorithm. Please review my code for readability and elegance. Answer: Refactor to use functions Try to avoid boolean variables. Pseudocode like: result = True for item in iterable: if item fails test: result = False break if result: do stuff
{ "domain": "codereview.stackexchange", "id": 43893, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, combinatorics", "url": null }
python, combinatorics if result: do stuff can almost always be refactored to: def any_item_fails_test(iterable): for item in iterable: if item fails test: return False return True if any_item_fails_test(iterable): do stuff This is an improvement because it breaks a logical operation out to a separate function, cleaning up the calling code, reducing state, making debugging easier and promoting reusability. It provides a name for the operation and shows its dependent data as parameters. I suggest putting all of your code into functions rather than loose in the global scope. In addition to the above organizational reasons, this should provide faster execution in CPython. The typical setup for a main program or small script is def main(): # your code here if __name__ == "__main__": main() While you're going about creating functions, take hardcoded variables like n = 8 MIN_RATIO = 0.4 and make them parameters to the function. This facilitates reuse and makes the calling code clearer. I only use global constants like MIN_RATIO when the value is unlikely to change, is used everywhere in the program and is more than just an argument that can be conveniently passed as a parameter in one or two places. List comprehensions vs generators sum([1 if i < prefix_len else 0 for i in c]) is good because the list comprehension is faster than a generator unless memory consumption is an issue, in which case consider using a generator here. I haven't thought about the algorithm here much, but since combinations can blow up in size quickly, you'll typically want to return a generator rather than a list once you put this into a function. Let the caller consume the result as they see fit, optionally printing the results. len([x for x in combination if x < prefix_len]) seems a bit clearer since we're trying to filter out elements that fail a predicate, then count how many passed.
{ "domain": "codereview.stackexchange", "id": 43893, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, combinatorics", "url": null }
python, combinatorics Simplify conditions The condition if not (MIN_RATIO <= prefix_ratio <= 1 - MIN_RATIO): is a bit too clever for me to grasp; negation adds a good deal of cognitive load. It seems clearer to write it positively: if prefix_ratio < MIN_RATIO or prefix_ratio > 1 - MIN_RATIO: Suggested rewrite from itertools import combinations def is_balanced(n, combination, min_ratio, start=4): for prefix_len in range(start, n): prefix_sum = len([x for x in combination if x < prefix_len]) prefix_ratio = prefix_sum / prefix_len if prefix_ratio < min_ratio or prefix_ratio > 1 - min_ratio: return False return True def all_balanced_sequences(n, min_ratio, chars="AB"): if len(chars) != 2: raise ArgumentError("chars length must be 2") for combination in combinations(range(n), n // 2): if is_balanced(n, combination, min_ratio): yield [chars[0] if i in combination else chars[1] for i in range(n)] def main(): for seq in all_balanced_sequences(n=8, min_ratio=0.4): print(seq) if __name__ == "__main__": main()
{ "domain": "codereview.stackexchange", "id": 43893, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, combinatorics", "url": null }
c++, performance, strings, memory-management, memory-optimization Title: StringPool in C++ Question: I wrote a simple string pool for my compiler in C++ and want to hear your thoughts on its design. String pool has 2 functions: intern and internLiteral. The only difference is that after interning literal, its memory is used. So no allocation happens. If memory for the same string was already allocated, it will be deallocated. Hence, I have 2 destruction behaviours differentiated by StringType enum. I also want my InternedStrings to have interface of const std::string_view (basically because of size method). EDIT: Added concept for char allocator Strings are always null-terminated Added tests (all passed) Fixed compilation EDIT: Removed shared_ptr and weak_ptr. Use raw pointer Now, after interning literals, previously allocated memory for the same non-literal string will be deallocated Simplified logic Updated test FAQ: How to use InternedString? InternedString is only meant to do 2 things: O(1) equality check (as it is a pointer to const std::string_view) read-only access to string StringPool shouldn't be destroyed, while InternedString exists. Is StringPool worth it? Well, it depends. My use case is a compiler, where I have a lot of repeated strings for keywords, common functions names, etc. Let's take while keyword for example. Null-terminated "while" string contains 6 bytes. StringPool uses additional sizeof(std::string_view) bytes for it. After 4 while keywords we start gaining profit. And comparing pointers is extremely fast Why care about literals? I want to "preallocate" keywords, I already use in my program as literals. But it's a very small optimization, and I may delete it to simplify pool. #pragma once #include <string_view> #include <unordered_map> /** * @file StringPool.hpp * @brief Manage pool of strings. * Pros: * - No allocation for repeated strings * - No allocation for literals * - Strings have stable addresses -- fast to check for equality */ namespace ppl::common {
{ "domain": "codereview.stackexchange", "id": 43894, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, performance, strings, memory-management, memory-optimization", "url": null }
c++, performance, strings, memory-management, memory-optimization namespace ppl::common { /// Reference to string, interned in the pool using InternedString = const std::string_view *; namespace concepts { /// Concept for char allocator template<typename T> concept CharAllocator = requires(T t, char *str, size_t size) { { t.allocate(size) } -> std::same_as<char *>; { t.deallocate(str, size) }; }; } /// Pool of strings template<concepts::CharAllocator Allocator = std::allocator<char>> class StringPool { public: /// Allocator, used by pool Allocator allocator; /// Perfect forward arguments to allocator template<typename ...Args> requires std::is_constructible_v<Allocator, Args...> StringPool(Args &&... args) noexcept : allocator(std::forward<Args>(args)...) {} /// Forbid copy StringPool(const StringPool &) = delete; /// Forbid copy StringPool &operator=(const StringPool &) = delete; /// Allow move StringPool(StringPool &&) = default; /// Allow move StringPool &operator=(StringPool &&) = default; /// @brief Intern a string literal on the pool /// @note Never allocates memory for string /// @note Deallocates memory for previously interned non-literal string InternedString internLiteral(const char *literal) { std::string_view view{literal}; auto [it, _] = strings.emplace(view, StringType::literal); if (it->second == StringType::allocated) { // We can safely change it to be a view over literal, // because it's exactly the same string. // // ...But I'm not sure auto &oldView = const_cast<std::string_view &>(it->first); deallocateViewContent(oldView); oldView = view; it->second = StringType::literal; } return &it->first; }
{ "domain": "codereview.stackexchange", "id": 43894, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, performance, strings, memory-management, memory-optimization", "url": null }
c++, performance, strings, memory-management, memory-optimization /// @brief Intern a string on the pool /// @note /// If string is a literal, /// use @c internLiteral() instead for memory efficiency InternedString intern(std::string_view str) { if (auto it = strings.find(str); it != strings.end()) { return &it->first; } auto *allocated = allocator.allocate(str.size() + 1); if (!allocated) { return nullptr; } std::uninitialized_copy(str.begin(), str.end(), allocated); allocated[str.size()] = '\0'; return &strings.emplace( std::string_view{allocated, str.size()}, StringType::allocated ).first->first; } /// Deallocate memory ~StringPool() { for (auto &[str, type] : strings) { if (type == StringType::allocated) { deallocateViewContent(str); } } } private: /// Deallocate string that is viewed void deallocateViewContent(std::string_view view) { allocator.deallocate( const_cast<char *>(view.data()), view.size() + 1 ); } /// Type of string enum class StringType { literal, // Doesn't need deallocation allocated // Needs deallocation }; /// Interned strings std::unordered_map< std::string_view, StringType > strings; }; } // namespace ppl::common Google tests: #include <gtest/gtest.h> #include "ppl/common/StringPool.hpp" template<typename Allocator> struct TrackAllocator { Allocator allocator; char * allocate(size_t size) { ++allocations; return allocator.allocate(size); } void deallocate(char *str, size_t size) { ++deallocations; allocator.deallocate(str, size); } size_t allocations = 0; size_t deallocations = 0; };
{ "domain": "codereview.stackexchange", "id": 43894, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, performance, strings, memory-management, memory-optimization", "url": null }
c++, performance, strings, memory-management, memory-optimization size_t allocations = 0; size_t deallocations = 0; }; /// Doesn't allocate memory struct NullAllocator { char * allocate(size_t) { return nullptr; } void deallocate([[maybe_unused]]char *ptr, size_t) { assert(!ptr); } }; using namespace ppl::common; TEST(StringPool, internLiteralFirst) { auto pool = StringPool<TrackAllocator<NullAllocator>> { TrackAllocator<NullAllocator>{} }; const char *literal = "Hello"; auto internedLiteral = pool.internLiteral(literal); ASSERT_EQ(pool.allocator.allocations, 0); ASSERT_EQ(pool.allocator.deallocations, 0); ASSERT_EQ(internedLiteral->data(), literal); auto internedLiteral1 = pool.internLiteral(literal); ASSERT_EQ(pool.allocator.allocations, 0); ASSERT_EQ(pool.allocator.deallocations, 0); ASSERT_EQ(internedLiteral1, internedLiteral); std::string str = literal; auto internedStr = pool.intern(str); ASSERT_EQ(pool.allocator.allocations, 0); ASSERT_EQ(pool.allocator.deallocations, 0); ASSERT_EQ(internedStr, internedLiteral); } TEST(StringPool, internFirst) { TrackAllocator<std::allocator<char>> trackAllocator; { StringPool<TrackAllocator<std::allocator<char>> &> pool(trackAllocator); const char *literal = "Hello"; std::string str = literal; auto internedStr = pool.intern(str); ASSERT_EQ(pool.allocator.allocations, 1); ASSERT_EQ(pool.allocator.deallocations, 0); ASSERT_EQ(*internedStr, literal); auto internedLiteral = pool.internLiteral(literal); ASSERT_EQ(pool.allocator.allocations, 1); // Note that internedStr was deallocated ASSERT_EQ(pool.allocator.deallocations, 1); ASSERT_EQ(internedLiteral, internedStr); // Note that literal's memory is used instead ASSERT_EQ(internedLiteral->data(), literal); } ASSERT_EQ(trackAllocator.deallocations, 1); }
{ "domain": "codereview.stackexchange", "id": 43894, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, performance, strings, memory-management, memory-optimization", "url": null }
c++, performance, strings, memory-management, memory-optimization TEST(StringPool, allocationFailure) { TrackAllocator<NullAllocator> trackAllocator; { auto pool = StringPool<TrackAllocator<NullAllocator> &> { trackAllocator }; std::string str = "hello"; auto internedStr = pool.intern(str); ASSERT_FALSE(internedStr); ASSERT_EQ(pool.allocator.allocations, 1); ASSERT_EQ(pool.allocator.deallocations, 0); } ASSERT_EQ(trackAllocator.deallocations, 0); } P.S: don't know how to handle if InternedString outlives the pool. I guess, it's not an issue of string pool, but an incorrect usage. Answer: Make it more generic You have already written somewhat generic code, as StringPool is a template. However, you can go further than that. First, consider that std::string is actually a std::basic_string<char>. You could add the same template parameters as std::basic_string has: template<typename CharT = char, typename Traits = std::char_traits<CharT>, typename Allocator = std::allocator<CharT>> class StringPool { const Allocator& allocator; ... };
{ "domain": "codereview.stackexchange", "id": 43894, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, performance, strings, memory-management, memory-optimization", "url": null }
c++, performance, strings, memory-management, memory-optimization Note that the allocator is stored by reference, just like std::basic_string<> does. This allows multiple pools to use the same allocator object. Replacing an allocated string with a literal is dangerous There are potential issues with replacing an allocated string with a literal. While InternedString is a stable pointer to a std::string_view stored in the pool, consider that some code might at some point copy a dereferenced InternedString somewhere. That is of course something it probably shouldn't do, but still. A more realistic problem is if you have multi-threaded code. In that case, one thread might have dereferenced an allocated string, while another thread is replacing it with a literal. You could place restrictions on the users of your code, and forbid multi-threaded access, but it's hard to enforce that programmatically. Make sure that these restrictions are documented, and possibly add run-time assertions to the code to catch misuse. Also consider that pre-C++11, std::string was copy-on-write, which caused lots of issues, and ultimately led to the standards committee to forbid that. Don't handle literals at all I don't think there is much point in letting your pool handle the difference between literals and non-literals. Most compilers will already detect duplicate string literals and will merge them. If you don't need to deal with literals, all strings will be allocated, and then you can avoid the whole manual allocation dance by storing strings in a std::unordered_set<std::string>. Is it worth it? Consider whether it is worth having a pool at all. How many bytes are saved by deduplicating strings? Conversely, how much memory is now used by all the std::string_view objects (one in the pool itself, and one copy the caller of intern() has to keep), and how much is the overhead of the std::unordered_map?
{ "domain": "codereview.stackexchange", "id": 43894, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, performance, strings, memory-management, memory-optimization", "url": null }
c++, performance, strings, memory-management, memory-optimization Also consider that if you are mostly interested in deduplicating and comparing small strings: since C++11, on most platforms std::string comes with small string optimization (SSO). That means if the string is smaller than almost sizeof(std::string), it doesn't perform an allocation, and comparing two such std::strings is almost as fast as comparing two std::string_views. In fact, it is likely to be faster to compare two small std::strings if they are unequal!
{ "domain": "codereview.stackexchange", "id": 43894, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, performance, strings, memory-management, memory-optimization", "url": null }
java, matrix Title: Immutable matrix class with mathematical methods Question: This was a homework assignment for a data structures course. The goal was to implement a given interface and the assignment was auto-graded by a system that ran some validation tests. Sadly I did not really get any feed back on the code structure or any advice on how to improve on what I did if anything was wrong or non-idiomatic for java, a language I have not really use outside of this course. I am particularly interested in if my code for handling the math operations is silly or "overly clever" or maybe if there is a better way I could have achieved a similar pattern that would be more idiomatic for someone well versed in java. interface MathOperation { int Run(int a, int b); } interface MatrixOperation { void Run(int row, int column); } public class CompletedMatrix implements Matrix { private int[][] _matrix; public CompletedMatrix(int[][] matrix) { if (!NullCheck(matrix)) { throw new IllegalArgumentException("Cannot perform operation on null matrix"); } _matrix = new int[matrix.length][]; for (int row = 0; row < matrix.length; row++) { _matrix[row] = matrix[row].clone(); } } @Override public int getElement(int y, int x) { return _matrix[y][x]; } @Override public int getRows() { return _matrix.length; } @Override public int getColumns() { int columns = 0; if (this.getRows() != 0) { columns = _matrix[0].length; for (int row = 1; row < this.getRows(); row++) { if (columns != _matrix[row].length) { throw new RuntimeException("Matrices do not have matching dimensions"); } } } return columns; }
{ "domain": "codereview.stackexchange", "id": 43895, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, matrix", "url": null }
java, matrix return columns; } @Override public Matrix plus(Matrix other) { return ExecuteMatrixMathOperation(other, (a, b) -> a + b); } @Override public Matrix minus(Matrix other) { return ExecuteMatrixMathOperation(other, (a, b) -> a - b); } @Override public Matrix multiply(Matrix other) { return ExecuteMatrixMathOperation(other, (a, b) -> a * b); } private Matrix ExecuteMatrixMathOperation(Matrix b, MathOperation op) { ValidateMatrix(b); int[][] result = new int[this.getRows()][this.getColumns()]; MatrixOperation((row, column) -> { result[row][column] = op.Run(this.getElement(row, column), b.getElement(row, column)); }); return new CompletedMatrix(result); } private void ValidateMatrix(Matrix other) { if (!NullCheck(other)) { throw new IllegalArgumentException("Cannot perform operation on null matrix"); } if (!DimensionsMatch(other)) { throw new RuntimeException("Matrices do not have matching dimensions"); } } private boolean NullCheck(Object other) { return (this != null && other != null); } private boolean DimensionsMatch(Matrix other) { return (this.getRows() == other.getRows() && this.getColumns() == other.getColumns()); } private void MatrixOperation(MatrixOperation op) { for(int row = 0; row < this.getRows(); row++) { for(int column = 0; column < this.getColumns(); column++) { op.Run(row, column); } } } }
{ "domain": "codereview.stackexchange", "id": 43895, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, matrix", "url": null }
java, matrix This is a trimmed down interface given in the assignment public interface Matrix { public int getElement(int y, int x); public int getRows(); public int getColumns(); public Matrix plus(Matrix other); public Matrix minus(Matrix other); public Matrix multiply(Matrix other); }
{ "domain": "codereview.stackexchange", "id": 43895, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, matrix", "url": null }
java, matrix Answer: In canonical java, Methods use camelCase. This visually distinguishes them from classes, which start with a capital letter. Open parens are on the same line, not a new line Underscores are not used to indicate instance variables There is whitespace between a control flow keyword (for, if, while, do) and the open paren. This visually distinguishes it from a method call. The method nullCheck is just overhead. this != null will always be true, so the only part that matters is other != null. High preferable would be Objects.requireNonNull(). The exception message in the constructor is confusing. Constructing an objects is not "perform[ing] an operation". getColumns is the wrong place to validate the columns are correct. What if the client passes in a malformed matrix and then never calls getColumns? Validating the invariants of a class belongs in the constructor to that class. This check can be folded into the copying of the rows. When throwing exceptions, try to provide enough information in the exception message to debug. For instance, don't just say there's a mismatch in column lengths, also call out the rows which don't match. The matrix parameter starts as "other", which I'm not a big fan of, and then inexplicably becomes b in executeMatrixMathOperation. This is confusing on its own, and made worse by the use of b in the anonymous function definitions in plus, minus, and multiply. I'd really rather the parameter was consistently named matrix, or perhaps otherMatrix. other isn't meaningful, and neither is b. When an argument is invalid, prefer an IllegalArgumentException over the more generic RuntimeException. dimensionsMatch can be folded into validateMatrix. There's not enough there to be its own method. op is inadequately descriptive. mathOperation or matrixOperation would be preferable, especially since the same parameter name is reused for both kinds of operation. You don't "run" a mathematical operation, you evaluate it.
{ "domain": "codereview.stackexchange", "id": 43895, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, matrix", "url": null }
java, matrix You don't "run" a mathematical operation, you evaluate it. The matrixOperation method implementation can be moved into executeMatrixMathOperation. The extra complexity is not worth the method being 2 lines shorter. I'm not super fond of being able to declare a new CompletedMatrix(new int[0][5]), then calling getColumns() and getting back 0. If this is the expected behavior, it should be documented. If you made all these changes, your code might look more like: import java.util.Objects;
{ "domain": "codereview.stackexchange", "id": 43895, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, matrix", "url": null }
java, matrix public final class CompletedMatrix implements Matrix { private final int[][] matrix; public CompletedMatrix(int[][] matrix) { Objects.requireNonNull(matrix, "`matrix` parameter may not be null."); if (matrix.length == 0) { this.matrix = new int[0][0]; return; } this.matrix = new int[matrix.length][]; int columns = matrix[0].length; for (int row = 0; row < matrix.length; row++) { this.matrix[row] = matrix[row].clone(); if (matrix[row].length != columns) { throw new IllegalArgumentException("All rows must have the same number of columns. Row 0 has " + columns + " columns, but row " + row + " has " + matrix[row].length); } } } @Override public int getElement(int y, int x) { return matrix[y][x]; } @Override public int getRows() { return matrix.length; } @Override public int getColumns() { return (matrix.length == 0) ? 0 : matrix[0].length; } @Override public Matrix plus(Matrix otherMatrix) { return executeMatrixMathOperation(otherMatrix, (a, b) -> a + b); } @Override public Matrix minus(Matrix otherMatrix) { return executeMatrixMathOperation(otherMatrix, (a, b) -> a - b); } @Override public Matrix multiply(Matrix otherMatrix) { return executeMatrixMathOperation(otherMatrix, (a, b) -> a * b); } private Matrix executeMatrixMathOperation(Matrix otherMatrix, MathOperation mathOperation) { validateMatrix(otherMatrix);
{ "domain": "codereview.stackexchange", "id": 43895, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, matrix", "url": null }
java, matrix int[][] result = new int[this.getRows()][this.getColumns()]; for (int row = 0; row < this.getRows(); row++) { for (int column = 0; column < this.getColumns(); column++) { result[row][column] = mathOperation.evaluate(this.getElement(row, column), otherMatrix.getElement(row, column)); } } return new CompletedMatrix(result); } private void validateMatrix(Matrix otherMatrix) { Objects.requireNonNull(otherMatrix, "`otherMatrix` parameter may not be null."); if ((this.getRows() != otherMatrix.getRows()) || (this.getColumns() != otherMatrix.getColumns())) { throw new IllegalArgumentException("Cannot operate on matrixes of different sizes. This matrix has " + this.getRows() + " rows and " + this.getColumns() + " columns, while the argument matrix has " + otherMatrix.getRows() + " rows and " + otherMatrix.getColumns() + "columns"); } } }
{ "domain": "codereview.stackexchange", "id": 43895, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, matrix", "url": null }
performance, python-3.x, web-scraping, python-requests Title: request data and print results Question: On last test, the below code takes approximately 10 seconds to download then print the data from 10 url's. I wish to speed this up as much as possible as later on I plan to expand this further and use the scraped data as live data in a GUI. The display_value() function consists of 95% of the time, which seems like an awful lot considering it's a small number. I am thinking it's due to how I've written the function call, but out of ideas. def live_indices(): import sys """Acquire stock value from Yahoo Finance using stock symbol as key. Then assign the relevant variable to the respective value. ie. 'GSPC' equates to the value keyed to 'GSPC' stock indices_price_value. """ start_time = datetime.datetime.now() # Use to time how long the function takes to complete import requests import bs4 headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.61 Safari/537.36'} all_indices_values = {} symbols = ['GSPC', 'DJI', 'IXIC', 'FTSE', 'NSEI', 'FCHI', 'N225', 'GDAXI', 'IMOEX.ME', '000001.SS'] for ticker in symbols: url = f'https://uk.finance.yahoo.com/lookup/all?s={ticker}' tmp_res = requests.get(url, headers=headers) tmp_res.raise_for_status() soup = bs4.BeautifulSoup(tmp_res.text, 'html.parser') indices_price_value = soup.select('#Main tbody>tr td')[2].text all_indices_values[ticker] = indices_price_value end_time = datetime.datetime.now() - start_time sys.stdout.write(f'DONE - time taken = {end_time}'.upper()) return all_indices_values
{ "domain": "codereview.stackexchange", "id": 43896, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "performance, python-3.x, web-scraping, python-requests", "url": null }
performance, python-3.x, web-scraping, python-requests return all_indices_values def display_value(live_indices): print(live_indices['GSPC']) print(live_indices['DJI']) print(live_indices['IXIC']) print(live_indices['FTSE']) print(live_indices['NSEI']) print(live_indices['FCHI']) print(live_indices['N225']) print(live_indices['GDAXI']) print(live_indices['IMOEX.ME']) print(live_indices['000001.SS']) display_value(live_indices()) Answer: I think your profiling potentially is misleading. Neither 10 prints nor accessing 10 dictionary keys should take upwards 10 seconds. Maybe try profiling again with something like def display_values(live_indices): for key in SYMBOLS: print(key) all_indices_values = live_indices() display_values(all_indices_values) Now, to actually speed up the requests you will have to use parallelism. You are currently doing sequential requests, which understandably takes forever since you have to wait for each scrape to finish before starting the next one. You can probably also look for some API instead of scraping web pages for the data; that should decrease the payload by quite a bit. If you do not already know, there are modules for both profiling and for timing built into the standard library - you don't need to manually try to time stuff.
{ "domain": "codereview.stackexchange", "id": 43896, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "performance, python-3.x, web-scraping, python-requests", "url": null }
beginner, php, converting, number-systems, roman-numerals Title: Convert integer to Roman numeral string Question: This is my 1st time developing PHP code and I am only 13 years old. I have experience in other programming languages like lua, python, and c++. This is a simple Number to Roman Numeral code I made for my mom because she had a hard time making herself one. Below is my code. Don't mind the names of the variables. <?php
{ "domain": "codereview.stackexchange", "id": 43897, "lm_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, php, converting, number-systems, roman-numerals", "url": null }
beginner, php, converting, number-systems, roman-numerals $NumberRomanNumeral = array( 1 => array( "RomanNumeral" => "I", "NearestNum" => null ), 5 => array( "RomanNumeral" => "V", "NearestNum" => 4 ), 10 => array( "RomanNumeral" => "X", "NearestNum" => 9 ), 50 => array( "RomanNumeral" => "L", "NearestNum" => 40 ), 100 => array( "RomanNumeral" => "C", "NearestNum" => 90 ), 500 => array( "RomanNumeral" => "D", "NearestNum" => 400 ), 1000 => array( "RomanNumeral" => "M", "NearestNum" => 900 ), ); function separateNumberIntoUnits($n) { $separated = str_split($n,1); for ($i = 0;$i <= count($separated)-1; $i++){ $currentNum = $separated[$i]; $length = count($separated) - $i; $separated[$i] = str_pad($currentNum, $length, "0"); } return $separated; } function getClosestNum($numToFind){ //echo($numToFind); global $NumberRomanNumeral; $closestNum = null; $foundKey = null; $closestMag = null; $differenceArray = array(); $numLeft = null; if ($numToFind == 0) { return null; } foreach($NumberRomanNumeral as $num => $data){ array_push($differenceArray, $data["NearestNum"]); } foreach($NumberRomanNumeral as $num => $data){ $currentIndex = array_search($num,array_keys($NumberRomanNumeral)); $romanNumeral = $data["RomanNumeral"]; $differenceToSum = $data["NearestNum"]; $previousDifferenceToSum = null;
{ "domain": "codereview.stackexchange", "id": 43897, "lm_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, php, converting, number-systems, roman-numerals", "url": null }
beginner, php, converting, number-systems, roman-numerals if ($num != 1){ $previousDifferenceToSum = $differenceArray[$currentIndex-1]; } $mag = $num - $numToFind; if ($mag < 0){ $mag *= -1; } if ($numToFind == $num){ $closestNum = $num; $foundKey = $romanNumeral; break; }elseif($numToFind == $differenceToSum){ $closestNum = $num; $foundKey = $romanNumeral; break; } if ($closestMag == null){ $closestNum = $num; $closestMag = $mag; $foundKey = $romanNumeral; } else { if ($mag < $closestMag && $mag > $previousDifferenceToSum) { $closestNum = $num; $closestMag = $mag; $foundKey = $romanNumeral; } } } $numLeft = $numToFind - $closestNum; if ($numLeft < 0){ $numLeft *= -1; } return array($closestNum, $foundKey, $numLeft); } function num2RomanNumeral($num, &$string){ if ($num != null || $num != 0){ $numArray = separateNumberIntoUnits($num); foreach($numArray as $splitNum){ $data = getClosestNum($splitNum); if ($data != null){ $closestNumber = $data[0]; $foundRomanNumeral = $data[1]; $numLeft = $data[2]; if ($splitNum > $closestNumber){ $string = $string.$foundRomanNumeral; if ($numLeft > 0){ num2RomanNumeral($numLeft, $string); } }elseif($splitNum < $closestNumber){ if ($numLeft > 0){ num2RomanNumeral($numLeft, $string); }
{ "domain": "codereview.stackexchange", "id": 43897, "lm_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, php, converting, number-systems, roman-numerals", "url": null }
beginner, php, converting, number-systems, roman-numerals num2RomanNumeral($numLeft, $string); } $string = $string.$foundRomanNumeral; }else{ if ($numLeft > 0){ num2RomanNumeral($numLeft, $string); } $string = $string.$foundRomanNumeral; } } } } } $romanNumeralText = "";
{ "domain": "codereview.stackexchange", "id": 43897, "lm_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, php, converting, number-systems, roman-numerals", "url": null }
beginner, php, converting, number-systems, roman-numerals num2RomanNumeral(4212, $romanNumeralText); echo $romanNumeralText; ?> I would appreciate if you give some tips and some things that would make the code better. Answer: For a beginner it seems fine. There are some improvements that can be made. The points below are analysis of the given code. Obviously there are examples of simpler implementations - e.g. see answers to Numbers to Roman Numbers with php on Stack Overflow. While I wouldn't expect a beginner to write a succinct and optimized function they are out there for the reader to compare. Avoid Global variables The first thing I spot is this line near the beginning of getClosestNum() global $NumberRomanNumeral; Global variables have more negative aspects than positives. Since that variable is never re-assigned it can be declared as a constant instead of a variable. Then there is no need to reference a global variable. Coding Style can be changed to be idiomatic I would not expect a beginner to write code that always adheres to a standard coding style, but there are recommended styles that many PHP developers write code to be inline with. One popular style guide is PSR-12. It has many conventions for readability and robust code. There are 54 errors and 1 warning for the code above. Many of the errors concern spacing between operators, tokens, etc. For example, instead of: }elseif($numToFind == $differenceToSum){ Idiomatic PHP code would be spaced like this: } elseif ($numToFind == $differenceToSum) { Array syntax can be simplified There isn't anything wrong with using array() but as of the time of writing, there is currently active support for versions 8.0 and 8.1 of PHP, and since PHP 5.4 arrays can be declared with short array syntax (PHP 5.4). So lines like: $differenceArray = array(); can be simplified like this: $differenceArray = []; Variable gets overwritten The seventh line of getClosestNum() is: $numLeft = null;
{ "domain": "codereview.stackexchange", "id": 43897, "lm_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, php, converting, number-systems, roman-numerals", "url": null }
beginner, php, converting, number-systems, roman-numerals Variable gets overwritten The seventh line of getClosestNum() is: $numLeft = null; Then towards the end of the function, that same variable is assigned with the difference of two other variables. $numLeft = $numToFind - $closestNum; This makes the first assignment (to null) superfluous. That line can be removed. Extra indentation level can be eliminated Near the end of getClosestNum() are these blocks of code: if ($closestMag == null) { $closestNum = $num; $closestMag = $mag; $foundKey = $romanNumeral; } else { if ($mag < $closestMag && $mag > $previousDifferenceToSum) { $closestNum = $num; $closestMag = $mag; $foundKey = $romanNumeral; } } The second if (within the else) can be changed to an elseif: if ($closestMag == null) { $closestNum = $num; $closestMag = $mag; $foundKey = $romanNumeral; } elseif ($mag < $closestMag && $mag > $previousDifferenceToSum) { $closestNum = $num; $closestMag = $mag; $foundKey = $romanNumeral; } This allows for one less indentation level for the lines within the else block.
{ "domain": "codereview.stackexchange", "id": 43897, "lm_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, php, converting, number-systems, roman-numerals", "url": null }
beginner, c, math-expression-eval Title: K&R Exercise 5-10. reverse Polish calculator Question: I have been learning C with K&R Book 2nd Ed. And well, so far I've gotten to chapter five, and I've been dealing with pointers/command line arguments. I came up with the following solution for the exercise (Chapter 5, Ex-5.10): Exercise 5-10. Write the program expr, which evaluates a reverse Polish expression from the command line, where each operator or operand is a separate argument. For example, expr 2 3 4 + * evaluates 2 x (3 + 4). I would like to know how to improve it.: /*- * Exercise 5-10. Write the program expr, which evaluates a reverse Polish * expression from the command line, where each operator or operand is a separate * argument. For example, * * expr 2 3 4 + * * * evaluates 2 x (3 + 4). * * By jr.chavez * * NOTE: * To receive the expected output with the following example: * 2 3 4 + * * '\' must be used (e.g., 2 3 4 + \* instead of *) */ #include <stdio.h> #include <stdlib.h> /* for atof() */ #include <string.h> /* for strlen() */ #include <ctype.h> /* for isdigit() */ #define NUMBER '0' /* signal that a number was found */ #define MAXVAL 100 /* next free stack position */ static int sp = 0; /* next free stack position */ static double val[MAXVAL]; /* value stack */ void push(double); double pop(void);
{ "domain": "codereview.stackexchange", "id": 43898, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "beginner, c, math-expression-eval", "url": null }
beginner, c, math-expression-eval void push(double); double pop(void); /* reverse Polish calculator */ int main(int argc, char *argv[]) { int type, c; double op2; while (--argc > 0) { { char *p = *++argv; type = (!isdigit(c = *p) && strlen(p) == 1) ? c : NUMBER; } switch (type) { case NUMBER: push(atof(*argv)); break; case '+': push(pop() + pop()); break; case '*': push(pop() * pop()); break; case '-': op2 = pop(); push(pop() - op2); break; case '/': op2 = pop(); if (op2 != 0.0) push(pop() / op2); else fprintf(stderr, "error: zero divisor\n"); break; default: fprintf(stderr, "error: unkown command %s\n", *argv); argc = 1; break; } } printf("\t%.8g\n", pop()); return 0; } /* push: push f onto value stack */ void push(double f) { if (sp < MAXVAL) val[sp++] = f; else fprintf(stderr, "error: stack full, can't push %g\n", f); } /* pop: pop and return top value from stack */ double pop(void) { if (sp > 0) return val[--sp]; else { fprintf(stderr, "error: empty stack\n"); return 0.0; } } input: ./bin/main 2 3 4 + \* output: 14 Note: I decided not to add options like sin, cos, exp, and pow.
{ "domain": "codereview.stackexchange", "id": 43898, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "beginner, c, math-expression-eval", "url": null }
beginner, c, math-expression-eval output: 14 Note: I decided not to add options like sin, cos, exp, and pow. Answer: General Observations Nice comment block at the top. The comments on the include files are unnecessary. What happens with 2 digit numbers? Example 15 10 *? Avoid Global Variables It is very difficult to read, write, debug and maintain programs that use global variables. Global variables can be modified by any function within the program and therefore require each function to be examined before making changes in the code. In C and C++ global variables impact the namespace and they can cause linking errors if they are defined in multiple files. The answers in this stackoverflow question provide a fuller explanation. Code Organization Function prototypes are very useful in large programs that contain multiple source files, and that in case they will be in header files. In a single file program like this it is better to put the main() function at the bottom of the file and all the functions that get used in the proper order above main(). Keep in mind that every line of code written is another line of code where a bug can crawl into the code.
{ "domain": "codereview.stackexchange", "id": 43898, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "beginner, c, math-expression-eval", "url": null }
beginner, reinventing-the-wheel, rust Title: Quadratic equation solver using ABC and PQ formula Question: Getting my feet wet with Rust, I implemented a solver for quadratic equations. I implemented both, ABC and PQ formula solvers, to challenge myself with branch conditions. main.rs mod quadratic; use quadratic::QuadraticEquation; fn main() { let equation1 = QuadraticEquation::new(3.0, 3.0, -18.0); let equation2 = QuadraticEquation::new(1.0, 3.0, -18.0); let equation3 = QuadraticEquation::new(-4.0, -5.0, 12.0); let equation4 = QuadraticEquation::new(1.0, 0.0, 50.0); let equation5 = QuadraticEquation::new(1.0, 0.0, 1.0); println!("The solutions of {} are {}", equation1, equation1.solve()); println!("The solutions of {} are {}", equation2, equation2.solve()); println!("The solutions of {} are {}", equation3, equation3.solve()); println!("The solutions of {} are {}", equation4, equation4.solve()); println!("The solutions of {} are {}", equation5, equation5.solve()); } quadratic.rs use std::fmt; mod solution; pub use self::solution::Solution; mod functions; use self::functions::with_sign; pub struct QuadraticEquation { a: f64, b: f64, c: f64, } impl QuadraticEquation { pub fn new(a: f64, b: f64, c: f64) -> QuadraticEquation { QuadraticEquation { a: a, b: b, c: c } } pub fn solve_abc(&self) -> Solution { let root = f64::sqrt(f64::powi(self.b, 2) - 4.0 * self.a * self.c); let x1 = (-self.b + root) / (2f64 * self.a); let x2 = (-self.b - root) / (2f64 * self.a); Solution::new(x1, x2) } pub fn solve_pq(&self) -> Solution { if self.a != 1.0 { return Solution::none(); } let minus_b_half = -self.b / 2.0; let root = f64::sqrt(f64::powi(self.b / 2.0, 2) - self.c); let x1 = minus_b_half + root; let x2 = minus_b_half - root; Solution::new(x1, x2) }
{ "domain": "codereview.stackexchange", "id": 43899, "lm_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, reinventing-the-wheel, rust", "url": null }
beginner, reinventing-the-wheel, rust pub fn solve(&self) -> Solution { if self.a == 1.0 { println!("a = 1 -> Using pq-formula."); self.solve_pq() } else { self.solve_abc() } } pub fn to_string(&self) -> String { let mut result = Vec::new(); if self.a != 0.0 { result.push(format!("{}x²", with_sign(self.a, true, result.is_empty()))); } if self.b != 0.0 { result.push(format!("{}x", with_sign(self.b, true, result.is_empty()))); } if self.c != 0.0 { result.push(with_sign(self.c, false, result.is_empty())); } result.join(" ") } } impl fmt::Display for QuadraticEquation { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self.to_string()) } } quadratic/solution.rs use std::fmt; pub struct Solution { pub x1: f64, pub x2: f64, } impl Solution { pub fn new(x1: f64, x2: f64) -> Solution { Solution { x1: x1, x2: x2 } } pub fn none() -> Solution { Solution::new(f64::NAN, f64::NAN) } pub fn error(&self) -> bool { self.x1.is_nan() && self.x2.is_nan() } pub fn to_string(&self) -> String { if self.error() { "N/A".to_string() } else { format!("x₁ = {}, x₂ = {}", self.x1, self.x2) } } } impl fmt::Display for Solution { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self.to_string()) } } quadratic/functions.rs pub fn with_sign(number: f64, omit_one: bool, first: bool) -> String { if number < 0.0 { with_minus(abs_str(number, omit_one), first) } else { with_plus(abs_str(number, omit_one), first) } } fn abs_str(number: f64, omit_one: bool) -> String { if omit_one { empty_if_one(number.abs()) } else { number.abs().to_string() } }
{ "domain": "codereview.stackexchange", "id": 43899, "lm_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, reinventing-the-wheel, rust", "url": null }
beginner, reinventing-the-wheel, rust fn with_minus(number: String, first: bool) -> String { if first { format!("-{}", number) } else { format!("- {}", number) } } fn with_plus(number: String, first: bool) -> String { if first { number } else { format!("+ {}", number) } } fn empty_if_one(number: f64) -> String { if number == 1.0 { "".to_string() } else { number.to_string() } } How can I improve the code? Answer: For one, the special case of a=1 is not very interesting. You could as well remove the branch and just use abc everytime. Instead you could check if a is close to 0 and choose a different formula that is more numerically stable in this case. Second I dislike the flag arguments a little: with_sign(number: f64, omit_one: bool, first: bool) They make the call site cryptic, I can hardly see why the arguments are passed that way. I would replace this with 2 separate functions: One for the sign/operator and one for the coefficient: if self.a != 0.0 { let withSpace = result.any(); // Not sure if this works in Rust result.push(format_sign(self.a, withSpace)) result.push(format!("{}x²", format_coefficient(self.a))); } //... if self.c != 0.0 { let withSpace = result.any(); // Not sure if this works in Rust result.push(format_sign(self.a, withSpace)) result.push(format_constant(self.c)); } So format_sign would print a + or - and with or without the space and then format_constant will just print the number and format_coefficient can return "" if the number is exactly one. Sorry, I don't have a rust compiler at hand.
{ "domain": "codereview.stackexchange", "id": 43899, "lm_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, reinventing-the-wheel, rust", "url": null }
javascript, beginner, interview-questions, random, playing-cards Title: Pick two random cards from a standard deck Question: I wrote this code as a refactor of code I saw on Programiz. I thought about this refactor before going to bed and implemented it successfully in code. // Make an array of suits const suits = "S D C H".split(' ') // Make an array of values const values = "A 2 3 4 5 6 7 9 10 J Q K".split(' ') // Create a function to pick two random cards function pickTwoRandomCards(suit, value) { randomSuitOne = suit[Math.floor(Math.random() * suit.length)] randomValueOne = value[Math.floor(Math.random() * value.length)] randomSuitTwo = suit[Math.floor(Math.random() * suit.length)] randomValueTwo = value[Math.floor(Math.random() * value.length)] // Check to see if random cards happen to match // if they match run the function recursively because you can't pick the same // card from a deck twice if (randomValueOne + randomSuitOne == randomValueTwo + randomSuitTwo) { pickTwoRandomCards(suit, value); } else { return `${randomValueOne}${randomSuitOne} ${randomValueTwo}${randomSuitTwo}` } } const pickTwo = pickTwoRandomCards(suits, values) console.log(pickTwo) Answer: There is a bug A return statement is missing when making the recursive call when the same card is picked twice. Don't use recursion to repeat an operation To repeat an operation, use a loop, for example: while (true) { // ... if (randomValueOne + randomSuitOne != randomValueTwo + randomSuitTwo) { return `${randomValueOne}${randomSuitOne} ${randomValueTwo}${randomSuitTwo}` } } Picking two random cards without duplicates and without an infinite loop There is an interesting idea in a famous answer, I quote the relevant part verbatim: initialize set S to empty for J := N-M + 1 to N do T := RandInt(1, J) if T is not in S then insert T in S else insert J in S
{ "domain": "codereview.stackexchange", "id": 43900, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, beginner, interview-questions, random, playing-cards", "url": null }
javascript, beginner, interview-questions, random, playing-cards assumes that RandInt(1, J) returns values inclusive of J. To understand the above algorithm, you need to realize that you choose a random value from a range that is smaller than the full range, and then after each value, you extend that to include one more. In the event of a collision, you can safely insert the max because it was never possible to include it before. If we can use a single random number to decide both the suit and the value, then we can use the above technique to generate two distinct random numbers from the possible choices, without looping. Putting that into code: function pickTwoRandomCards(suits, values) { const max = suits.length * values.length const random1 = Math.floor(Math.random() * (max - 1)) const random2maybe = Math.floor(Math.random() * max) const random2 = random2maybe != random1 ? random2maybe : max - 1 const randomSuitOne = suits[Math.floor(random1 / values.length)] const randomValueOne = values[random1 % values.length] const randomSuitTwo = suits[Math.floor(random2 / values.length)] const randomValueTwo = values[random2 % values.length] return `${randomValueOne}${randomSuitOne} ${randomValueTwo}${randomSuitTwo}` } Fix variable declarations randomSuitOne and the other variables inside the function are missing the const keyword. Consider usability Returning two random cards separated by a space doesn't seem very useful. It would be good to consider how the returned values are expected to be used by callers. Confusing function parameters suit and value It's confusing that these parameters are arrays, but their names are singular.
{ "domain": "codereview.stackexchange", "id": 43900, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, beginner, interview-questions, random, playing-cards", "url": null }
python Title: Automate the Boring Stuff Chapter 9 - Mad Libs Exercise Question: The project outline: Create a Mad Libs program that reads in text files and lets the user add their own text anywhere the word ADJECTIVE, NOUN, ADVERB, or VERB appears in the text file. For example, a text file may look like this: The ADJECTIVE panda walked to the NOUN and then VERB. A nearby NOUN was unaffected by these events. The program would find these occurrences and prompt the user to replace them. Enter an adjective: silly Enter a noun: chandelier Enter a verb: screamed Enter a noun: pickup truck The following text file would then be created: The silly panda walked to the chandelier and then screamed. A nearby pickup truck was unaffected by these events. The results should be printed to the screen and saved to a new text file. My solution: import pyinputplus as pyip import re text_file = open("mad_libs_text.txt", "r") text = text_file.read() reg_obj = re.compile(r"ADJECTIVE|NOUN|VERB") mo = reg_obj.findall(text) new_text = text for i in mo: art = "a" if i == "ADJECTIVE": art = "an" user_inp = pyip.inputStr(f"Enter {art} {i.lower()}\n") new_text = re.sub(i, user_inp, new_text, count=1) print(new_text) new_text_file = open("mad_libs_new.txt", "w") new_text_file.write(new_text) text_file.close() new_text_file.close() Thanks in advance for the critique. Answer: Use descriptive names It's good to use descriptive names for variables (and everything) to help readers understand the elements of the code and how they might interact. Names like reg_obj, mo, i, art don't describe what's stored in them, so readers have to understand how they are used to deduce their purpose. With descriptive names, the code is a lot easier to understand: re_word_types = re.compile(r"ADJECTIVE|NOUN|VERB") word_types = re_word_types.findall(text) new_text = text
{ "domain": "codereview.stackexchange", "id": 43901, "lm_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 for word_type in word_types: article = "a" if word_type == "ADJECTIVE": article = "an" word = pyip.inputStr(f"Enter {article} {word_type.lower()}\n") new_text = re.sub(word_type, word, new_text, count=1) Use more strict patterns I suspect that you want to replace the word types when they are not part of other words. For example you probably don't want to replace the NOUN in PRONOUNCE, or VERB in VERBAL. Such unintended replacements can be prevented using stricter patterns, for example: re_word_types = re.compile(r"\b(ADJECTIVE|NOUN|VERB)\b") By enclosing the terms within \b...\b, we ensure that they will only be matched at proper word boundaries. Use context manager for file operations Instead of: text_file = open("mad_libs_text.txt", "r") text = text_file.read() text_file.close() The recommended idiom: with open("mad_libs_text.txt", "r") as text_file: text = text_file.read() And then no need to call .close() explicitly, the context manager will do it automatically when leaving the scope of the with. Replace words all at once The posted code repeatedly replaces one term at a time in the text. With 4 terms in the text, the text is re-processed 4 times. Another alternative is to replace all the patterns in a single pass, by using another form of re.sub, with a callable. However, to be able to replace all the terms at once, the words needed in the replacement must all be collected up front. So this is a tradeoff of the two techniques. def replacer(match): word_type = match.group() word = words[word_type].popleft() return word words = defaultdict(deque) for word_type in word_types: article = "a" if word_type == "ADJECTIVE": article = "an" word = pyip.inputStr(f"Enter {article} {word_type.lower()}\n") words[word_type].append(word) new_text = re_word_types.sub(replacer, text)
{ "domain": "codereview.stackexchange", "id": 43901, "lm_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, number-guessing-game Title: Number guessing game with difficulties and highscore Question: I'm sure you've heard this before, I'm a beginner, however I'm trying to break out of the basics and use more intermediate things like functions and such but I'm having a hard time understanding how to properly integrate them into my code. I've created a number guessing game that uses 2 functions, it has difficulty settings, and even a high score. I was hoping somebody could look over it and help me understand how this could've been written better. (The program works entirely, however will throw an error if you try to input incorrect data). import random # Default highscores for difficulties easyScore = 9999999999 mediumScore = 9999999999 hardScore = 9999999999 attempts = [0] isPlaying = True # Setting the global variable dif to 1-3 to determine difficulty later on def difficultysetting(input): global dif if input.lower() == "e": dif = 1 elif input.lower() == "m": dif = 2 elif input.lower() == "h": dif = 3 # Returns the high score of whatever difficulty the user is playing on def highscore(): if dif == 1: return easyScore elif dif == 2: return mediumScore elif dif == 3: return hardScore while isPlaying: print("Difficulties (E)asy, (M)edium, (H)ard") difficulty = difficultysetting(input("Choose a difficulty: ")) guess = -1 # Checking which difficulty user is playing on and generating a random number based on that if dif == 1: number = int(random.randint(1, 100)) elif dif == 2: number = int(random.randint(1, 1000)) elif dif == 3: number = int(random.randint(1, 10000))
{ "domain": "codereview.stackexchange", "id": 43902, "lm_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, number-guessing-game", "url": null }
python, number-guessing-game # Prompting user which numbers to guess between per difficulty while guess != number: if dif == 1: guess = int(input("Pick a number between 1-100: ")) elif dif == 2: guess = int(input("Pick a number between 1-1000: ")) elif dif == 3: guess = int(input("Pick a number between 1-10000: ")) # Lets user know if they've guessed to high or too low if guess < number: print("Higher") attempts.append(guess) elif guess > number: print("Lower") attempts.append(guess) else: print("That's Correct!") print("Guesses: ", len(attempts)) # Checking if new highscore is lower than old highscore and updating the variable if so if dif == 1 and len(attempts) < easyScore: easyScore = len(attempts) elif dif == 2 and len(attempts) < mediumScore: mediumScore = len(attempts) elif dif == 3 and len(attempts) < hardScore: hardScore = len(attempts) # reseting list attempts.clear() attempts.append(0) # Asking user if they'd like to play again and ending while loop if no print("Highscore: ", str(highscore())) playAgain = input("Do you want to play again? (Y/N): ") if playAgain.lower() == "n": isPlaying = False Answer: PEP-8 First off, some minor things your variable names aren't compliant with PEP-8, which recommends using: UPPER_SNAKE for top-level variables PascalCase for classes lower_snake for ordinary functions and variables It also has recommendations on indent levels, etc. I suggest you look into getting a linter such as flake8 or pylint and run your code through them to standardise it against others' codes. You also do something called "shadowing" of functions. Which means using the name of something declared elsewhere and giving it a new meaning. Here: def difficultysetting(input):
{ "domain": "codereview.stackexchange", "id": 43902, "lm_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, number-guessing-game", "url": null }
python, number-guessing-game you use the name input which is an internal Python function (and indeed one you've used), but override it with the variable passed into the function. This means that if we wanted to use input in the function, we couldn't. In this case it's not catastrophic, but doing it is bad practice and confusing. In this case we might want to change it to choice, for example. Now you should note that there exists a function called choice in the random library. However, because we're importing it with its name, in our local namespace, it is called random.choice, so we aren't shadowing it. This is also why importing * can be a bad idea, we might use names which conflict with some functions defined in libraries we've imported. Handle user input smartly At the moment, you are putting a lot of trust in the user to enter sensible values to each of your inputs. Realistically, we want to be prepared to handle whatever the user throws at us. Consider your guess: guess = int(input("Pick a number between 1-100: ")) What happens if a user provides "a" as their guess? At the moment you crash out with: ValueError: invalid literal for int() with base 10: 'a' We can be smarter than this. Consider: while True: guess = input("Pick a number between 1-100: ") try: guess = int(guess) except ValueError: print(f"Invalid guess ({guess}), must be valid number") continue # Go back to start of loop and get a new guess if 1 <= guess <= 100: break else: # Go back to start of loop and get a new guess print(f"Invalid guess ({guess}), must be between 1 and 100")
{ "domain": "codereview.stackexchange", "id": 43902, "lm_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, number-guessing-game", "url": null }
python, number-guessing-game This can even be stuck in a function so it doesn't clutter up our main code. Functions (and how to use them) Functions in Python (and most languages) take arguments and return some answers. The idea being that they can be used in multiple different places and be useful. A common structure of a function looks like: def function_name(argument): """ Describe function, what it does Describe function arguments Describe what function returns """ do stuff to argument(s) return result N.B. This is not always the case, there are some cases where you might have no arguments or want a function which doesn't return anything, e.g. to change the input argument or change global settings. So, taking your difficulty selection as an example: # It is sometimes recommended to name functions as verbs where appropriate def get_difficulty(choice: str) -> int: # Type-hints give information to a user about how your code is meant to be used """ Returns difficulty to 1-3 depending on user choice, otherwise raises a ValueError :param choice: string containing user-entered choice :returns: 1,2 or 3 representing difficulty :rtype: int """ choice = choice.lower() # Changing the argument here doesn't change the value outside the function as `lower` returns a new string if choice == "e": difficulty = 1 elif choice == "m": difficulty = 2 elif choice == "h": difficulty = 3 else: # Consider what happens if a user enters e.g. "really hard" raise ValueError(f"Invalid difficulty, must be one of e,m or h. Received: {choice}") return difficulty
{ "domain": "codereview.stackexchange", "id": 43902, "lm_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, number-guessing-game", "url": null }
python, number-guessing-game Using the right variable for the job You have a lot of if blocks which all just check against difficulty, e.g. to get which score, to get which max number, how many attempts, etc. This might be best done using arrays/tuples and we simply index into the array with difficulty. N.B.: This does mean the difficulties become 0, 1, 2 as arrays are indexed from 0 I.e. SCORES = [9999999999] * 3 DIFFICULTY_RANGES = [100, 1000, 10000] ... while isPlaying: ... # You could set a variable to store DIFFICULTY_RANGES[difficulty] when you get difficulty, so you don't have to use the full name every time number = random.randint(1, DIFFICULTY_RANGES[difficulty]) while guess != number: guess = int(input(f"Pick a number between 1-{DIFFICULTY_RANGES[difficulty]}: ")) ... if len(attempts) < SCORES[difficulty]: SCORES[difficulty] = len(attempts) Also, your attempts is a list of prior guesses, but as it is, you don't use it as a list, you just check against its length. This means that it could probably just be an integer which counts up each time. Summary Putting all this together along with a few other minor changes we end up with: """ Play number guessing game """ import random # Max number for difficulty DIFFICULTY_RANGES = [100, 1000, 10000] def get_difficulty() -> int: """ Returns difficulty to 0-2 depending on user choice :returns: 0, 1 or 2 representing difficulty :rtype: int """ difficulty = -1 while difficulty < 0: choice = input("Choose a difficulty, (E)asy, (M)edium, (H)ard: ").lower() if choice == "e": difficulty = 0 elif choice == "m": difficulty = 1 elif choice == "h": difficulty = 2 else: print(f"Invalid difficulty choice ({choice}) must be one of e, m or h") return difficulty def get_guess(max_number: int) -> int: """ Get valid user guess, i.e. is a number and in range
{ "domain": "codereview.stackexchange", "id": 43902, "lm_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, number-guessing-game", "url": null }
python, number-guessing-game def get_guess(max_number: int) -> int: """ Get valid user guess, i.e. is a number and in range :returns: User guess :rtype: int """ while True: guess = input(f"Pick a number between 1-{max_number}: ") try: guess = int(guess) except ValueError: print(f"Invalid guess ({guess}), must be valid number") continue if 1 <= guess <= max_number: return guess print(f"Invalid guess ({guess}), must be between 1 and {max_number}") def play_game(max_number: int) -> int: """ Play a round of the guessing game :param max_number: Maximum value in range to guess :returns: Number of attempts :rtype: int """ number = random.randint(1, max_number) guess = -1 attempts = 0 # Prompting user which numbers to guess between per difficulty while guess != number: guess = get_guess(max_number) # Lets user know if they've guessed to high or too low if guess < number: print("Higher") attempts += 1 elif guess > number: print("Lower") attempts += 1 else: print("That's Correct!") print("Guesses: ", attempts) return attempts def main(): # Default highscores for difficulties scores = [9999999999] * 3 is_playing = True while is_playing: difficulty = get_difficulty() max_number = DIFFICULTY_RANGES[difficulty] attempts = play_game(max_number) # Checking if new highscore is lower than old highscore and updating the variable if so if attempts < scores[difficulty]: print("New high score!") scores[difficulty] = attempts print(f"Current Highscore: {scores[difficulty]}") # Asking user if they'd like to play again and ending while loop if no while True: play_again = input("Do you want to play again? (Y/N): ").lower()
{ "domain": "codereview.stackexchange", "id": 43902, "lm_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, number-guessing-game", "url": null }
python, number-guessing-game if play_again == "n": is_playing = False break if play_again == "y": break print(f"Invalid option ({play_again}), must be Y/N") if __name__ == '__main__': # Main guard means that code will only run if called as `python guessing_game.py` and not when imported as a package main() There's certainly some more room for expansion, e.g. saving and loading high scores from a file, if you want some extra challenge.
{ "domain": "codereview.stackexchange", "id": 43902, "lm_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, number-guessing-game", "url": null }
python Title: Automate the Boring Stuff Chapter 9 - Regex Search Question: The project outline: Write a program that opens all .txt files in a folder and searches for any line that matches a user-supplied regular expression. The results should be printed to the screen. My solution: import os, re from pathlib import Path while True: user_path = input("Enter a path to search: ") if user_path == "": print("Please enter a valid path.") elif Path(user_path).exists() != True: print("This path does not exist.") else: while True: all_files = os.listdir(user_path) matches = [] lines = [] user_input = input("What do you want to find? (Enter nothing to search another path)\n") regex_object = re.compile(user_input) if user_input == "": break else: for filename in all_files: if filename.endswith(".txt") != True: continue text_file = open(Path(user_path) / filename) for line in text_file.readlines(): match_object = regex_object.findall(line) for match in match_object: matches.append(match) lines.append(line) text_file.close() if matches == []: print("No matches found") else: print(matches) print(lines) Thanks in advance for the critique. Answer: Use stronger input validation The code checks: if Path(user_path).exists() != True: And later it does: all_files = os.listdir(user_path) Also later it creates another Path from the same path string: open(Path(user_path) / filename) It would be better to check that the input is a directory, and create a Path object once and reuse it. So the above uses become: basedir = Path(user_path) # ...
{ "domain": "codereview.stackexchange", "id": 43903, "lm_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 if not basedir.is_dir(): # ... all_files = os.listdir(basedir) # ... open(basedir / filename) Wrap code in if __name__ == '__main__': guard The recommended way to organize Python code is put the main logic in functions, and call the functions from under a if __name__ == '__main__': guard, something like this: def main(): # the main work, probably calling other functions # ... if __name__ == '__main__': main() Use functions It's good to organize code to functions, where each function does one logical thing. For example the innermost part of the code could be in a function: def find_matches_and_lines(basedir, re_pattern): matches = [] lines = [] for filename in os.listdir(basedir): if not filename.endswith(".txt"): continue with open(basedir / filename) as text_file: for line in text_file.readlines(): for match in re_pattern.findall(line): matches.append(match) lines.append(line) return matches, lines
{ "domain": "codereview.stackexchange", "id": 43903, "lm_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 return matches, lines The benefit is that a smaller piece code like this is easier to understand as a single logical unit, without having to worry about all the complexity in the rest of the program outside of this function. Zip the results The program builds two parallel lists: matches and the matched lines. I don't know how you plan to use it. I think it's very likely that when looking at a match, you might want to look at the corresponding line. With two parallel lists, you have to use indexes. Which is ok, but if you only plan to use the values in pairs, then it would make sense zip the lists, which would open up the possibility to use a generator pattern, and a bit simpler code: def find_matches_and_lines(basedir, re_pattern): for filename in os.listdir(basedir): if not filename.endswith(".txt"): continue with open(basedir / filename) as text_file: for line in text_file.readlines(): for match in re_pattern.findall(line): yield match, line Simplify conditionals on empty things PEP8 recommends to use the fact that empty sequences are false. That is, instead of these: if user_path == "": if matches == []: Write: if not user_path: if not matches: And instead of these: elif Path(user_path).exists() != True: if filename.endswith(".txt") != True: Write: elif not Path(user_path).exists(): if not filename.endswith(".txt"): Use context manager for file operations Instead of: text_file = open(path, "r") text = text_file.read() text_file.close() The recommended idiom: with open(path, "r") as text_file: text = text_file.read() And then no need to call .close() explicitly, the context manager will do it automatically when leaving the scope of the with.
{ "domain": "codereview.stackexchange", "id": 43903, "lm_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 }
performance, vba, ms-access Title: VBA code which exports data from Access to Excel and then loops through the Excel file Question: I have a couple of VBA loops that work in the blink of eye when I execute them through Excel, but doing this as part of an Access VBA application takes like 15 minutes. The loops run through each row and check to see if multiple conditions are met, and if they are they change the value of one cell in the row in question. This is the database code pertaining to the Excel portion: With MyExcel .Workbooks.Open ReportName Set WB = GetObject(ReportName) WB.DisplayAlerts = False WB.Sheets(2).Select WB.Sheets(3).Select WB.Sheets(3).Columns("E:F").Delete WB.Sheets(3).Columns("G:G").Delete WB.Sheets(3).Columns("AF:AF").Delete WB.Sheets(3).Columns("A:AE").NumberFormat = "@" LastRow = WB.Sheets(3).Range("A2").End(xlDown).Row For i = 2 To LastRow If WB.Sheets(3).Cells(i, 6).Value = 2 Then WB.Sheets(3).Rows(i).Copy Destination:=WB.Sheets(3).Rows(WB.Sheets(3).Range("A2").End(xlDown).Row + 1) ElseIf WB.Sheets(3).Cells(i, 6).Value = 4 Then WB.Sheets(3).Rows(i).Copy Destination:=WB.Sheets(3).Rows(WB.Sheets(3).Range("A2").End(xlDown).Row + 1) WB.Sheets(3).Rows(i).Copy Destination:=WB.Sheets(3).Rows(WB.Sheets(3).Range("A2").End(xlDown).Row + 1) WB.Sheets(3).Rows(i).Copy Destination:=WB.Sheets(3).Rows(WB.Sheets(3).Range("A2").End(xlDown).Row + 1) End If Next i With WB.Sheets(3).Range("A1:AE" & LastRow) .WrapText = False .Orientation = 0 .AddIndent = False .IndentLevel = 0 .ShrinkToFit = False .ReadingOrder = xlContext .MergeCells = False End With
{ "domain": "codereview.stackexchange", "id": 43904, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "performance, vba, ms-access", "url": null }
performance, vba, ms-access WB.Sheets(3).Range("A1").AutoFilter LastRow = WB.Sheets(3).Range("A2").End(xlDown).Row WB.Sheets(3).ListObjects.Add(xlSrcRange, WB.Sheets(3).Range("$A$1:$AE$" & LastRow), , xlYes).Name = "tblAccess" WB.Sheets(3).ListObjects("tblAccess").TableStyle = "TableStyleLight8" WB.Sheets(3).ListObjects("tblAccess").Sort.SortFields.Clear WB.Sheets(3).ListObjects("tblAccess").Sort.SortFields. _ Add Key:=WB.Sheets(3).Range("tblAccess[NDC NUMBER]"), SortOn:=xlSortOnValues, Order:= _ xlAscending, DataOption:=xlSortNormal WB.Sheets(3).ListObjects("tblAccess").Sort.SortFields. _ Add Key:=WB.Sheets(3).Range("tblAccess[GROUP_ID]"), SortOn:=xlSortOnValues, Order:= _ xlAscending, DataOption:=xlSortNormal With WB.Sheets(3).ListObjects("tblAccess").Sort .Header = xlYes .MatchCase = False .Orientation = xlTopToBottom .SortMethod = xlPinYin .Apply End With
{ "domain": "codereview.stackexchange", "id": 43904, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "performance, vba, ms-access", "url": null }
performance, vba, ms-access For i = 2 To LastRow If WB.Sheets(3).Cells(i, 2) = WB.Sheets(3).Cells(i + 1, 2) And WB.Sheets(3).Cells(i, 6) = 2 And WB.Sheets(3).Cells(i, 7) = "New QL" Then WB.Sheets(3).Cells(i, 7) = "QLL OUT OF RANGE" ElseIf WB.Sheets(3).Cells(i, 2) <> WB.Sheets(3).Cells(i + 1, 2) And WB.Sheets(3).Cells(i, 6) = 2 And WB.Sheets(3).Cells(i, 7) = "New QL" Then WB.Sheets(3).Cells(i, 7) = "QLL IN RANGE" ElseIf WB.Sheets(3).Cells(i, 2) = WB.Sheets(3).Cells(i + 1, 2) And WB.Sheets(3).Cells(i, 6) = 2 And WB.Sheets(3).Cells(i, 7) = "New PA" Then WB.Sheets(3).Cells(i, 7) = "New PA-1" ElseIf WB.Sheets(3).Cells(i, 2) <> WB.Sheets(3).Cells(i + 1, 2) And WB.Sheets(3).Cells(i, 6) = 2 And WB.Sheets(3).Cells(i, 7) = "New PA" Then WB.Sheets(3).Cells(i, 7) = "New PA-2" ElseIf WB.Sheets(3).Cells(i, 2) = WB.Sheets(3).Cells(i + 1, 2) And WB.Sheets(3).Cells(i, 6) = 2 And WB.Sheets(3).Cells(i, 7) = "Uptiered/Modify QL" Then WB.Sheets(3).Cells(i, 7) = "Uptiered/Modify QL-1" ElseIf WB.Sheets(3).Cells(i, 2) <> WB.Sheets(3).Cells(i + 1, 2) And WB.Sheets(3).Cells(i, 6) = 2 And WB.Sheets(3).Cells(i, 7) = "Uptiered/Modify QL" Then WB.Sheets(3).Cells(i, 7) = "Uptiered/Modify QL-2" ElseIf WB.Sheets(3).Cells(i, 2) = WB.Sheets(3).Cells(i + 1, 2) And WB.Sheets(3).Cells(i, 6) = 2 And WB.Sheets(3).Cells(i, 7) = "Modify QL" Then WB.Sheets(3).Cells(i, 7) = "Modify QL-1" ElseIf WB.Sheets(3).Cells(i, 2) <> WB.Sheets(3).Cells(i + 1, 2) And WB.Sheets(3).Cells(i, 6) = 2 And WB.Sheets(3).Cells(i, 7) = "Modify QL" Then WB.Sheets(3).Cells(i, 7) = "Modify QL-2" ElseIf WB.Sheets(3).Cells(i, 2) = WB.Sheets(3).Cells(i + 1, 2) And WB.Sheets(3).Cells(i, 6) = 4 And WB.Sheets(3).Cells(i, 7) = "Modify QL" _ And WB.Sheets(3).Cells(i, 2) = WB.Sheets(3).Cells(i + 2, 2) And WB.Sheets(3).Cells(i, 2) = WB.Sheets(3).Cells(i + 3, 2) Then
{ "domain": "codereview.stackexchange", "id": 43904, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "performance, vba, ms-access", "url": null }
performance, vba, ms-access WB.Sheets(3).Cells(i, 7) = "Modify QL-1" ElseIf WB.Sheets(3).Cells(i, 2) = WB.Sheets(3).Cells(i + 1, 2) And WB.Sheets(3).Cells(i, 6) = 4 And WB.Sheets(3).Cells(i, 7) = "Modify QL" _ And WB.Sheets(3).Cells(i, 2) = WB.Sheets(3).Cells(i + 2, 2) Then WB.Sheets(3).Cells(i, 7) = "Modify QL-2" ElseIf WB.Sheets(3).Cells(i, 2) = WB.Sheets(3).Cells(i + 1, 2) And WB.Sheets(3).Cells(i, 6) = 4 And WB.Sheets(3).Cells(i, 7) = "Modify QL" Then WB.Sheets(3).Cells(i, 7) = "Modify QL-3" ElseIf WB.Sheets(3).Cells(i, 2) = WB.Sheets(3).Cells(i - 1, 2) And WB.Sheets(3).Cells(i, 6) = 4 And WB.Sheets(3).Cells(i, 7) = "Modify QL" Then WB.Sheets(3).Cells(i, 7) = "Modify QL-4" ElseIf WB.Sheets(3).Cells(i, 2) = WB.Sheets(3).Cells(i + 1, 2) And WB.Sheets(3).Cells(i, 6) = 4 And WB.Sheets(3).Cells(i, 7) = "New QL" _ And WB.Sheets(3).Cells(i, 2) = WB.Sheets(3).Cells(i + 2, 2) And WB.Sheets(3).Cells(i, 2) = WB.Sheets(3).Cells(i + 3, 2) Then WB.Sheets(3).Cells(i, 7) = "QLL OUT OF RANGE PA ADDED" ElseIf WB.Sheets(3).Cells(i, 2) = WB.Sheets(3).Cells(i + 1, 2) And WB.Sheets(3).Cells(i, 6) = 4 And WB.Sheets(3).Cells(i, 7) = "New QL" _ And WB.Sheets(3).Cells(i, 2) = WB.Sheets(3).Cells(i + 2, 2) Then WB.Sheets(3).Cells(i, 7) = "QLL OUT OF RANGE NO PA" ElseIf WB.Sheets(3).Cells(i, 2) = WB.Sheets(3).Cells(i + 1, 2) And WB.Sheets(3).Cells(i, 6) = 4 And WB.Sheets(3).Cells(i, 7) = "New QL" Then WB.Sheets(3).Cells(i, 7) = "QLL IN RANGE PA ADDED" ElseIf WB.Sheets(3).Cells(i, 2) = WB.Sheets(3).Cells(i - 1, 2) And WB.Sheets(3).Cells(i, 6) = 4 And WB.Sheets(3).Cells(i, 7) = "New QL" Then WB.Sheets(3).Cells(i, 7) = "QLL IN RANGE NO PA" Else WB.Sheets(3).Cells(i, 7) = WB.Sheets(3).Cells(i, 7) End If Next i
{ "domain": "codereview.stackexchange", "id": 43904, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "performance, vba, ms-access", "url": null }
performance, vba, ms-access WB.Sheets("POS_Claims").Activate WB.Sheets("POS_Claims").ListObjects("tblMain").Resize WB.Sheets("POS_Claims").Range("$A$1:$MI$" & LastRow) WB.Sheets("POS_Claims").Range("C2") = "=tblAccess[@[BIN]]" WB.Sheets("POS_Claims").Range("D2") = "=tblAccess[@[PCN]]" WB.Sheets("POS_Claims").Range("Y2") = "=tblAccess[@[GROUP_ID]]" WB.Sheets("POS_Claims").Range("AT2") = "=tblAccess[@[NDC NUMBER]]" WB.Sheets("POS_Claims").Range("FT2") = "=tblAccess[@[Testing Scenarios]]" WB.Sheets("POS_Claims").Range("HI2") = "=tblAccess[@[PAUTH_IND]]" WB.Sheets("POS_Claims").Range("HJ2") = "=tblAccess[@[PAUTH_Start_Date]]" WB.Sheets("POS_Claims").Range("HK2") = "=tblAccess[@[PAUTH_End_Date]]" WB.Sheets("POS_Claims").Range("HN2") = "=tblAccess[@[PAUTH_SPEC_OV]]" WB.Sheets("POS_Claims").Range("HO2") = "=tblAccess[@[PAUTH_SPEC_COPAY_OV]]" WB.Sheets("POS_Claims").Range("HS2") = "=tblAccess[@[PAUTH_MEDB_OV]]" WB.Sheets("POS_Claims").Range("HU2") = "=tblAccess[@[PAUTH_CLAIM_SUB]]" WB.Sheets("POS_Claims").Range("HV2") = "=tblAccess[@[PAUTH_CAP_OV]]" WB.Sheets("POS_Claims").Range("HY2") = "=tblAccess[@[PAUTH_AUTH_TYPE]]" WB.Sheets("POS_Claims").Range("IC2") = "=tblAccess[@[PAUTH_DAW]]" WB.Sheets("POS_Claims").Range("ID2") = "=tblAccess[@[PAUTH_MAX_DOSE]]" WB.Sheets("POS_Claims").Range("IF2") = "=tblAccess[@[PAUTH_DENY_COV]]" WB.Sheets("POS_Claims").Range("IG2") = "=tblAccess[@[PAUTH_PRICE_POINT_IND]]" WB.Sheets("POS_Claims").Range("II2") = "=tblAccess[@[PAUTH_Brand_COPAY_OV]]" WB.Sheets("POS_Claims").Range("IJ2") = "=tblAccess[@[PAUTH_RTS]]" WB.Sheets("POS_Claims").Range("JF2") = "=tblAccess[@[MBA_Indicator]]"
{ "domain": "codereview.stackexchange", "id": 43904, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "performance, vba, ms-access", "url": null }
performance, vba, ms-access WB.Sheets("POS_Claims").Range("A1:MI" & LastRow).Copy WB.Sheets("POS_Claims").Range("A1:MI" & LastRow).PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _ :=False, Transpose:=False WB.Application.CutCopyMode = False WB.Sheets("POS_Claims").ListObjects(1).Unlist WB.Sheets("POS_Claims").Range("A1:MI" & LastRow).Replace What:="0", Replacement:="", LookAt:=xlPart, _ SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _ ReplaceFormat:=False WB.Sheets("POS_Claims").Range("A2").Select WB.Close SaveChanges:=True End With Answer: Two options: Move your Excel code back to Excel. Make this code run on open. Open the workbook from Access and the code will run. Update the code to save & close the workbook when it's done. Alternatively: Move your Excel code back to Excel in a "standard" module. Call the Excel method from Access code: Set Rpt = XLobj.Workbooks.Open(ExcelFileName) Rpt.Application.Run ExcelMacroName 'you can provide parameters to the function here if needed/desired Rpt.Close False This will open Excel, run the code within Excel, then close the file
{ "domain": "codereview.stackexchange", "id": 43904, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "performance, vba, ms-access", "url": null }
beginner, c, formatting, io Title: K&R Exercise 5-11. Modify the "detab" - to accept a list of tab stops as arguments Question: So far I have reached chapter 5 of the K&R Book, Edition 2 from which I have been learning C. I spent a few days thinking of a solution to this program. I wrote two or three versions of the same program, And the truth is that I couldn't bring myself to think of a better solution for this exercise: Exercise 5-11. Modify the program "entab" and "detab" (written as exercises in Chapter 1.) to accept a list of tab stops as arguments. Use the default tab settings if there are no arguments. And well, I assumed that this was the best one I had written. Here is the solution for the exercise (Chapter 5, Ex-5.11): I would like to know how to improve it to take it "further?" or if I'm taking the right approach: /*- * detab.c - expand tabs to equivalent spaces * * The-C-Programming-Language Book 2nd Edition. * * Created by jr.chavez on 9/22/22. */ #include <stdio.h> #include <stdlib.h> #define DTAB_STOP 8 /* DEFAULT TAB STOP */ #define MAX_TAB_STOP 100 enum escapes { BACKSPACE = '\b', TAB = '\t', NEWLINE = '\n', RETURN = '\r' }; static int getstops(char *cp) { int n; n = 0; while (*cp) { if (*cp < '0' || *cp > '9') return -1; if (*cp >= '0' && *cp <= '9') n = n * 10 + *cp - '0'; cp++; } return n; } int main(int argc, char *argv[]) { int ch; int n, col; /* n, columns */ int nstops; int tabstops[MAX_TAB_STOP]; nstops = argc - 1; if (nstops > MAX_TAB_STOP) { fprintf(stderr, "error: too many args.\n"); exit(EXIT_FAILURE); } for (int indx = 1; indx < argc; indx++) { tabstops[indx - 1] = getstops(argv[indx]) - 1; }
{ "domain": "codereview.stackexchange", "id": 43905, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "beginner, c, formatting, io", "url": null }
beginner, c, formatting, io col = 0; while ((ch = getchar()) != EOF) { switch (ch) { case TAB: if (nstops == 0) { while (col < DTAB_STOP) { printf("\u25A0"); col++; } continue; } for (n = 0; n < nstops; n++) if (col < tabstops[n]) break; if (n == nstops) { printf("\u25A0"); col++; continue; } while (col < tabstops[n]) { printf("\u25A0"); col++; } break; case BACKSPACE: if (col > 0) --col; putchar(BACKSPACE); break; case RETURN: case NEWLINE: putchar(ch); col = 0; continue; default: putchar(ch); break; } } if (ferror(stdin)) { perror("stdin"); return EXIT_FAILURE; } return 0; } I did some "tests": cat test.txt | ./bin/detab 4 9 29 Input File: # # # # # # # # # # # # # #
{ "domain": "codereview.stackexchange", "id": 43905, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "beginner, c, formatting, io", "url": null }
beginner, c, formatting, io Output: #■■■■■■■■■■■■■■■■■■■■■■■■■■■■#■■# #■■■■■■■■■■■■■■■■■■■■■■■■■■■■■#■■# #■■■■■■■■■■■■■■■■■■■■■■■■■■■■#■#■■■#■# #■■■#■■■■■■■■■■■■■■■■■■■■■■■■■■# These are the results I get with the expand command: (Of course, I never intended the results to be accurate in the first place - but for now I'd just like to improve it.) cat test.txt | expand -t 4,9,29 output: # # # # # # # # # # # # # # Note: I've only written the detab program, for now. I had focused on doing something "similar" to what the "expand" command does. (I don't get the same output, but something similar). I also didn't add flags or read from a file. (I still haven't reached Chapter 7.). Answer: how to improve it to take it "further?" User input is evil. getstops(char *cp), which should be getstops(const char *cp) does not detect invalid conversions. Better to use strtol() and test for acceptable range. Error out on bad input. Pedantic: Hacker hardening getstops(argv[indx]) - 1; invokes undefined behavior when getstops() returns INT_MIN. Obviously this is not an expected return value, yet better to test valid range of user values before using them in calculations. Black square Rather than printf("\u25A0"); consider #define BLACK_SQUARE "\u25A0", fputs(BLACK_SQUARE, stdout); or the like. More informative message // fprintf(stderr, "error: too many args.\n"); fprintf(stderr, "error: More than %d args.\n", MAX_TAB_STOP + 1); // or fprintf(stderr, "error: More than %d tab stops.\n", MAX_TAB_STOP); Good error detection Nice: if (ferror(stdin)) { Be generous I could see automated tools making many tap stops. // #define MAX_TAB_STOP 100 #define MAX_TAB_STOP 4096
{ "domain": "codereview.stackexchange", "id": 43905, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "beginner, c, formatting, io", "url": null }
beginner, c, formatting, io Better code would simple allow argc tab stops. Size int tabstops[] to argc. Useless code if (*cp >= '0' && *cp <= '9') serves no purpose. It is already known cp is in range. #include <stdlib.h> // Parse for positive int static int getstops(const char *cp) { errno = 0; char *endptr; long val = strtol(cp, endptr, 0); if (cp == endptr || *endptr) { fprintf(stderr, "Non-numeric conversion <%s>\n", cp); exit(EXIT_FAILURE); // or alternative handling } if (errno || val < 0 || val > INT_MAX) { fprintf(stderr, "Invalid tab stop %ld>\n", val); exit(EXIT_FAILURE); // or alternative handling } return (int) val; }
{ "domain": "codereview.stackexchange", "id": 43905, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "beginner, c, formatting, io", "url": null }
performance, linux, assembly, x86, bigint Title: Add two huge base-10 numbers Question: This is some assembly code I've written to add two base-10 numbers. The input and output are represented as null-terminated ASCII strings, with digits in big-endian order. I have also provided comments for each line explaining what it does. Is there anywhere I can use SIMD or something which will be faster here? Since the function's called add_whole, it only adds whole numbers, a.k.a. non-negative integers. I also use my own strlen which only modifies rcx. extern strlen section .text global add_whole add_whole: ; Input: ; - char *a -> rdi ; - char *b -> rsi ; - char *res -> rdx
{ "domain": "codereview.stackexchange", "id": 43906, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "performance, linux, assembly, x86, bigint", "url": null }
performance, linux, assembly, x86, bigint ; Registers used: ; - rax ; - rcx ; - r8 ; - r9 ; - r10 ; - r11 ; - r12 ; - r13 ; - r14 push r12 ; Save callee-saved registers used. push r13 ; In this case, push r14 ; r12, r13, and r14. call strlen ; Calculate the length of char *a and store it in rax. push rax ; Save rax, push rdi ; and rdi to make another call to strlen. mov rdi, rsi ; Move char *b into rdi. call strlen ; Calculate the length of char *b, mov r8, rax ; and store it in r8. pop rdi ; Now, rax = strlen(a) pop rax ; r8 = strlen(b) mov r9, r8 ; The next two lines of code cmp rax, r8 ; put std::max(rax, r8) into cmovnc r9, rax ; the r9 register. xor r10b, r10b ; r10b = false := carry_flag xor rcx, rcx ; rcx = 0 := loop_counter .loop_1: lea r13, [rcx + 1] ; r13 = loop_counter + 1 mov r11b, 48 ; r11b = '0', if there are no more digits in the number/s, mov r12b, r11b ; r12b = '0' then these default values will be used. cmp rax, r13 ; Compare strlen(a) with loop_counter + 1. js .after_if_1 ; if (loop_counter < strlen(a)): lea r14, [rdi+rax] ; r11b = a[strlen(a) - loop_counter - 1] sub r14, rcx ; The next two lines dec r14 ; execute that one mov r11b, byte [r14] ; line if statement. .after_if_1: cmp r8, r13 ; Compare strlen(b) with loop_counter + 1. js .after_if_2 ; if (loop_counter < strlen(b)): lea r14, [rsi+r8] ; r12b = b[strlen(b) - loop_counter - 1] sub r14, rcx ; The next two lines dec r14 ; execute that one
{ "domain": "codereview.stackexchange", "id": 43906, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "performance, linux, assembly, x86, bigint", "url": null }
performance, linux, assembly, x86, bigint sub r14, rcx ; The next two lines dec r14 ; execute that one mov r12b, byte [r14] ; line if statement. .after_if_2: mov r13b, r11b ; These next two lines add individual digits add r13b, r12b ; of the numbers. sub r13b, 48 test r10b, r10b ; Check for carry. jz .after_if_3 ; if (carry_flag): xor r10b, r10b ; carry_flag = false inc r13b ; r13b++, add the carry .after_if_3: cmp r13b, 57 ; Compare the current addition result with '9' jle .after_if_4 ; if (r13b > '9'): sub r13b, 10 ; r13b -= 10 mov r10b, 1 ; carry_flag = true .after_if_4: mov byte[rdx+rcx], r13b ; res[loop_counter] = r13b inc rcx ; Increment the loop counter, which now points to the end of res. cmp rcx, r9 ; Keep looping, js .loop_1 ; while (loop_counter < std::max(strlen(a), strlen(b))). test r10b, r10b ; Check for a final carry. jz .after_if_5 ; if (carry_flag): mov byte[rdx+rcx], 49 ; res[loop_counter] = '1' inc r9 ; Increment r9, which stores strlen(res). .after_if_5: xor rcx, rcx ; rcx = 0 := loop_counter mov r11, r9 ; Note that r9 = strlen(res). shr r11, 1 ; r11 = strlen(res) / 2 .loop_2: lea r12, [rdx+r9] ; r12 = &res[strlen(res) - loop_counter - 1] sub r12, rcx dec r12 mov r8b, byte [rdx+rcx] ; r8b = res[loop_counter] mov r10b, byte [r12] ; r10b = *r12 = res[strlen(res) - loop_counter - 1] mov byte [rdx+rcx], r10b ; res[loop_counter] = r10b mov byte [r12], r8b ; res[strlen(res) - loop_counter - 1] = r8b inc rcx cmp rcx, r11 ; Keep looping while (loop_counter < strlen(res) / 2) js .loop_2
{ "domain": "codereview.stackexchange", "id": 43906, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "performance, linux, assembly, x86, bigint", "url": null }
performance, linux, assembly, x86, bigint cmp rcx, r11 ; Keep looping while (loop_counter < strlen(res) / 2) js .loop_2 mov byte [rdx+r9], 0 ; res should be null terminated. pop r14 ; Pop used callee-saved registers. pop r13 pop r12 ret
{ "domain": "codereview.stackexchange", "id": 43906, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "performance, linux, assembly, x86, bigint", "url": null }
performance, linux, assembly, x86, bigint Answer: Following the ABI (you are preserving R12, R13, and R14), the RDX and RSI registers are not amongst the callee-saved registers. Therefore neither might have survived those strlen calls! Optimizations to the existing code xor rcx, rcx ; rcx = 0 := loop_counter Write this as xor ecx, ecx. It'll shave off the REX prefix and will zero the whole RCX register just as well. lea r14, [rdi+rax] sub r14, rcx dec r14 Better avoid that separate dec r14 and add the 'minus 1' that it does to the lea instruction: lea r14, [rdi+rax-1]. lea r13, [rcx + 1] ; r13 = loop_counter + 1 cmp rax, r13 ; cmp strlen(a) with loop_counter + 1 js .after_if_1 ; if (loop_counter < strlen(a)): Why don't you code it the way your C code expresses it? You wouldn't need the detour via the extra R13 register. Since the meaning of '<' for unsigned numbers is 'Below' and you want to by-pass, the conditional to use is 'JumpIfNotBelow': cmp rcx, rax ; cmp loop_counter, strlen(a) jnb .after_if_1 mov r13b, r11b ; These next two lines add individual digits add r13b, r12b ; of the numbers. sub r13b, 48 It is unnecessary to first copy R11B to another register. Just process the sum in the R11B register: add r11b, r12b ; (*) Using R11B instead of R13B sub r11b, 48 test r10b, r10b ; Check for carry. jz .after_if_3 ; if (carry_flag): xor r10b, r10b ; carry_flag = false inc r13b ; r13b++, add the carry .after_if_3: The carry variable in the R10B register is limited to the values of 0 and 1. If it holds 0, you don't want to do anything, and if it is 1, you want to increment the sum and reset the carry variable. Next code is much simpler and does just that: add r11b, r10b ; (*) Using R11B instead of R13B xor r10b, r10b mov byte[rdx+rcx], r13b ; res[loop_counter] = r13b
{ "domain": "codereview.stackexchange", "id": 43906, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "performance, linux, assembly, x86, bigint", "url": null }
performance, linux, assembly, x86, bigint mov byte[rdx+rcx], r13b ; res[loop_counter] = r13b Because you store the result of the addition reversed, you have added a string reversal routine to the code. This is an inefficient approach. The final result will have the same number of digits as the longest of the two inputs, or maybe just one extra digit in case of a final carry. lea rdx, [rdx+1+r9] ; R9 is longest input mov byte [rdx], 0 ; Zero-terminated result Writing an optimized version Don't do the whole calculation in a single loop. First process the positions that both inputs have in common, then process the positions that remain in the longer of the two inputs. You'll have much less conditional branches to execute. Carefully choosing your registers can shave off a lot of bytes via not requiring a REX prefix, being able to use the short accumulator encodings, and not having to preserve callee-saved registers. Input: RDI RSI RDX v v v a, b, res -> 1158791457863133@ 2678139@ .................. Setup: RDI R8 RSI R9 RDX v v v v v a, b, res -> 1158791457863133@ 2678139@ .................@ Loops: LoopB LoopA /-------\/-----\ a -> 1158791457863133@ b -> 2678139@ res -> .1158791460541272@ Output: R8 R9 RDX v v v a, b, res -> 1158791457863133@ 2678139@ .1158791460541272@ ^ RAX ; IN (rdx,rsi,rdi) OUT (rax) MOD (rcx,rdx,rsi,rdi,r8,r9) push rbx ; The only callee-saved register to preserve
{ "domain": "codereview.stackexchange", "id": 43906, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "performance, linux, assembly, x86, bigint", "url": null }
performance, linux, assembly, x86, bigint push rdx ; (1) push rsi ; (2) push rdi ; (3) call strlen ; -> RAX is strlen(a) mov ebx, eax ; For sure less than 4GB mov rdi, [rsp+8] call strlen ; -> RAX is strlen(b) pop rdi ; (3) pop rsi ; (2) pop rdx ; (1) ; At RDI are RBX bytes, at RSI are RAX bytes cmp ebx, eax jae .NoSwap xchg rdi, rsi ; Make (RDI:RBX) refer to the longer input xchg ebx, eax .NoSwap: mov ecx, eax ; RAX is length of the shorter input lea r8, [rdi+rbx] ; R8 points at the terminating zero lea r9, [rsi+rax] ; R9 points at the terminating zero lea rdx, [rdx+1+rbx] ; RBX is length of the longer input xor ebx, ebx ; BL is carry [0,1] mov [rdx], bl ; Zero-terminating the result jecxz .NoLoopA .LoopA: ; Deals with the common positions movzx eax, byte [r8-1] add al, [r9-1] sub al, '0' add al, bl ; Plus carry xor ebx, ebx ; Clear carry cmp al, '9' jbe .CharOK sub al, 10 inc ebx ; Set carry .CharOK: mov [rdx-1], al dec r9 dec r8 dec rdx dec rcx jnz .LoopA .NoLoopA: cmp r8, rdi jna .NoLoopB .LoopB: ; Deals with remainder of the longer input movzx eax, byte [r8-1] add al, bl ; Plus carry xor ebx, ebx ; Clear carry cmp al, '9' jbe .CharOK_ sub al, 10 inc ebx ; Set carry .CharOK_: mov [rdx-1], al dec r8 dec rdx cmp r8, rdi ja .LoopB .NoLoopB: test bl, bl ; Check for a final carry. jz .Done dec rdx mov byte [rdx], '1' .Done: mov rax, rdx ; RAX is ptr to zero-terminated result pop rbx ret
{ "domain": "codereview.stackexchange", "id": 43906, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "performance, linux, assembly, x86, bigint", "url": null }
performance, linux, assembly, x86, bigint .Done: mov rax, rdx ; RAX is ptr to zero-terminated result pop rbx ret Tip: The code can be optimized with a further loop, because once the addition in LoopB does not produce another carry, we can exit from that loop and copy the remainder of the string unmodified. If your bigints have very different lengths, this can speed up a lot... Refinement Is there any way to make it so you directly write to char *res instead of returning a pointer to a part of it without it affecting the speed? The little detail that sits in the way for what you desire, is the possibility of having to prepend a "1" digit in case of a final carry. The probability that a final carry occurs IMO would be extremely small when working with these extremely long numbers. Therefore I suggest we rewrite the algorithm so as to ignore a potential final carry at first, but if in the end we do discover one, we just copy the result one byte up in memory and prepend the "1" digit. Sure, this will cost extra when it runs, but it will almost never have to run. ; Version that leaves RDX unchanged ; IN (rdx,rsi,rdi) OUT () MOD (rax,rcx,rsi,rdi,r8,r9) push rbx ; The only callee-saved register to preserve push rdx ; (1) push rsi ; (2) push rdi ; (3) call strlen ; -> RAX is strlen(a) mov ebx, eax ; For sure less than 4GB mov rdi, [rsp+8] call strlen ; -> RAX is strlen(b) pop rdi ; (3) pop rsi ; (2) pop rdx ; (1) ; At RDI are RBX bytes, at RSI are RAX bytes
{ "domain": "codereview.stackexchange", "id": 43906, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "performance, linux, assembly, x86, bigint", "url": null }
performance, linux, assembly, x86, bigint ; At RDI are RBX bytes, at RSI are RAX bytes cmp ebx, eax jae .NoSwap xchg rdi, rsi ; Make (RDI:RBX) refer to the longer input xchg ebx, eax .NoSwap: mov ecx, eax ; RAX is length of the shorter input lea r8, [rdi+rbx] ; R8 points at the terminating zero lea r9, [rsi+rax] ; R9 points at the terminating zero add rdx, rbx ; RBX is length of the longer input push rdx ; (4) "in case there's a final carry" xor ebx, ebx ; BL is carry [0,1] mov [rdx], bl ; Zero-terminating the result jecxz .NoLoopA .LoopA: ; Deals with the common positions movzx eax, byte [r8-1] add al, [r9-1] sub al, '0' add al, bl ; Plus carry xor ebx, ebx ; Clear carry cmp al, '9' jbe .CharOK sub al, 10 inc ebx ; Set carry .CharOK: mov [rdx-1], al dec r9 dec r8 dec rdx dec rcx jnz .LoopA .NoLoopA: cmp r8, rdi jna .NoLoopB .LoopB: ; Deals with remainder of the longer input movzx eax, byte [r8-1] add al, bl ; Plus carry xor ebx, ebx ; Clear carry cmp al, '9' jbe .CharOK_ sub al, 10 inc ebx ; Set carry .CharOK_: mov [rdx-1], al dec r8 dec rdx cmp r8, rdi ja .LoopB .NoLoopB: pop rcx ; (4) test bl, bl ; Check for a final carry. jz .Done .CopyUp: mov al, [rcx] mov [rcx+rbx], al ; RBX=1 dec rcx cmp rcx, rdx jae .CopyUp mov byte [rdx], '1' .Done: pop rbx ; Unchanged RDX is ptr to zero-terminated result ret Not only does the extra .CopyUp code very seldom have to run, since it's a simple memcpy, you can replace it with any specialized version of it (or just invoke one) should you deem this useful.
{ "domain": "codereview.stackexchange", "id": 43906, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "performance, linux, assembly, x86, bigint", "url": null }
python, hash-map Title: API request into a dictionary Question: I have the code below which currently pulls pricing data for Ethereum from CoinGecko API. From this request I am building a dictionary that contains the pieces of information and returning it to be used elsewhere in my code. This function works fine, but I can't help think it could be written so much shorter than this. How could this be written differently and shorter? def get_ethereum_data(): ethereum_data = {} response = requests.get(f"{COINGECKO_COIN_URL}") response.raise_for_status() data = response.json() ethereum_data["current_price"] = data["market_data"]["current_price"]["usd"] ethereum_data["market_cap"] = data["market_data"]["market_cap"]["usd"] ethereum_data["ath"] = data["market_data"]["ath"]["usd"] ethereum_data["ath_percentage"] = data["market_data"]["ath_change_percentage"]["usd"] ethereum_data["24h_percentage"] = data["market_data"]["price_change_percentage_24h"] ethereum_data["7d_percentage"] = data["market_data"]["price_change_percentage_7d"] ethereum_data["30d_percentage"] = data["market_data"]["price_change_percentage_30d"] ethereum_data["1y_percentage"] = data["market_data"]["price_change_percentage_1y"] return ethereum_data Answer: You could write a little bit simpler: Inline the returned ethereum_data dictionary, return it directly COINGECKO_COIN_URL is the same as f"{COINGECKO_COIN_URL}" (assuming it's a string) Extract the frequently used data["market_data"] as market_data = data["market_data"] Like this: def get_ethereum_data(): response = requests.get(COINGECKO_COIN_URL) response.raise_for_status()
{ "domain": "codereview.stackexchange", "id": 43907, "lm_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, hash-map", "url": null }
python, hash-map data = response.json() market_data = data["market_data"] return { "current_price": market_data["current_price"]["usd"], "market_cap": market_data["market_cap"]["usd"], "ath": market_data["ath"]["usd"], "ath_percentage": market_data["ath_change_percentage"]["usd"], "24h_percentage": market_data["price_change_percentage_24h"], "7d_percentage": market_data["price_change_percentage_7d"], "30d_percentage": market_data["price_change_percentage_30d"], "1y_percentage": market_data["price_change_percentage_1y"], }
{ "domain": "codereview.stackexchange", "id": 43907, "lm_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, hash-map", "url": null }
beginner, reinventing-the-wheel, rust, vectors Title: General purpose 2D grid Question: I am developing (WIP) a mine sweeping game to get more familiar with Rust. I decided to represent the mine field as a 2D grid. While developing I realized that this grid can be outsourced as a general purpose grid into an own module. Here it goes: #[derive(Debug)] pub struct Grid<T> { width: usize, height: usize, items: Vec<Vec<T>>, } impl<T> Grid<T> { pub fn new(width: usize, height: usize, initializer: impl Fn() -> T) -> Self { Self { width, height, items: (0..height) .map(move |_| (0..width).map(|_| initializer()).collect()) .collect(), } } pub fn width(&self) -> usize { self.width } pub fn height(&self) -> usize { self.height } pub fn get(&self, x: usize, y: usize) -> Option<&T> { if x < self.width() && y < self.height() { Some(&self.items[y][x]) } else { None } } pub fn get_mut(&mut self, x: usize, y: usize) -> Option<&mut T> { if x < self.width() && y < self.height() { Some(&mut self.items[y][x]) } else { None } } pub fn iter(&self) -> impl Iterator<Item = &T> { self.items.iter().flat_map(|line| line) } pub fn iter_mut(&mut self) -> impl Iterator<Item = &mut T> { self.items.iter_mut().flat_map(|line| line) } pub fn enumerate(&self) -> impl Iterator<Item = (usize, usize, &T)> { self.items .iter() .enumerate() .flat_map(|(y, line)| line.iter().enumerate().map(move |(x, item)| (x, y, item))) } pub fn enumerate_mut(&mut self) -> impl Iterator<Item = (usize, usize, &mut T)> { self.items.iter_mut().enumerate().flat_map(|(y, line)| { line.iter_mut() .enumerate() .map(move |(x, item)| (x, y, item)) }) }
{ "domain": "codereview.stackexchange", "id": 43908, "lm_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, reinventing-the-wheel, rust, vectors", "url": null }
beginner, reinventing-the-wheel, rust, vectors pub fn neighbors(&self, x: usize, y: usize) -> impl Iterator<Item = (usize, usize, &T)> { self.enumerate().filter(move |(other_x, other_y, _)| { is_neighbor(other_x.abs_diff(x), other_y.abs_diff(y)) }) } pub fn neighbors_mut( &mut self, x: usize, y: usize, ) -> impl Iterator<Item = (usize, usize, &mut T)> { self.enumerate_mut().filter(move |(other_x, other_y, _)| { is_neighbor(other_x.abs_diff(x), other_y.abs_diff(y)) }) } } fn is_neighbor(dx: usize, dy: usize) -> bool { is_adjunct(dx) && is_adjunct(dy) && !same_field(dx, dy) } fn is_adjunct(offset: usize) -> bool { offset == 0 || offset == 1 } fn same_field(dx: usize, dy: usize) -> bool { dx == 0 && dy == 0 } As I am still a beginner regarding Rust, I'd like to have feedback on the proper and idiomatic use of the language. Answer: That code is already of utterly high quality for a "beginner" in Rust. I think you should be proud of yourself here! Highlights: you use an initializer function in the constructor! your code is generic over all types, and you use impl types where possible your code is free of panics you have tests for the important items Here's what I would improve. Linting Use clippy to lint your code. It's the default for Rust. The first "warning" is clippy::len_without_is_empty, which normally applies to vectors, and warns if a struct has a len(&self) -> usize method without an is_empty(&self) -> bool method. Since the length of your array is not variable, but constant after initialization, I would rename the method to something else to avoid associating your len with variable-length objects. pub fn size(&self) -> usize { self.width * self.height }
{ "domain": "codereview.stackexchange", "id": 43908, "lm_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, reinventing-the-wheel, rust, vectors", "url": null }
beginner, reinventing-the-wheel, rust, vectors Then you have a clippy::flat_map_identity lint. Your iter and iter_mut methods make use of flat_map, which combines flatten() and map() in one function. You do not need the map part, since you do not apply any function to row. So you can shorten that to flatten(). pub fn iter(&self) -> impl Iterator<Item = &T> { self.items.iter().flatten() } pub fn iter_mut(&mut self) -> impl Iterator<Item = &mut T> { self.items.iter_mut().flatten() } Finding neighbors Your fn neighbors(...) -> impl Iterator is very inefficient, since you traverse the whole Grid to find the neighbors, whose coordinates you could calculate very easily instead. Calculating the coordinates directly is a constant-time operation, while your current implementation is O(n * m) where n and m are the height and width of your grid. I would write this with slightly more code, but in a more efficient manner. Unfortunately, we need to convert between usize and isize a couple of times then. const NEIGHBOR_INDICES: [isize; 3] = [-1, 0, 1]; ..... // impl Grid pub fn neighbors(&self, x: usize, y: usize) -> impl Iterator<Item = (usize, usize, &T)> { self.calc_neighbor_indices(x, y) .map(|(x, y)| (x, y, self.get(x, y).unwrap())) } fn generate_neighbor_offsets() -> impl Iterator<Item = (isize, isize)> { NEIGHBOR_INDICES .into_iter() .flat_map(|i| [i].into_iter().cycle().zip(NEIGHBOR_INDICES)) .filter(|(x, y)| !(*x == 0 && *y == 0)) } fn calc_neighbor_indices(&self, x: usize, y: usize) -> impl Iterator<Item = (usize, usize)> + '_ { Self::generate_neighbor_offsets() .map(move |(nx, ny)| (x as isize + nx, y as isize + ny)) .filter(|(nx, ny)| { // remove elements outside of grid 0 <= *nx && *nx < self.width as isize && 0 <= *ny && *ny < self.height as isize }) .map(|(nx, ny)| (nx as usize, ny as usize)) }
{ "domain": "codereview.stackexchange", "id": 43908, "lm_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, reinventing-the-wheel, rust, vectors", "url": null }
beginner, reinventing-the-wheel, rust, vectors I was surprised to find out that neighbors_mut() cannot be written in the same manner, but I cannot figure out right now how to fix it. So this does not work. pub fn neighbors_mut( &mut self, x: usize, y: usize, ) -> impl Iterator<Item = (usize, usize, &mut T)> { self.calc_neighbor_indices(x, y) .map(|(x, y)| (x, y, self.get_mut(x, y).unwrap())) } If you could figure out how to write that correctly, you could get rid of the is_adjunct() and is_neighbor() functions.
{ "domain": "codereview.stackexchange", "id": 43908, "lm_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, reinventing-the-wheel, rust, vectors", "url": null }
beginner, reinventing-the-wheel, rust, vectors data structure You have decided to represent the 2D grid as a Vec<Vec<T>>, which is the trivial solution, but by far not the most efficient. AFAICR allocating a new Vec reserves space for one element. If that space is used, and you want to push another element to the vector, the current size is doubled. So the vector grows exponentially, which is good for the runtime performance, but slow for allocation. Generally, think that each row requires ld(width) allocations, where ld is the binary logarithm. Furthermore, the same considerations apply to your outer vector. So you are looking at a total of ld(height) * ld(width) allocations (assuming no optimizations). BUT, since you used collect(), which uses FromIterator, the vector automatically is allocated with the right capacity from the size hint of the iterator, so you wouldn't need to worry about that here. Now you have an outer vector which stores the starting address of each row vector, so you have height + 1 vectors. Since they are allocated individually, they are very likely located at different positions on the heap. That is bad for performance, since when you need the data, the CPU needs to "jump" to different addresses often. This is not critical for your envisioned minesweeper, but nevertheless good to keep in mind. What I would do here is storing the data as 1D-vector internally, and then calculating the offsets in the vector from a provided x and y. This is often done in numerical applications, where performance is of highest importance. #[derive(Debug)] pub struct Grid<T> { width: usize, height: usize, items: Vec<T>, } impl<T> Grid<T> { pub fn new(width: usize, height: usize, initializer: impl Fn() -> T) -> Self { Self { width, height, items: (0..height) .flat_map(|_| (0..width).map(|_| initializer())) .collect(), } }
{ "domain": "codereview.stackexchange", "id": 43908, "lm_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, reinventing-the-wheel, rust, vectors", "url": null }
beginner, reinventing-the-wheel, rust, vectors pub fn get(&self, x: usize, y: usize) -> Option<&T> { if x < self.width() && y < self.height() { Some(&self.items[self.coordinate_to_idx(x, y)]) } else { None } } pub fn get_mut(&mut self, x: usize, y: usize) -> Option<&mut T> { if x < self.width() && y < self.height() { let idx = self.coordinate_to_idx(x, y); Some(&mut self.items[idx]) } else { None } } fn idx_to_coordinate(&self, idx: usize) -> (usize, usize) { let x = idx % self.width; let y = (idx - x) / self.width; (x, y) } fn coordinate_to_idx(&self, x: usize, y: usize) -> usize { y * self.width + x } Then you can also remove the flatten() call in iter. Unfortunately, the iter_mut method has the same issue as neighbors_mut. Maybe someone else can figure that out. I have commented it out for now, to make the code compile. Here is my final code. Please apologize that I could not get it to work entirely. const NEIGHBOR_INDICES: [isize; 3] = [-1, 0, 1]; #[derive(Debug)] pub struct Grid<T> { width: usize, height: usize, items: Vec<T>, } impl<T> Grid<T> { pub fn new(width: usize, height: usize, initializer: impl Fn() -> T) -> Self { Self { width, height, items: (0..height) .flat_map(|_| (0..width).map(|_| initializer())) .collect(), } } pub fn width(&self) -> usize { self.width } pub fn height(&self) -> usize { self.height } pub fn size(&self) -> usize { self.width * self.height } pub fn get(&self, x: usize, y: usize) -> Option<&T> { if x < self.width() && y < self.height() { Some(&self.items[self.coordinate_to_idx(x, y)]) } else { None } }
{ "domain": "codereview.stackexchange", "id": 43908, "lm_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, reinventing-the-wheel, rust, vectors", "url": null }
beginner, reinventing-the-wheel, rust, vectors fn coordinate_to_idx(&self, x: usize, y: usize) -> usize { y * self.width + x } pub fn get_mut(&mut self, x: usize, y: usize) -> Option<&mut T> { if x < self.width() && y < self.height() { let idx = self.coordinate_to_idx(x, y); Some(&mut self.items[idx]) } else { None } } pub fn iter(&self) -> impl Iterator<Item = &T> { self.items.iter() } pub fn iter_mut(&mut self) -> impl Iterator<Item = &mut T> { self.items.iter_mut() } pub fn enumerate(&self) -> impl Iterator<Item = (usize, usize, &T)> { self.items.iter().enumerate().map(|(idx, item)| { let (x, y) = self.idx_to_coordinate(idx); (x, y, item) }) } // pub fn enumerate_mut(&mut self) -> impl Iterator<Item = (usize, usize, &mut T)> { // self.items.iter_mut().enumerate().map(|(idx, item)| { // let (x, y) = self.idx_to_coordinate(idx); // (x, y, item) // }) // } fn idx_to_coordinate(&self, idx: usize) -> (usize, usize) { let x = idx % self.width; let y = (idx - x) / self.width; (x, y) } pub fn neighbors(&self, x: usize, y: usize) -> impl Iterator<Item = (usize, usize, &T)> { self.calc_neighbor_indices(x, y) .map(|(x, y)| (x, y, self.get(x, y).unwrap())) } fn generate_neighbor_offsets() -> impl Iterator<Item = (isize, isize)> { NEIGHBOR_INDICES .into_iter() .flat_map(|i| [i].into_iter().cycle().zip(NEIGHBOR_INDICES)) .filter(|(x, y)| !(*x == 0 && *y == 0)) }
{ "domain": "codereview.stackexchange", "id": 43908, "lm_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, reinventing-the-wheel, rust, vectors", "url": null }
beginner, reinventing-the-wheel, rust, vectors fn calc_neighbor_indices( &self, x: usize, y: usize, ) -> impl Iterator<Item = (usize, usize)> + '_ { Self::generate_neighbor_offsets() .map(move |(nx, ny)| (x as isize + nx, y as isize + ny)) .filter(|(nx, ny)| { // remove elements outside of grid 0 <= *nx && *nx < self.width as isize && 0 <= *ny && *ny < self.height as isize }) .map(|(nx, ny)| (nx as usize, ny as usize)) } // pub fn neighbors_mut( // &mut self, // x: usize, // y: usize, // ) -> impl Iterator<Item = (usize, usize, &mut T)> { // self.enumerate_mut().filter(move |(other_x, other_y, _)| { // is_neighbor(other_x.abs_diff(x), other_y.abs_diff(y)) // }) // } } fn is_neighbor(dx: usize, dy: usize) -> bool { is_adjunct(dx) && is_adjunct(dy) && !same_field(dx, dy) } fn is_adjunct(offset: usize) -> bool { offset == 0 || offset == 1 } fn same_field(dx: usize, dy: usize) -> bool { dx == 0 && dy == 0 }
{ "domain": "codereview.stackexchange", "id": 43908, "lm_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, reinventing-the-wheel, rust, vectors", "url": null }
python, python-3.x, python-requests, rss Title: Create URL's, then download and print each RSS feed text Question: Looking for a more efficient way of achieving this. In particular the combine_all_rss_lists so I don't need all those params. Feedparser module doesn't accept lists which is why I've had to initially break them into strings. Would be ideal to have minimal arguments as well. def create_rss_urls(): topics = ['business', 'technology', 'science_and_environment', 'politics', 'world', 'health', 'education', 'uk'] url_list = [] for topic in topics: url = f'http://feeds.bbci.co.uk/news/{topic}/rss.xml' url_list.append(url) return url_list def list_rss_feed(rss_feed_url): """Create a list of the top 10 articles for each RSS Feed topic. To be used by convert_rss_list_to_str() function.""" data = feedparser.parse(rss_feed_url) i = 0 full_feed_text_list = [] while i < 10: # Find first 10 articles feed_title_str = data['entries'][i]["title"] feed_description_str = data['entries'][i]['description'] full_feed_text = feed_title_str + ' ' + feed_description_str i = i + 1 # Move to the next article full_feed_text_list.append(full_feed_text) # Add each article to this list return full_feed_text_list def combine_all_rss_lists(rss_list: list, rss_list_2: list, rss_list_3: list, rss_list_4: list, rss_list_5: list, rss_list_6: list, rss_list_7: list, rss_list_8: list): full_list = rss_list + rss_list_2 + rss_list_3 + rss_list_4 + rss_list_5 + rss_list_6 + rss_list_7 + rss_list_8 return full_list def convert_rss_list_to_str(rss_list: list): """Convert RSS feed text to string which is to be displayed in rss_live_feeds.""" s = '\n\n'.join(str(x) for x in rss_list) return s
{ "domain": "codereview.stackexchange", "id": 43909, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x, python-requests, rss", "url": null }
python, python-3.x, python-requests, rss topic_urls = create_rss_urls() bbc_rss_business = list_rss_feed(topic_urls[0]) bbc_rss_technology = list_rss_feed(topic_urls[1]) bbc_science_and_environment_feed = list_rss_feed(topic_urls[2]) bbc_politics_feed = list_rss_feed(topic_urls[3]) bbc_world_feed = list_rss_feed(topic_urls[4]) bbc_health_feed = list_rss_feed(topic_urls[5]) bbc_uk_feed = list_rss_feed(topic_urls[6]) bbc_education_feed = list_rss_feed(topic_urls[7]) # investing_feed = list_rss_feed(topic_urls[8]) # Add to full_list later full_list = combine_all_rss_lists(bbc_rss_business, bbc_rss_technology, bbc_science_and_environment_feed, bbc_politics_feed, bbc_world_feed, bbc_health_feed, bbc_uk_feed, bbc_education_feed) print(str(convert_rss_list_to_str(full_list))) Answer: Your topics should be a tuple and not a list, and if you want they can be moved to a global constant. Add PEP484 type hints. I don't think that feedparser is able to process feeds incrementally. If you truly do want to pull only the first ten items from each topic, and only pay the bandwidth and processing costs for them and ignore the rest, you have to cut to a lower level of abstraction (probably Requests and sax). Don't hard-code indices [0], [1] etc. Computers are good at loops. Suggested from contextlib import contextmanager from itertools import islice from typing import Iterator, Iterable, NamedTuple, Optional from xml.sax import make_parser from xml.sax.handler import ContentHandler from xml.sax.xmlreader import AttributesImpl from requests import Session TOPICS = ('business', 'technology', 'science_and_environment', 'politics', 'world', 'health', 'education', 'uk')
{ "domain": "codereview.stackexchange", "id": 43909, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x, python-requests, rss", "url": null }
python, python-3.x, python-requests, rss @contextmanager def load_feed(session: Session, topic: str) -> Iterator[Iterable[str]]: with session.get( url=f'http://feeds.bbci.co.uk/news/{topic}/rss.xml', headers={ 'Accept': 'application/rss+xml', 'Accept-Encoding': 'gzip', }, stream=True, ) as resp: resp.raise_for_status() yield resp.iter_content(chunk_size=1024, decode_unicode=True) class Item(NamedTuple): title: str desc: str def __str__(self) -> str: return f'{self.title}: {self.desc}' class FeedHandler(ContentHandler): def __init__(self) -> None: super().__init__() self.collecting_cdata = False self.items: list[Item] = [] self.title: Optional[str] = None self.desc: Optional[str] = None self.text = '' def startElement(self, name: str, attrs: AttributesImpl) -> None: match name: case 'item': self.title = None self.desc = None case 'title' | 'description': self.text = '' self.collecting_cdata = True case _: self.collecting_cdata = False def characters(self, content: str) -> None: if self.collecting_cdata: self.text += content def endElement(self, name: str) -> None: match name: case 'title': self.title = self.text case 'description': self.desc = self.text case 'item': self.items.append(Item(self.title, self.desc)) self.collecting_cdata = False def output(self) -> list[Item]: to_output = self.items self.items = [] return to_output def parse_feed(chunks: Iterable[bytes]) -> Iterator[Item]: handler = FeedHandler() parser = make_parser(('xml.sax.expatreader',)) parser.setContentHandler(handler)
{ "domain": "codereview.stackexchange", "id": 43909, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x, python-requests, rss", "url": null }
python, python-3.x, python-requests, rss for chunk in chunks: parser.feed(chunk) yield from handler.output() def main() -> None: with Session() as session: for topic in TOPICS: print(topic) with load_feed(session, topic) as chunks: for element in islice(parse_feed(chunks), 10): print(element) print() if __name__ == '__main__': main() Output business Pound sinks as investors question huge tax cuts: Markets worry over the outlook for government finances following the biggest tax cutting moves in 50 years. Mini-budget: What it means for you and your finances: Chancellor Kwasi Kwarteng has delivered what the government calls a "fiscal event". Here is how it affects you. 'We'll be lucky to keep our heads above water': The BBC talked to households and businesses to get their reactions to the mini-budget. Goldman Sachs: Sexual assault claims revealed in pay bias suit: Goldman Sachs is accused of "boys' club" culture that discriminated against women. Income tax to be cut by 1p from April: The basic rate of income tax will fall by 1p from April with most people paying 19p instead of 20p for each pound. Stamp duty cut in bid to help house buyers: The chancellor says the changes mean 200,000 more house buyers will no longer pay the tax. At a glance: What's in the mini-budget?: Chancellor Kwasi Kwarteng outlines changes to tax, stamp duty and rules for those claiming benefits. Universal credit rules tightened for part-time workers: The chancellor announced part-time workers will see their benefits cut if they don't try to earn more. UK may already be in recession - Bank of England: The warning comes as the Bank raises interest rates to 2.25% - the highest level for 14 years. Real Living Wage rises by record 10% to £10.90 an hour: A record increase in the voluntary pay scheme will benefit 400,000 workers.
{ "domain": "codereview.stackexchange", "id": 43909, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x, python-requests, rss", "url": null }
python, python-3.x, python-requests, rss technology Testing the new iPhone: From battery to always-on screen: The BBC's Technology Editor, Zoe Kleinman, has been testing out the latest Apple smartphone. Tesla ordered to recall more than a million US cars: The US car-safety watchdog says a window glitch is affecting all four Tesla models. Iran unrest: What's going on with Iran and the internet?: The internet is cutting out and residents are unable to access social media in parts of the country. Rape posts every half-hour found on online incel forum: More must be done to tackle women-hating movement incel, the Centre for Countering Digital Hate warns. Warning over scam energy bill support messages: Emails and texts link to a fake Ofgem website where people's personal details are demanded. Oxfordshire teen arrested in police hacking investigation: The National Cyber Crime Unit detained a 17-year-old from Oxfordshire on Thursday evening. Australia phones cyber-attack exposes personal data: Optus is looking into the unauthorised access of data including names, addresses and passport numbers. Twitch announces slots and roulette gambling ban: The livestreaming site will prohibit streams of slots, roulette or dice games from many jurisdictions. Molly Russell inquest: Instagram clips seen by teen 'most distressing': The 14-year-old girl viewed material about self-harm and suicide before she died in 2017. Online Safety Bill to return as soon as possible: But rules to tackle "legal but harmful" material will change over free-speech fears, a minister says.
{ "domain": "codereview.stackexchange", "id": 43909, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x, python-requests, rss", "url": null }