text
stringlengths
1
2.12k
source
dict
python Answer: clear identifiers distribute_total_reward() looks great. All the identifiers are very helpful. An URL citation of that formula which introduces the variable "a" wouldn't hurt. post-condition The essential aspect of this routine is the computed rewards shall sum to the specified input parameter. We should minimally spell this out with an English sentence in a docstring. The supplied test code nicely computes a sum(), but it is not self-evaluating so a human must eyeball the result and verify it's sensible. Ideally the function would end with an assert of equality, but due to FP ULP rounding errors we expect a small epsilon error, so the test would be for relative_error() less than e.g. 1 ppb. An easy assert would be to construct a unit test to check the post-condition. For some parameters, such as 1024 total reward and .5 decay rate, the FP result will yield exact equality. def main() Nice __main__ guard. There is starting to be enough code here that it may be worth burying it within def main():. By the time you introduce reverse_rewards we're definitely ready for that. I confess I'm not sure about the choice of tw rather than a tr name. nit: We switch between £$ and $ currency prefixes. distribute() It's unclear why the currency figures of total_reward and reverse_referral_reward would be of type int. Please understand that a float annotation subsumes int, even though integers can have unlimited magnitude and there's no inheritance relationship between them. We have a docstring, and it is informative. But it's a little wishy washy. If I'm tasked with writing a unit test that verifies correct behavior, verifies the implementation conforms to a spec, then consulting just the docstring, alas, won't suffice. The verbs "distributes" and "handles" are OK but they aren't accompanied by any specifics. It seems like we want a pair of post-conditions here, constraining what happens with each of the two reward categories. DRY
{ "domain": "codereview.stackexchange", "id": 45574, "lm_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 constraining what happens with each of the two reward categories. DRY adjusted_total_reward = total_reward - (num_reverse_referrals * reverse_referral_reward) ... reverse_rewards = [reverse_referral_reward for _ in range(num_reverse_referrals)]
{ "domain": "codereview.stackexchange", "id": 45574, "lm_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 These are kind of saying the same thing. Consider first computing reverse_rewards = [reverse_referral_reward] * num_reverse_referrals and then you can conveniently assign total_reward - sum(reverse_rewards). design of Public API return rewards, reverse_rewards
{ "domain": "codereview.stackexchange", "id": 45574, "lm_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 This kind of looks like we're returning parallel vectors a, b as seen in many Fortran APIs, where a[i] describes one aspect of entity i and b[i] another aspect of that same entity. But of course they have different lengths. Consider including 0 values in the reverse_rewards. Consider returning a single vector of namedtuples that contain values for both reward categories. Which brings us to the input parameters. You will need a way to describe who referred, in which direction, and how effectively. This could be a general graph, but I am skeptical that you have a business use case for that yet. Better to start out with a restricted graph such as a tree. Maybe pass in a vector of (forward, reverse) referral magnitudes, and of course when all the reverse values are zero we should produce same result as that first algorithm produces. algorithm The closed-form solution you provide is very nice. Here is another way, a little messier, to think about that initial algorithm. Assign total_reward to the initial entry, with the rest zero. Use a for i in range(max_levels): loop to make several passes over the vector, distributing a small fraction of remaining reward each time. The last iteration makes the one and only assignment to the final level. We always {add, subtract} same small value, preserving a constant total. Now consider a graph that includes reverse referrals. Again we make several passes over the graph starting from its root, distributing a fraction as we go. But when following an upward edge we now can distribute upward, as well. The current approach of “divide level I reward evenly among that level’s participants” will need to move toward considering each participant individually. It's possible that you wish to view this as "a single (downward) origin node plus N (upward) reverse nodes", and so you want to run N + 1 instances of the loop.
{ "domain": "codereview.stackexchange", "id": 45574, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python", "url": null }
c++, algorithm, image, template, c++20 Title: Gaussian Fisheye Image Generator Implementation in C++ Question: This is a follow-up question for An Updated Multi-dimensional Image Data Structure with Variadic Template Functions in C++ and Three dimensional gaussian image generator in C++. I am trying to make a Gaussian fisheye image generator in this post. The example output: Image Input Output The experimental implementation gaussian_fisheye template function implementation (in file image_operations.h) namespace TinyDIP { // gaussian_fisheye template function implementation template<arithmetic ElementT, std::floating_point FloatingType = double> constexpr static auto gaussian_fisheye(const Image<ElementT>& input, FloatingType D0) { if (input.getDimensionality()!=2) { throw std::runtime_error("Unsupported dimension!"); }
{ "domain": "codereview.stackexchange", "id": 45575, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, image, template, c++20", "url": null }
c++, algorithm, image, template, c++20 Image<ElementT> output(input.getWidth(), input.getHeight()); for (std::size_t y = 0; y < input.getHeight(); ++y) { for (std::size_t x = 0; x < input.getWidth(); ++x) { FloatingType distance_x = x - static_cast<FloatingType>(input.getWidth()) / 2.0; FloatingType distance_y = y - static_cast<FloatingType>(input.getHeight()) / 2.0; FloatingType distance = std::hypot(distance_x, distance_y); FloatingType angle = std::atan2(distance_y, distance_x); FloatingType weight = normalDistribution2D(std::fabs(distance_x), std::fabs(distance_y), D0) / normalDistribution2D(0.0, 0.0, D0); FloatingType new_distance = distance * weight; FloatingType new_distance_x = new_distance * std::cos(angle); FloatingType new_distance_y = new_distance * std::sin(angle); output.at( static_cast<std::size_t>(new_distance_x + static_cast<FloatingType>(input.getWidth()) / 2.0), static_cast<std::size_t>(new_distance_y + static_cast<FloatingType>(input.getHeight()) / 2.0)) = input.at(x, y); } } return output; } // gaussian_fisheye template function implementation template<typename ElementT, class FloatingType = double> requires ((std::same_as<ElementT, RGB>) || (std::same_as<ElementT, HSV>)) constexpr static auto gaussian_fisheye(const Image<ElementT>& input, FloatingType D0) { return apply_each(input, [&](auto&& planes) { return gaussian_fisheye(planes, D0); }); } }
{ "domain": "codereview.stackexchange", "id": 45575, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, image, template, c++20", "url": null }
c++, algorithm, image, template, c++20 normalDistribution2D function implementation (in file image_operations.h) template<typename T> T normalDistribution2D(const T xlocation, const T ylocation, const T standard_deviation) { return std::exp(-(xlocation * xlocation + ylocation * ylocation) / (2 * standard_deviation * standard_deviation)) / (2 * std::numbers::pi * standard_deviation * standard_deviation); } apply_each function implementation (in file image_operations.h) template<class T = RGB, class F, class... Args> requires (std::same_as<T, RGB>) constexpr static auto apply_each(Image<T> input, F operation, Args&&... args) { return constructRGB(operation(getRplane(input), args...), operation(getGplane(input), args...), operation(getBplane(input), args...)); } Image class implementation (in file image.h) namespace TinyDIP { template <typename ElementT> class Image { public: Image() = default; template<std::same_as<std::size_t>... Sizes> Image(Sizes... sizes): size{sizes...}, image_data((1 * ... * sizes)) {} template<std::same_as<int>... Sizes> Image(Sizes... sizes) { size.reserve(sizeof...(sizes)); (size.push_back(sizes), ...); image_data.resize( std::reduce( std::ranges::cbegin(size), std::ranges::cend(size), std::size_t{1}, std::multiplies<>() ) ); } template<std::ranges::input_range Range, std::same_as<std::size_t>... Sizes> Image(const Range& input, Sizes... sizes): size{sizes...}, image_data(begin(input), end(input)) { if (image_data.size() != (1 * ... * sizes)) { throw std::runtime_error("Image data input and the given size are mismatched!"); } }
{ "domain": "codereview.stackexchange", "id": 45575, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, image, template, c++20", "url": null }
c++, algorithm, image, template, c++20 Image(std::vector<ElementT>&& input, std::size_t newWidth, std::size_t newHeight) { size.reserve(2); size.emplace_back(newWidth); size.emplace_back(newHeight); if (input.size() != newWidth * newHeight) { throw std::runtime_error("Image data input and the given size are mismatched!"); } image_data = std::move(input); // Reference: https://stackoverflow.com/a/51706522/6667035 } Image(const std::vector<std::vector<ElementT>>& input) { size.reserve(2); size.emplace_back(input[0].size()); size.emplace_back(input.size()); for (auto& rows : input) { image_data.insert(image_data.end(), std::ranges::begin(input), std::ranges::end(input)); // flatten } return; } // at template function implementation template<typename... Args> constexpr ElementT& at(const Args... indexInput) { return const_cast<ElementT&>(static_cast<const Image &>(*this).at(indexInput...)); } // at template function implementation // Reference: https://codereview.stackexchange.com/a/288736/231235 template<typename... Args> constexpr ElementT const& at(const Args... indexInput) const { checkBoundary(indexInput...); constexpr std::size_t n = sizeof...(Args); if(n != size.size()) { throw std::runtime_error("Dimensionality mismatched!"); } std::size_t i = 0; std::size_t stride = 1; std::size_t position = 0; auto update_position = [&](auto index) { position += index * stride; stride *= size[i++]; }; (update_position(indexInput), ...);
{ "domain": "codereview.stackexchange", "id": 45575, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, image, template, c++20", "url": null }
c++, algorithm, image, template, c++20 return image_data[position]; } constexpr std::size_t count() const noexcept { return std::reduce(std::ranges::cbegin(size), std::ranges::cend(size), 1, std::multiplies()); } constexpr std::size_t getDimensionality() const noexcept { return size.size(); } constexpr std::size_t getWidth() const noexcept { return size[0]; } constexpr std::size_t getHeight() const noexcept { return size[1]; } constexpr auto getSize() noexcept { return size; } std::vector<ElementT> const& getImageData() const noexcept { return image_data; } // expose the internal data
{ "domain": "codereview.stackexchange", "id": 45575, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, image, template, c++20", "url": null }
c++, algorithm, image, template, c++20 void print(std::string separator = "\t", std::ostream& os = std::cout) const { if(size.size() == 1) { for(std::size_t x = 0; x < size[0]; ++x) { // Ref: https://isocpp.org/wiki/faq/input-output#print-char-or-ptr-as-number os << +at(x) << separator; } os << "\n"; } else if(size.size() == 2) { for (std::size_t y = 0; y < size[1]; ++y) { for (std::size_t x = 0; x < size[0]; ++x) { // Ref: https://isocpp.org/wiki/faq/input-output#print-char-or-ptr-as-number os << +at(x, y) << separator; } os << "\n"; } os << "\n"; } else if (size.size() == 3) { for(std::size_t z = 0; z < size[2]; ++z) { for (std::size_t y = 0; y < size[1]; ++y) { for (std::size_t x = 0; x < size[0]; ++x) { // Ref: https://isocpp.org/wiki/faq/input-output#print-char-or-ptr-as-number os << +at(x, y, z) << separator; } os << "\n"; } os << "\n"; } os << "\n"; } }
{ "domain": "codereview.stackexchange", "id": 45575, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, image, template, c++20", "url": null }
c++, algorithm, image, template, c++20 // Enable this function if ElementT = RGB void print(std::string separator = "\t", std::ostream& os = std::cout) const requires(std::same_as<ElementT, RGB>) { for (std::size_t y = 0; y < size[1]; ++y) { for (std::size_t x = 0; x < size[0]; ++x) { os << "( "; for (std::size_t channel_index = 0; channel_index < 3; ++channel_index) { // Ref: https://isocpp.org/wiki/faq/input-output#print-char-or-ptr-as-number os << +at(x, y).channels[channel_index] << separator; } os << ")" << separator; } os << "\n"; } os << "\n"; return; } Image<ElementT>& setAllValue(const ElementT input) { std::fill(std::ranges::begin(image_data), std::ranges::end(image_data), input); return *this; } friend std::ostream& operator<<(std::ostream& os, const Image<ElementT>& rhs) { const std::string separator = "\t"; rhs.print(separator, os); return os; } Image<ElementT>& operator+=(const Image<ElementT>& rhs) { check_size_same(rhs, *this); std::transform(std::ranges::cbegin(image_data), std::ranges::cend(image_data), std::ranges::cbegin(rhs.image_data), std::ranges::begin(image_data), std::plus<>{}); return *this; } Image<ElementT>& operator-=(const Image<ElementT>& rhs) { check_size_same(rhs, *this); std::transform(std::ranges::cbegin(image_data), std::ranges::cend(image_data), std::ranges::cbegin(rhs.image_data), std::ranges::begin(image_data), std::minus<>{}); return *this; }
{ "domain": "codereview.stackexchange", "id": 45575, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, image, template, c++20", "url": null }
c++, algorithm, image, template, c++20 Image<ElementT>& operator*=(const Image<ElementT>& rhs) { check_size_same(rhs, *this); std::transform(std::ranges::cbegin(image_data), std::ranges::cend(image_data), std::ranges::cbegin(rhs.image_data), std::ranges::begin(image_data), std::multiplies<>{}); return *this; } Image<ElementT>& operator/=(const Image<ElementT>& rhs) { check_size_same(rhs, *this); std::transform(std::ranges::cbegin(image_data), std::ranges::cend(image_data), std::ranges::cbegin(rhs.image_data), std::ranges::begin(image_data), std::divides<>{}); return *this; } friend bool operator==(Image<ElementT> const&, Image<ElementT> const&) = default; friend bool operator!=(Image<ElementT> const&, Image<ElementT> const&) = default; friend Image<ElementT> operator+(Image<ElementT> input1, const Image<ElementT>& input2) { return input1 += input2; } friend Image<ElementT> operator-(Image<ElementT> input1, const Image<ElementT>& input2) { return input1 -= input2; } friend Image<ElementT> operator*(Image<ElementT> input1, ElementT input2) { return multiplies(input1, input2); } friend Image<ElementT> operator*(ElementT input1, Image<ElementT> input2) { return multiplies(input2, input1); } #ifdef USE_BOOST_SERIALIZATION
{ "domain": "codereview.stackexchange", "id": 45575, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, image, template, c++20", "url": null }
c++, algorithm, image, template, c++20 #ifdef USE_BOOST_SERIALIZATION void Save(std::string filename) { const std::string filename_with_extension = filename + ".dat"; // Reference: https://stackoverflow.com/questions/523872/how-do-you-serialize-an-object-in-c std::ofstream ofs(filename_with_extension, std::ios::binary); boost::archive::binary_oarchive ArchiveOut(ofs); // write class instance to archive ArchiveOut << *this; // archive and stream closed when destructors are called ofs.close(); } #endif private: std::vector<std::size_t> size; std::vector<ElementT> image_data; template<typename... Args> void checkBoundary(const Args... indexInput) const { constexpr std::size_t n = sizeof...(Args); if(n != size.size()) { throw std::runtime_error("Dimensionality mismatched!"); } std::size_t parameter_pack_index = 0; auto function = [&](auto index) { if (index >= size[parameter_pack_index]) throw std::out_of_range("Given index out of range!"); parameter_pack_index = parameter_pack_index + 1; }; (function(indexInput), ...); } #ifdef USE_BOOST_SERIALIZATION friend class boost::serialization::access; template<class Archive> void serialize(Archive& ar, const unsigned int version) { ar& size; ar& image_data; } #endif }; template<typename T, typename ElementT> concept is_Image = std::is_same_v<T, Image<ElementT>>; } #endif The usage of gaussian_fisheye function: std::string file_path = "InputImages/1"; auto bmp1 = TinyDIP::bmp_read(file_path.c_str(), false); bmp1 = gaussian_fisheye(bmp1, 800.0); TinyDIP::bmp_write("test", bmp1);
{ "domain": "codereview.stackexchange", "id": 45575, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, image, template, c++20", "url": null }
c++, algorithm, image, template, c++20 TinyDIP on GitHub All suggestions are welcome. The summary information: Which question it is a follow-up to? An Updated Multi-dimensional Image Data Structure with Variadic Template Functions in C++ and Three dimensional gaussian image generator in C++ What changes has been made in the code since last question? I am trying to implement gaussian_fisheye template function in this post. Why a new review is being asked for? Please review the implementation of gaussian_fisheye template function. Answer: Unnecessary calculations You calculate angle using std::atan2(), but later use std::cos() and std::sin() to convert it back into x and y coordinates. This is unnecessary, you already had those to begin with, you only need to scale them. Furthermore, you don't need to use std::fabs() before passing the x and y position to normalDistribution2D(), since it will square those values anyway. Finally, you don't need any of the static casts to FloatingType, only the final casts back to std::size_t. So: FloatingType distance_x = x - input.getWidth() / 2.0; FloatingType distance_y = y - input.getHeight() / 2.0; FloatingType weight = normalDistribution2D(distance_x, distance_y, D0) / normalDistribution2D(0, 0, D0); FloatingType new_distance_x = distance_x * weight; FloatingType new_distance_y = distance_y * weight; output.at(static_cast<std::size_t>(new_distance_x + input.getWidth() / 2.0), static_cast<std::size_t>(new_distance_y + input.getHeight() / 2.0)) = input.at(x, y);
{ "domain": "codereview.stackexchange", "id": 45575, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, image, template, c++20", "url": null }
python, python-3.x, email Title: SMTP emailing library Question: Some time ago, I implemented an emailing library to simplify sending emails for several web applications and daemons. As usual, I am interested in improving my code. """Library for e-mailing.""" from __future__ import annotations from configparser import ConfigParser, SectionProxy from email.charset import Charset, QP from email.mime.multipart import MIMEMultipart from email.mime.nonmultipart import MIMENonMultipart from email.mime.text import MIMEText from email.utils import formatdate from functools import cache from logging import getLogger from smtplib import SMTPException, SMTP from typing import Iterable, Optional from warnings import warn __all__ = ['EMail', 'Mailer'] LOGGER = getLogger('emaillib') class MIMEQPText(MIMENonMultipart): """A quoted-printable encoded text.""" def __init__(self, payload: str, subtype: str = 'plain', charset: str = 'utf-8'): super().__init__('text', subtype, charset=charset) self.set_payload(payload, charset=get_qp_charset(charset)) class EMail(MIMEMultipart): """Email data for Mailer.""" def __init__(self, subject: str, sender: str, recipient: str, *, plain: str = None, html: str = None, charset: str = 'utf-8', quoted_printable: bool = False): """Creates a new EMail.""" super().__init__(subtype='alternative') self['Subject'] = subject self['From'] = sender self['To'] = recipient self['Date'] = formatdate(localtime=True, usegmt=True) text_type = MIMEQPText if quoted_printable else MIMEText if plain is not None: self.attach(text_type(plain, 'plain', charset)) if html is not None: self.attach(text_type(html, 'html', charset)) def __str__(self): """Converts the EMail to a string.""" return self.as_string()
{ "domain": "codereview.stackexchange", "id": 45576, "lm_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, email", "url": null }
python, python-3.x, email def __str__(self): """Converts the EMail to a string.""" return self.as_string() @property def subject(self): """Returns the Email's subject.""" return self['Subject'] @property def sender(self): """Returns the Email's sender.""" return self['From'] @property def recipient(self): """Returns the Email's recipient.""" return self['To'] class Mailer: """A simple SMTP mailer.""" def __init__( self, smtp_server: str, smtp_port: int, login_name: str, passwd: str, *, ssl: Optional[bool] = None, tls: Optional[bool] = None ): """Initializes the email with basic content.""" self.smtp_server = smtp_server self.smtp_port = smtp_port self.login_name = login_name self._passwd = passwd if ssl is not None: warn('Option "ssl" is deprecated. Use "tls" instead.', DeprecationWarning) self.ssl = ssl self.tls = tls def __call__(self, emails: Iterable[EMail]): """Alias to self.send().""" return self.send(emails) def __str__(self): return f'{self.login_name}:*****@{self.smtp_server}:{self.smtp_port}' @classmethod def from_section(cls, section: SectionProxy) -> Mailer: """Returns a new mailer instance from the provided config section.""" if (smtp_server := section.get( 'smtp_server', section.get('host') )) is None: raise ValueError('No SMTP server specified.') if (port := section.getint( 'smtp_port', section.getint('port') )) is None: raise ValueError('No SMTP port specified.') if (login_name := section.get( 'login_name', section.get('user') )) is None: raise ValueError('No login nane specified.')
{ "domain": "codereview.stackexchange", "id": 45576, "lm_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, email", "url": null }
python, python-3.x, email if (passwd := section.get('passwd', section.get('password'))) is None: raise ValueError('No password specified.') return cls( smtp_server, port, login_name, passwd, ssl=section.getboolean('ssl'), tls=section.getboolean('tls') ) @classmethod def from_config(cls, config: ConfigParser) -> Mailer: """Returns a new mailer instance from the provided config.""" return cls.from_section(config['email']) def _start_tls(self, smtp: SMTP) -> bool: """Start TLS connection.""" try: smtp.starttls() except (SMTPException, RuntimeError, ValueError) as error: LOGGER.error('Error during STARTTLS: %s', error) # If TLS was explicitly requested, re-raise # the exception and fail. if self.ssl or self.tls: raise # If TLS was not explicitly requested, return False # to make the caller issue a warning. return False return True def _start_tls_if_requested(self, smtp: SMTP) -> bool: """Start a TLS connection if requested.""" if self.ssl or self.tls or self.ssl is None or self.tls is None: return self._start_tls(smtp) return False def _login(self, smtp: SMTP) -> bool: """Attempt to log in at the server.""" try: smtp.ehlo() smtp.login(self.login_name, self._passwd) except SMTPException as error: LOGGER.error(str(error)) return False return True def send(self, emails: Iterable[EMail]) -> bool: """Sends emails.""" with SMTP(host=self.smtp_server, port=self.smtp_port) as smtp: if not self._start_tls_if_requested(smtp): LOGGER.warning('Connecting without SSL/TLS encryption.') if not self._login(smtp): return False return send_emails(smtp, emails)
{ "domain": "codereview.stackexchange", "id": 45576, "lm_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, email", "url": null }
python, python-3.x, email return send_emails(smtp, emails) def send_email(smtp: SMTP, email: EMail) -> bool: """Sends an email via the given SMTP connection.""" try: smtp.send_message(email) except SMTPException as error: LOGGER.warning('Could not send email: %s', email) LOGGER.error(str(error)) return False return True def send_emails(smtp: SMTP, emails: Iterable[EMail]) -> bool: """Sends emails via the given SMTP connection.""" return all({send_email(smtp, email) for email in emails}) @cache def get_qp_charset(charset: str) -> Charset: """Returns a quoted printable charset.""" qp_charset = Charset(charset) qp_charset.body_encoding = QP return qp_charset Answer: I noted the use of the := operator aka walrus. That means your code requires Python >= 3.8 so consider adding a guard to make sure this requirement is satisfied. Since you are aiming for recent versions of Python you could as well "upgrade" to a data class that will make your code more concise. Thus you could declare your class EMail like this: from dataclasses import dataclass @dataclass class EMail(MIMEMultipart): subject: str sender: str recipient: str plain: str html: str charset: str = 'utf-8' quoted_printable: bool = False in lieu if an __init__ method and you can use self.variable straight away without manual assignment. One additional benefit is that a __repr__() method is already implemented for you. The @property decorator can still be used casually: @property def subject(self) -> str: return self.subject Then you may want to use __post_init__ for additional initialization work eg: def __post_init__(self): text_type = MIMEQPText if quoted_printable else MIMEText if plain is not None: self.attach(text_type(plain, 'plain', charset)) if html is not None: self.attach(text_type(html, 'html', charset))
{ "domain": "codereview.stackexchange", "id": 45576, "lm_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, email", "url": null }
python, python-3.x, email if html is not None: self.attach(text_type(html, 'html', charset)) The downside of the data class is when you need positional or named arguments, so ask yourself if you need them or not. See this discussion for possible strategies plus this section of the docs. But note that the dataclass decorator has a kw_only argument: If true (the default value is False), then all fields will be marked as keyword-only This is a matter of personal preference but this code: def _login(self, smtp: SMTP) -> bool: """Attempt to log in at the server.""" try: smtp.ehlo() smtp.login(self.login_name, self._passwd) except SMTPException as error: LOGGER.error(str(error)) return False return True could be written as: def _login(self, smtp: SMTP) -> bool: """Attempt to log in at the server.""" try: smtp.ehlo() smtp.login(self.login_name, self._passwd) except SMTPException as error: LOGGER.error(str(error)) return False else: return True (I'm always wary of indentation in Python) Small typo on line 146: raise ValueError('No login nane specified.') SMTP login can be made optional as it's not always required, for example on a corporate LAN where local IP addresses are trusted (eg Postfix my_networks) or from some ISPs.
{ "domain": "codereview.stackexchange", "id": 45576, "lm_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, email", "url": null }
c++, functional-programming, c++17, template, template-meta-programming Title: Extending callable signature with std::optional in context of function composition (make_skippable) Question: (Please note: the post about the compose implementation announced below is now available.) This is about decorating callables by making their argument and return value to be a std::optional. Therefore I created the template function make_skippable that takes a callable and returns a wrapping lambda having an optional argument and an optional return value. Here a simple example of how to use this function: auto callable = [](auto arg) { return arg; }; auto skippable_callable = make_skippable(callable); std::optional<int> res1 = skippable_callable(static_cast<int>(1)); std::optional<int> res2 = skippable_callable(std::optional<int>{2}); std::optional<int> res3 = skippable_callable(std::optional<int>{}); The purpose of this functionality is to allow callables to be composed as a chain, whereby in the event that a callable doesn’t produce a result (by returning a std::nullopt), the chain breaks by skipping the processing of the subsequent callables (unless the callable is able to handle a std::nullopt). I will follow up on the compose implementation later in a separate review request. Below you will find the detailed requirements that the make_skippable implementation should fulfil: wrap a callable regardless of whether it already has an optional argument or an optional return value in case a nullopt argument occurs, only skip a callable that has a value argument, instead execute a callable that has an optional argument by forwarding the nullopt support all kinds callables having a single argument, including generic lambdas support perfect forwarding regarding argument and callable object c++17 Here the implementation itself: template <typename> struct IsOptional : std::false_type {}; template <typename T> struct IsOptional<std::optional<T>> : std::true_type {};
{ "domain": "codereview.stackexchange", "id": 45577, "lm_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++, functional-programming, c++17, template, template-meta-programming", "url": null }
c++, functional-programming, c++17, template, template-meta-programming template <typename TArg> auto ensure_optional(TArg&& arg) { if constexpr (IsOptional<std::decay_t<TArg>>::value) { return std::forward<TArg>(arg); } else { return std::make_optional(std::forward<TArg>(arg)); } } template <typename TFn> auto make_skippable(TFn&& fn) { return [fn = std::forward<TFn>(fn)](auto&& optional_or_value) { auto&& optional_arg = ensure_optional(std::forward<decltype(optional_or_value)>(optional_or_value)); using OptionalArg = decltype(optional_arg); constexpr bool invoke_with_optional = std::is_invocable_v<TFn, OptionalArg>; if constexpr (invoke_with_optional) { auto&& res = fn(std::forward<OptionalArg>(optional_arg)); return ensure_optional(std::forward<decltype(res)>(res)); } const bool invoke_with_value = optional_arg.has_value(); if (invoke_with_value) { auto&& value = std::forward<OptionalArg>(optional_arg).value(); auto&& res = fn(std::forward<decltype(value)>(value)); return ensure_optional(std::forward<decltype(res)>(res)); } // skip fn using ValueArg = typename std::decay_t<OptionalArg>::value_type; using Res = typename std::invoke_result<TFn, ValueArg>::type; if constexpr (IsOptional<Res>::value) { return Res{}; } else { return std::optional<Res>{}; } }; } Kudos to Jonathan Boccara who inspired me with his blog post The Optional Monad In C++, Without the Ugly Stuff - Fluent C++. Happy to receive any kind of feedback :-) This godbolt link refers to the implementation shown above and does also include tests.
{ "domain": "codereview.stackexchange", "id": 45577, "lm_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++, functional-programming, c++17, template, template-meta-programming", "url": null }
c++, functional-programming, c++17, template, template-meta-programming Answer: Design review This was a neat idea in 2017. I don’t think it’s really got the same shine in 2024. More recent C++ offers more and better options There are more “Maybe” types In C++17, std::optional was the only type that modelled “Maybe”; that is, a type that either holds a value, or “None”. Because it was the only game in town, it was abused. It was quite often used as a return type, where the “None” meant there was an error. Boccara actually makes that mistake in his post. He talks about “failable” functions… but returning an empty optional is not the correct way to indicate a failure. If a function returns an empty optional, that implies that the function succeeded… but just didn’t have any data to return. (For example, imagine a function get_nickname() that queries a database to get a person’s nickname; returning an empty optional would imply that everything succeeded, but the person just had no nickname.) As of C++23, we now have std::expected. This is the correct way to return a value-or-error. (In fact, get_nickname() should probably return expected<optional<string>, ...>. If the expected has a value, then the query succeeded… but the result might still be “no nickname” (an empty optional).) And there are even more “Maybe”-like types proposed for C++26, like std::nullable_view and std::maybe_view. So it is no longer safe to consider std::optional to be the only vocabulary type for modelling “Maybe”. You may object that because you are targeting C++17, those types are not relevant. But “targeting C++17” does not mean “ignoring everything that comes after”. If a library worked for C++17, and only C++17, and failed to work for any later standard, then it would be of little use. So at least you should consider making make_skippable() more generic, so that it can work with other “Maybe” types. Monads are the future
{ "domain": "codereview.stackexchange", "id": 45577, "lm_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++, functional-programming, c++17, template, template-meta-programming", "url": null }
c++, functional-programming, c++17, template, template-meta-programming Monads are the future As of C++23, std::optional got monadic operations. These can not only do what make_skippable() does more easily, they are far, far more powerful. I took your Godbolt example, and tweaked it a bit. Mostly, I just changed the compiler(s) and flags to be more up-to-date. (I also had to add default constructors for NonCopyableArg and NonCopyableFn.) Here is the modified Godbolt: https://godbolt.org/z/oaMzGo5P4. Then I took your tests, and replaced every call to a “skippable” with either an unwrapped direct call to the original lambda, or a monadic chain. I could have done all with an unwrapped direct call to the original lambda, or all with monadic operations, but I mixed half-and-half just for kicks. Here is the C++23 version: https://godbolt.org/z/jjzaxGYbo. Not only is the code simpler, take a look at the codegen. GCC is unable to strip away the optional wrapping in the make_skippable() version… but in the monadic version, the optionals are almost completely gone (some remain because they are returned, but even then, GCC recognized that they never fail, and stripped out the bad_optional_access). Clang does a decent job with both versions, but better with the monadic version. And the monadic interface is much more flexible. For example, it has .or_else(), to even allow handling the empty case. Is wrapping necessary? So, ultimately, all make_skippable() does is take any unary callable, and make sure both the argument and return type are std::optionals. But… does that make sense? What is the point of wrapping arguments? So let’s say you have a function auto f(int) -> std::string. What… exactly… is gained by wrapping the int in an optional? The logic seems to be that auto f_wrapped(std::optional<int>) -> std::optional<std::string> is easier to compose than auto f(int) -> std::string. However, the monadic operations show that is not true: auto result = get_optional_int() .transform(f) .and_then(to_upper) ;
{ "domain": "codereview.stackexchange", "id": 45577, "lm_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++, functional-programming, c++17, template, template-meta-programming", "url": null }
c++, functional-programming, c++17, template, template-meta-programming // ... works just as well as: auto result = get_optional_int() .and_then(f_wrapped) .and_then(to_upper) ; // ... except the latter has more complexity because it has to check // the optional int *twice*. Let me put this another way. Consider the implementation of make_skippable(): template <typename TFn> auto make_skippable(TFn&& fn) { return [fn = std::forward<TFn>(fn)](auto&& optional_or_value) { auto&& optional_arg = ensure_optional(std::forward<decltype(optional_or_value)>(optional_or_value)); using OptionalArg = decltype(optional_arg); constexpr bool invoke_with_optional = std::is_invocable_v<TFn, OptionalArg>; if constexpr (invoke_with_optional) { auto&& res = fn(std::forward<OptionalArg>(optional_arg)); return ensure_optional(std::forward<decltype(res)>(res)); } const bool invoke_with_value = optional_arg.has_value(); if (invoke_with_value) { auto&& value = std::forward<OptionalArg>(optional_arg).value(); auto&& res = fn(std::forward<decltype(value)>(value)); return ensure_optional(std::forward<decltype(res)>(res)); } // skip fn using ValueArg = typename std::decay_t<OptionalArg>::value_type; using Res = typename std::invoke_result<TFn, ValueArg>::type; if constexpr (IsOptional<Res>::value) { return Res{}; } else { return std::optional<Res>{}; } }; } The logic is: template <typename TFn> auto make_skippable(TFn&& fn) { return [fn = std::forward<TFn>(fn)](auto&& optional_or_value) { // Wrap value in optional. // If function takes optional argument: // * Call function. // Else: // * If the optional has a value: // - Unwrap value. // - Call function. // If we get here, function does not take optional, and // optional was empty, so return nullopt. }; }
{ "domain": "codereview.stackexchange", "id": 45577, "lm_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++, functional-programming, c++17, template, template-meta-programming", "url": null }
c++, functional-programming, c++17, template, template-meta-programming See the problem? If you are given a value (and not an optional), you wrap the value, do a pointless test (because you know the optional has a value), then unwrap it. Let’s flip the logic around: template <typename TFn> auto make_skippable(TFn&& fn) { return [fn = std::forward<TFn>(fn)](auto&& optional_or_value) { // If argument is not optional: // * Call function. // Else: // * If function takes optional argument: // - Call function. // * Else: // - If the optional has a value: // o Unwrap value. // o Call function // - Else: // o Return nullopt. }; } If the argument isn’t an optional, just call the function. Either the function takes a straight T, or an optional<T>. Doesn’t matter. If it takes a T, then… well, it has a T. If it takes a optional<T>, the copy/move construction from T is implicit, so… it just works. If the argument is an optional, then if the function takes an optional, just pass it through. If it doesn’t then you do the test, and only conditionally call the function. Like so: template <typename TFn> auto make_skippable(TFn&& fn) { return [fn = std::forward<TFn>(fn)](auto&& arg) { using Arg = decltype(arg); if constexpr (not IsOptional<std::remove_cvref_t<Arg>>::value) { return ensure_optional(fn(std::forward<Arg>(arg))); } else { if constexpr (std::is_invocable_v<TFn, Arg>) { return ensure_optional(fn(std::forward<Arg>(arg))); } else { if (optional_or_value) return ensure_optional(fn(std::forward<Arg>(arg).value())); else return decltype(ensure_optional(fn(std::forward<Arg>(arg).value()))){}; } } }; }
{ "domain": "codereview.stackexchange", "id": 45577, "lm_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++, functional-programming, c++17, template, template-meta-programming", "url": null }
c++, functional-programming, c++17, template, template-meta-programming The key point is that you never need to wrap the argument. If it’s an optional, it’s already wrapped. And if it’s not, wrapping is pointless: either the function will take the argument directly, or it will be implicitly wrapped. What is the point of wrapping return values? Wrapping the argument is unnecessary because it will be implicitly wrapped if needed. But what about the return value? Well, there is a different problem there. Consider the function auto f(int) -> string. If you wrap the return type, you get: auto g(int) -> optional<string>. Is this an improvement? No, in fact it is a terrible idea. Because the function auto f(int) -> string is safe and easy to use. It’s just auto s = f(42); and then s is always safe to use. But auto g(int) -> optional<string> is more complex and dangerous, because you always have to do: auto temp = g(42); if (temp) { auto s = *temp; /* !!! */ }, and s is only safe to use in the scope marked !!!. So the mere act of wrapping a function makes using the result: slower more complex more dangerous … and the benefit is… composability? It had better be really nice composability. Unconditional wrapping is inflexible make_skippable() unconditionally wraps return values, even when there is no possibility of failure. Even if the function is auto f(optional<T>) -> U, meaning I am 100% guaranteed to get a U result, no matter what, even if there is no T, make_skippable() will turn that into optional<U>, with all the extra complexity and cost that brings with it. As written, make_skippable() also unconditionally wraps the argument, but I showed that doesn’t need to be the case. There is another, deeper problem though. When I have an int or a “Maybe(int)”… that is, optional<int>, and I am applying some function f to it that returns double or a “Maybe(double)” (optional<double>), there are several possible outcomes: f Value argument (int) Maybe argument (optional<int>) Always gives result double optional<double>
{ "domain": "codereview.stackexchange", "id": 45577, "lm_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++, functional-programming, c++17, template, template-meta-programming", "url": null }
c++, functional-programming, c++17, template, template-meta-programming f Value argument (int) Maybe argument (optional<int>) Always gives result double optional<double> May not give result optional<double> ??? What should I get in that last quadrant? make_skippable()’s answer is optional<double>. That might be right, but consider the following program: #include <optional> #include <type_traits> auto f(int) -> std::optional<double> { return 1.0; } auto g(int) -> std::optional<double> { return 2.0; } auto main() -> int { auto v1 = std::optional{1} .transform(f) ; auto v2 = std::optional{1} .and_then(g) ; static_assert(std::is_same_v<decltype(v1), std::optional<std::optional<double>>>); static_assert(std::is_same_v<decltype(v2), std::optional<double>>); }
{ "domain": "codereview.stackexchange", "id": 45577, "lm_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++, functional-programming, c++17, template, template-meta-programming", "url": null }
c++, functional-programming, c++17, template, template-meta-programming Note that when I use .transform(), the return type is always wrapped, even if it is already an optional. With .and_then() the return type is never wrapped (but it must always be an optional). I can choose whether or not I want optional<double> or optional<optional<double>> simply by selecting which monadic operation to apply. I might want optional<optional<double>>, because it gives me more information. For example, if .has_value() is false, then I know the original optional<int> argument was nullopt… but if .has_value() is true but .value().has_value() is false, then I know the original argument had an int value, but f() did not give a result. Note that I can’t get plain double, because these are monadic operations, meaning the argument is always (effectively) optional<int>. This is different from the situation with make_skippable(), where sometimes the argument is int, and the extra wrapping is pointless. If the function is auto func(int) -> double, then it makes sense to wrap the result if the argument is optional<int> (this is .transform()), but it is silly to wrap the return value if the argument is int. So with optional’s monadic operations, I can chose whether I want optional<double> or optional<optional<double>>. (But I can’t choose just double, because we’re only starting with optional<int>, not int. If I wanted it, I would get double by just not wrapping the known int in an optional to begin with.) So with make_skippable(), how could I choose whether I want double, optional<double>, or optional<optional<double>>? Conclusion This idea was great back in 2017… nowadays I’m not so sure. What might save it is the composability, which you promise “later”. It would have to be pretty good to beat the composability of the monadic operations… but that could happen. Without considering composability, what make_skippable() amounts to is a wrapper function of dubious utility.
{ "domain": "codereview.stackexchange", "id": 45577, "lm_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++, functional-programming, c++17, template, template-meta-programming", "url": null }
c++, functional-programming, c++17, template, template-meta-programming It makes no sense to wrap non-optional arguments. It makes no sense to wrap non-optional return values. The only argument for either of those things is… something-something composition. So I can’t really say with any certainty whether this design is actually worthwhile or not, without seeing the composition in action.
{ "domain": "codereview.stackexchange", "id": 45577, "lm_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++, functional-programming, c++17, template, template-meta-programming", "url": null }
javascript, mathematics, combinatorics Title: Combinations of elements in array Question: I wrote this code to get all possible arrangements for an array containing 3 elements: let a = ["A", "B", "C"]; let b = []; function change(A) { let x = []; for (let i = 0; i < A.length; i++) { x.push(A[i]); } for (let i = 0; i < x.length; i++) { A[i] = x[i + 1]; if (i == (x.length - 1)) { A[i] = x[0]; } } } function combinations() { for (let i = 0; i < a.length; i++) { b.push([a[0], a[1], a[2]]); b.push([a[0], a[2], a[1]]); change(a); } console.log(b); } combinations(); How can I write this more concisely, and how is it possible to get all possible arrangements of an array consisting of more than 3 elements? Answer: Firstly, style looks good. Indentation, spacing, etc. is good. Common mistakes include indenting code inconsistently or in a way that does not match the scope of the code, your code does not have those issues. change() All this appears to do is move the first element to the last place and shift all the other elements down by 1. You could do this without creating a separate array: function change(A) { let tmp = A[0]; for (let i = 0; i < A.length - 1;) { A[i] = A[++i]; } A[A.length - 1] = tmp; } Remove the if in the loop in change() regardless But if you wanted to use the method that creates a temporary copy of the original array, instead of checking for the last iteration of the loop: for (let i = 0; i < x.length; i++) { A[i] = x[i + 1]; if (i == (x.length - 1)) { A[i] = x[0]; } } Just move the statement outside the loop (and make the loop iterate one less time because you will overwrite the value anyway): for (let i = 0; i < x.length - 1; i++) { A[i] = x[i + 1]; } A[x.length - 1] = x[0];
{ "domain": "codereview.stackexchange", "id": 45578, "lm_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, mathematics, combinatorics", "url": null }
javascript, mathematics, combinatorics combinations() and global variables combinations() simply accesses a global array hardcoded in the function. Defining a function that takes no arguments and immediately calling it once is not really better than just having the function body by itself. For better practice and code reuse, you should make combinations() accept an array parameter: function combinations(A) { let b = []; for (let i = 0; i < A.length; i++) { b.push([A[0], A[1], A[2]]); b.push([A[0], A[2], A[1]]); change(A); } console.log(b); } Additionally, b was not used outside combinations() so should be a local variable instead. Revised: function change(A) { let tmp = A[0]; for (let i = 0; i < A.length - 1;) { A[i] = A[++i]; } A[A.length - 1] = tmp; } function combinations(A) { let b = []; for (let i = 0; i < A.length; i++) { b.push([A[0], A[1], A[2]]); b.push([A[0], A[2], A[1]]); change(A); } console.log(b); } combinations(["A", "B", "C"]); As for finding the combinations of arrays larger than 3, you already have a way to do this with arrays of 3, so for one additional element, you could insert that in each one of the possible positions in each one of the existing combinations. You could implement a recursive approach to handle an arbitrary number of elements.
{ "domain": "codereview.stackexchange", "id": 45578, "lm_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, mathematics, combinatorics", "url": null }
performance, c, benchmarking Title: Benchmarking putchar_many vs puts Performance for the Same Byte Question: Whilst writing an interpreter for Brainfuck, I had collapsed sequences of .......... to a single instruction OP_PUT (10) (Note that the . instruction in Brainfuck corresponds to a putchar() call in C. Say the byte at the current cell in Brainfuck was 'h', OP_PUT (10) would print h to stdout 10 times). In doing so, I had wondered what the performance difference would be in calling putchar() 10 times vs building a string of length 10 and calling puts() once. Here's the code I wrote to benchmark the performance: #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdint.h> #include <inttypes.h> #include <float.h> #include <time.h> #include <sys/time.h> #define MCS_TO_SEC(microseconds) ((double)(microseconds) / 1000000.0) typedef uint64_t timestamp_t; static inline void putchar_many(size_t count, const char str[static count]) { for (int i = 0; i < count; i++) { putchar(str[i]); } } static char *generate_str(size_t size, int c) { char *const str = malloc(size + 1); if (str) { memset(str, c, size); str[size - 1] = '\0'; } return str; } static timestamp_t get_posix_clock_time_fallback(void) { struct timeval tv; if (gettimeofday (&tv, NULL) == 0) { return (timestamp_t) (tv.tv_sec * 1000000 + tv.tv_usec); } return 0; } /* Reference: https://stackoverflow.com/a/37920181/20017547 */ static timestamp_t get_posix_clock_time(void) { #ifdef _POSIX_MONOTONIC_CLOCK struct timespec ts; if (clock_gettime (CLOCK_MONOTONIC, &ts) == 0) { return (timestamp_t) (ts.tv_sec * 1000000 + ts.tv_nsec / 1000); } return get_posix_clock_time_fallback(); #else return get_posix_clock_time_fallback(); #endif /* _POSIX_MONOTONIC_CLOCK */ } static inline timestamp_t get_clock_difftime(timestamp_t t0, timestamp_t t1) { return t1 - t0; }
{ "domain": "codereview.stackexchange", "id": 45579, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "performance, c, benchmarking", "url": null }
performance, c, benchmarking static inline timestamp_t get_clock_difftime(timestamp_t t0, timestamp_t t1) { return t1 - t0; } static void benchmark_puts_vs_putchar_many(size_t strlen) { char *const str = generate_str(strlen, 'X'); if (str == NULL) { perror("malloc()"); exit(EXIT_FAILURE); } timestamp_t t0 = get_posix_clock_time(); puts(str); timestamp_t t1 = get_posix_clock_time(); double puts_msecs = get_clock_difftime(t0, t1); timestamp_t t2 = get_posix_clock_time(); putchar_many(strlen, str); timestamp_t t3 = get_posix_clock_time(); double putchar_msecs = get_clock_difftime(t2, t3); fprintf(stderr, "| %-11zu | %-21.*f | %-29.*f |\n", strlen, FLT_DECIMAL_DIG, MCS_TO_SEC(puts_msecs), FLT_DECIMAL_DIG, MCS_TO_SEC(putchar_msecs)); free(str); } int main(void) { fprintf(stderr, "|-------------|-----------------------|-------------------------------|\n" "| String Size | Time (puts) (seconds) | Time (putchar_many) (seconds) | \n" "|-------------|-----------------------|-------------------------------|\n"); benchmark_puts_vs_putchar_many(1); benchmark_puts_vs_putchar_many(2); benchmark_puts_vs_putchar_many(5); benchmark_puts_vs_putchar_many(10); benchmark_puts_vs_putchar_many(100); benchmark_puts_vs_putchar_many(1000); benchmark_puts_vs_putchar_many(10000); benchmark_puts_vs_putchar_many(100000); benchmark_puts_vs_putchar_many(1000000); benchmark_puts_vs_putchar_many(10000000); benchmark_puts_vs_putchar_many(100000000); benchmark_puts_vs_putchar_many(1000000000); benchmark_puts_vs_putchar_many(10000000000); benchmark_puts_vs_putchar_many(100000000000); benchmark_puts_vs_putchar_many(1000000000000); fprintf(stderr, "|-------------|-----------------------|-------------------------------|\n"); return EXIT_SUCCESS; }
{ "domain": "codereview.stackexchange", "id": 45579, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "performance, c, benchmarking", "url": null }
performance, c, benchmarking Compiled with -O3 -march=native, these are the results: |-------------|-----------------------|-------------------------------| | String Size | Time (puts) (seconds) | Time (putchar_many) (seconds) | |-------------|-----------------------|-------------------------------| | 1 | 0.000040000 | 0.000001000 | | 2 | 0.000000000 | 0.000001000 | | 5 | 0.000001000 | 0.000000000 | | 10 | 0.000000000 | 0.000001000 | | 100 | 0.000000000 | 0.000002000 | | 1000 | 0.000001000 | 0.000011000 | | 10000 | 0.000009000 | 0.000229000 | | 100000 | 0.000017000 | 0.001388000 | | 1000000 | 0.000224000 | 0.013781000 | | 10000000 | 0.002739000 | 0.125450000 | | 100000000 | 0.021062000 | 1.188414000 | | 1000000000 | 0.204244000 | 12.139592000 | malloc(): Cannot allocate memory and some system information: OS: Linux Mint 21.2 x86_64 Host: VMware Virtual Platform None Kernel: 5.15.0-94-generic CPU: Intel i5-8350U (2) @ 1.896GHz GPU: 00:0f.0 VMware SVGA II Adapter Memory: 791MiB / 2933MiB Review Request: Are the calculations and the functions for determining the execution time of the functions correct? How can I improve the benchmarking code?
{ "domain": "codereview.stackexchange", "id": 45579, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "performance, c, benchmarking", "url": null }
performance, c, benchmarking Answer: If you really are trying to output one character n times, and not n distinct characters, I would make putchar_many take the count and the char only. And then charge the allocation/free time to the puts() variant. puts() also puts a newline. If you don't want that, use fputs(). (At which point, you might what putc() instead of putchar(), just to be equivalent.) Also test with fwrite(). It should be faster than fputs, as it doesn't do a strlen(). Also test with write(). It should be faster still. You should be invoking fflush(stdout) to finish the output. This should be charged to each variant. You should experiment with the buffer sizes (setvbuf()) Also, generate_str() is buggy in the line str[size - 1] = '\0'; There should be no -1. (Or was that compensation for the newline?) There is a question of where you are sending the output. Are you redirecting to /dev/null? (you should be.) There is also an issue of granularity of time. You should also be repeating each test many times. Perhaps target at least 5 seconds in each test. The overhead times (malloc/memset/free/fflush) might or might not be repeated, depending on your use case. And finally, the problem. I just checked my systems (GCC 10.2.1, GLIBC 2.31;also GCC 4.7, GLIBC 2.13), and the implementation of putc() and putchar() are defective (at least as far as I am concerned). They are supposed to be macros. Back in version 7 Unix, they were macros. (I remember being fascinated by the implementation.) They are supposed to be FAST. Now, because of threading and/or C++ and/or other extension issues, they are just function calls. Thus, the slowness you are seeing with putchar() is all the function calls.
{ "domain": "codereview.stackexchange", "id": 45579, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "performance, c, benchmarking", "url": null }
python, algorithm, validation, finance, checksum Title: Simple credit card validation with Luhn's Algorithm Question: Originally written in C (which was abysmal, you may check here if you want), I rewrote my simple credit card validation program using Python def main(): # Prompts user for card number nums = int(input("Number: ")) if len(str(nums)) > 16 or len(str(nums)) < 12: print("INVALID") else: card_classify(card_luhn(nums), nums) # Luhn's Algorithm def card_luhn(nums): tmp = str(nums) digit_sum = 0 # Loops through the digits that needs to be multiplied by 2 for i in range(2, len(tmp) + 1, 2): digits = 2 * int(tmp[-i]) # Condition if resulting product has 2 digits if_sum = 0 if len(str(digits)) == 2: for digit in str(digits): if_sum += int(digit) digits = 0 if_sum += digits digit_sum += if_sum # Loops through the digits that does not need to be multiplied by 2 for i in range(1, len(tmp) + 1, 2): digits = int(tmp[-i]) digit_sum += digits if digit_sum % 10 == 0: return 0 else: return 1 # Classifies the card whether AMEX, VISA, or MASTERCARD def card_classify(check, nums): num = int(str(nums)[:2]) if check != 0: print("INVALID") # AMEX condition (first two digits from left are either 37 or 34) elif num == 37 or num == 34: print("AMEX") # VISA condition (first digit from left is 4) elif str(num)[:1] == "4": print("VISA") # MASTERCARD condition (first two digits from left are between 50 and 56) elif num > 50 and num < 56: print("MASTERCARD") else: print("INVALID") if __name__ == "__main__": main()
{ "domain": "codereview.stackexchange", "id": 45580, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, algorithm, validation, finance, checksum", "url": null }
python, algorithm, validation, finance, checksum else: print("INVALID") if __name__ == "__main__": main() Could someone please review my code if it follows good practice and style? I want to be more Pythonic as I continue to learn. I also think that my implementation of Luhn's Algorithm could be improved, considering I looped over the card number twice. Answer: Getting the First 2 Digits of a Number A solution for this in constant space and time is already documented in this answer: from math import log10 # go from this num = int(str(nums)[:2]) # to this def leading_digits(num): return num // 10 ** (int(math.log10(num)) - 1) And checking for a type of card lends itself to using a dictionary Credit Card Types Replace your if/elif statements with a dictionary: card_types = { 37: 'AMEX', 34: 'AMEX', } card_types.update({i: 'MASTERCARD' for i in range(51, 56)}) # these all start with 4 card_types.update({i: 'VISA' for i in range(40, 50)}) try: card_type = card_types[leading_digits(num)] except KeyError: print("Invalid card type!") card_luhn I don't think this is a good name for this function. I think it's better as is_valid_card, which implies returning a boolean, which is technically being done here. I'd change the return to more explicitly be either True or False: # instead of this if digit_sum % 10 == 0: return 0 else: return 1 # do this return bool(digit_sum % 10) Checking for Two-Digit Numbers You already know what the 2-digit numbers are, they are all in the range 10 <= x <= 99. So a comparison test here is the answer: # go from this if len(str(digits)) == 2: # to this if 9 < digits < 100: Determining the Number of Digits in an Integer Here is a good answer for that. It avoids casting to string unnecessarily Getting each digit in a number Using the previous point, we can construct a function that will give us each digit in the number provided: from math import log10, ceil
{ "domain": "codereview.stackexchange", "id": 45580, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, algorithm, validation, finance, checksum", "url": null }
python, algorithm, validation, finance, checksum def get_digits(number): if not number: yield 0 return elif number < 0: # for a solution that processes negative numbers # however, for your case, it might be better to # raise a ValueError here number *= -1 num_digits = ceil(log10(number)) for _ in range(num_digits): digit = (number % 10) yield digit number //= 10 This has a few benefits: You aren't casting to string, avoiding unnecessary overhead This gives you the digits in the order you want (right to left) No more index lookups We can use itertools.islice to get an iterator from digit 2 onward in steps of 2: # go from this: for i in range(2, len(tmp) + 1, 2): # to this # islice takes arguments: # iterator, start, stop, step for digit in islice(get_digits(nums), 2, None, 2): Unfortunately, islice doesn't take keyword arguments, so a comment might be useful to remind yourself what the arguments are This same snippet can be used on the odd digits as well. Looping once As you mentioned, you only need to iterate once over the digits, and you can use enumerate to track if you're on an even or odd index: digits_iter = islice(get_digits(card_number), 1, None) for i, digit in enumerate(digits_iter, start=1): if i % 2: # odd else: # even Refactoring card_luhn from math import log10, ceil from itertools import islice from typing import Iterator def get_digits(number: int) -> Iterator[int]: """Yields the digits of an integer from right to left""" if not number: yield 0 # stops the generator return elif number < 0: # for a solution that processes negative numbers # however, for your case, it might be better to # raise a ValueError here number *= -1 num_digits = ceil(log10(number)) for _ in range(num_digits): digit = (number % 10) yield digit number //= 10
{ "domain": "codereview.stackexchange", "id": 45580, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, algorithm, validation, finance, checksum", "url": null }
python, algorithm, validation, finance, checksum yield digit number //= 10 def is_valid_card(card_number: int) -> bool: """Uses Luhn's algorithm to determine if a credit card number is valid""" digit_sum = 0 digits_iter = islice(get_digits(card_number), 1, None) for i, digit in enumerate(digits_iter, start=1): # process odd digits if i % 2: digit_sum += digit continue doubled = 2 * digit # Condition if resulting product has 2 digits if 10 <= doubled <= 99: digit_sum += sum(get_digits(doubled)) else: digit_sum += doubled return bool(digit_sum % 10) Quite a few changes here. First, note I'm checking if the index is odd or even with the i % 2 operation. The continue keyword allows me to skip the rest of the loop body and go on to the next iteration. Next, I renamed digits to doubled, since digits isn't really what it is, it's twice the value of a digit. I'm using the int comparison operation to test if doubled is in a given range, which is fast and very readable. I've gotten rid of the if_sum temporary variable, simply sum the digits returned by the iterator and add that sum to digit_sum. Last, I'm returning a bool, so you get an explicit True or False from the function. I've also added type hints and some short docstrings to help with readability. card_classify Let's reorder these to classify_card. I don't think check needs to be a variable here. Call the is_valid_card function inside that function. It's easier to see what's happening that way: def classify_card(card_number: int) -> None: """Classifies a card as AMEX, VISA, MASTERCARD or INVALID""" # test if the card number is valid if not is_valid_card(card_number): print("INVALID") return card_types = { 37: 'AMEX', 34: 'AMEX', }
{ "domain": "codereview.stackexchange", "id": 45580, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, algorithm, validation, finance, checksum", "url": null }
python, algorithm, validation, finance, checksum card_types = { 37: 'AMEX', 34: 'AMEX', } card_types.update({i: 'MASTERCARD' for i in range(51, 56)}) # these all start with 4 card_types.update({i: 'VISA' for i in range(40, 50)}) try: card_type = card_types[leading_digits(num)] except KeyError: print("INVALID") else: print(card_type) main I'd postpone your integer conversion of the input string, since it's really easy to test the length while it's still a str: def main(): card_num = input("Number: ") if len(card_num) not in range(12, 17): print('INVALID') else: classify_card(int(card_num)) And I would move main towards the bottom of the script.
{ "domain": "codereview.stackexchange", "id": 45580, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, algorithm, validation, finance, checksum", "url": null }
c++, game, console Title: Terminal based game Question: Looking to build a terminal based game. I am assuming X-Term like terminal. This means: I can use the X-Term control codes to clear and move around the screen. I can use tcsetattr functions to make standard input none buffered (I think). I know this game loop runs as basically a busy wait. I will sove that at the select() command by adding the appropriate timeout there (I just need to calculate an appropriate value). Note: I installed the signal handlers so that when the application is being forced to quit I can still restore the terminal to its original state before the application quite. You will notice the std::cout << showCursor; to turn the cursor back on and the destructor sets the terminal state back to its original value: tcsetattr(STDIN_FILENO, TCSAFLUSH, &originalConfig); This is the shell for my game (I have not implemented game logic). I wanted to make sure I am not messing stuff up around display and terminal manipulation before I go any further. #include <iostream> #include <signal.h> #include <termios.h> #include <stdio.h> #include <unistd.h> static volatile sig_atomic_t done = 0; extern "C" void handle_done(int signum) { if (!done) { done = signum; } } class Game { static constexpr int width = 40; static constexpr int height = 20; static constexpr char clearScreen[] = "\033[2J"; static constexpr char movetoZeroZero[] = "\033[0;0H"; static constexpr char hideCursor[] = "\033[?25l"; static constexpr char showCursor[] = "\033[?25h"; termios originalConfig; bool gameOver;
{ "domain": "codereview.stackexchange", "id": 45581, "lm_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++, game, console", "url": null }
c++, game, console termios originalConfig; bool gameOver; char getChar(int x, int y) { if (y == 0 || y == height -1 || x == 0 || x == width -1 ) { return '#'; } return ' '; } void draw(bool dirty) { std::cout << movetoZeroZero << "Snake V1\n"; for (int y = 0; y < height; ++y) { for (int x = 0; x < width; ++x) { std::cout << getChar(x, y); } std::cout << "\n"; } std::cout << std::flush; } bool input() { if (done) { gameOver = true; } fd_set input; FD_ZERO(&input); FD_SET(STDIN_FILENO, &input); timeval timeout{0, 0}; if (select(STDIN_FILENO+1, &input, nullptr, nullptr, &timeout) > 0) { char key = std::cin.get(); if (key == 'Q') { gameOver = true; } } return false; } bool logic() { return false; } int install_done(const int signum) { struct sigaction act {0}; memset(&act, 0, sizeof act); sigemptyset(&act.sa_mask); act.sa_handler = handle_done; act.sa_flags = 0; if (sigaction(signum, &act, NULL) == -1) { return errno; } return 0; } public: Game() : gameOver(false) { if (install_done(SIGINT) || install_done(SIGTERM) || install_done(SIGHUP)) { throw std::runtime_error("Fail: Installing handlers\n"); } termios config; if (!isatty(STDIN_FILENO) || tcgetattr(STDIN_FILENO, &originalConfig) || tcgetattr(STDIN_FILENO, &config)) { throw std::runtime_error("Fail: Setting up input stream\n"); }
{ "domain": "codereview.stackexchange", "id": 45581, "lm_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++, game, console", "url": null }
c++, game, console config.c_lflag &= ~(ICANON | ECHO); config.c_cc[VMIN] = 1; /* Blocking input */ config.c_cc[VTIME] = 0; tcsetattr(STDIN_FILENO, TCSANOW, &config); } ~Game() { tcsetattr(STDIN_FILENO, TCSAFLUSH, &originalConfig); } void run() { std::cout << clearScreen << hideCursor; bool dirty = true; while (!gameOver) { draw(dirty); dirty = input(); dirty = logic() || dirty; } std::cout << showCursor; } }; int main() { Game game; game.run(); } Answer: Use a curses library or something similar There are many details to worry about when writing low-level terminal code. I strongly recommend you use a library that takes away that burden, and that will let you focus more on writing the game itself. I would recommend that you use a curses library, like ncurses. The API is standardized, and while ncurses is perhaps the most well-known one for UNIX, there are curses libraries for other operating systems as well, including Windows. Curses provides functions to hide the cursor, clear the screen, draw only changed portions of the screen, and even handle keyboard input, so it covers everything you already do in the code you posted. It will probably also cover many things you will need in the future. However, there are other terminal libraries as well that can go even further, for example FTXUI.
{ "domain": "codereview.stackexchange", "id": 45581, "lm_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++, game, console", "url": null }
c++, beginner, game-of-life Title: Game of life code in C++ Question: Does my code for game of life look good enough? What changes can I make to optimize the code? I am a beginner to java and I've coded the Game of Life! For those not familiar, the game entails creating a grid of specified dimensions with each box in the grid being either dead or alive. The grid starts with a random dead or alive state for each box. New generations have new dead/alive boxes based on the following conditions: If there are 3 alive boxes neighbouring any dead box, it becomes alive. If there are less than 2 alive boxes neighbouring an alive box, that box dies. It also dies if there are more than 3 alive boxes around it. #include<cstdlib> #include<ctime> const int Grid_Width = 10; const int Grid_Height = 10; int Grid [Grid_Width][Grid_Height]; //2-D array to hold the grids //initialize grid with random cell states void initializegrid() { std::srand(std::time(nullptr)); //seed the random number generator for(auto i=0; i<Grid_Width;++i){ for(auto j=0; j<Grid_Height; ++j){ Grid[i][j]=std::rand() % 2; //gives each cell a value of 1 or 0 } } } //function to print the grid to the console void print_grid() { for(auto i=0; i<Grid_Width;++i){ for(auto j=0; j<Grid_Height; ++j){ std::cout<< (Grid[i][j] == 1 ? "*" : ".")<<" "; //print * for live cell and . for dead one } std::cout<<std::endl; } } //function to count live neihghbour int countliveNeighbour( int x, int y){ int count =0; for(auto i=-1; i<=1; ++i){ for(auto j=-1; j<=1; ++j){ //covering 3X3 grid int neighbourX = x + i; int neighbourY = y + j; if(i==0 && y==0) continue; //skipping the cell itself if(neighbourX>=0 && neighbourX< Grid_Width && neighbourY>=0 && neighbourY< Grid_Height ){ count+= Grid[neighbourX][neighbourY]; } } } return count; }
{ "domain": "codereview.stackexchange", "id": 45582, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, beginner, game-of-life", "url": null }
c++, beginner, game-of-life //function to update the grid based on the rules of the game void updateGrid(){ int newGrid[Grid_Width][Grid_Height]; for(auto i=0; i<Grid_Width; ++i){ for(auto j=0; j<Grid_Height; ++j){ int liveNeighbours = countliveNeighbour(i,j); if(Grid[i][j]==1){ if(liveNeighbours <2 || liveNeighbours >3){ newGrid[i][j]=0; //cell dies due to underpopulation }else{ newGrid[i][j]=1; } }else{ if(liveNeighbours ==3){ newGrid[i][j]=1; //cell becomes alive due to overpopulation }else{ newGrid[i][j]=0; //remains dead } } } } //update the old grid with the new grid for(auto i=0; i<Grid_Width; ++i){ for(auto j=0; j<Grid_Height; ++j){ Grid[i][j]=newGrid[i][j]; } } } int main(){ initializegrid(); print_grid(); updateGrid(); print_grid(); } Answer: Everything Toby Said. So not going to repeat those. Added: Game play improvement: I would not do this. It means that that things die off at the edges of the grid. if(neighbourX>=0 && neighbourX< Grid_Width && neighbourY>=0 && neighbourY< Grid_Height ){ count+= Grid[neighbourX][neighbourY]; } I would rather think of the grid as wrapping around on both the X and Y axis. That way life things like gliders will wrap around the edge rather than die as they hit the edge. Try this: count+= Grid[neighbourX % Grid_Width][neighbourY % Grid_Height]; Can't remember the exact rules on % and negative number you should test. But if it does not work as expected you can fix like this: count+= Grid[(neighbourX + Grid_Width) % Grid_Width][(neighbourY + Grid_Height) % Grid_Height];
{ "domain": "codereview.stackexchange", "id": 45582, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, beginner, game-of-life", "url": null }
c++, beginner, game-of-life A lot of life games produces output that would go out of the viable area quickly and thus leave a boring blank screen, this will allow the simulation a better chance of continuing. I personally dislike global state (the mutable kind anyway). It makes debugging a lot harder when you have to worry about state that is not part of your function. So rather than: const int Grid_Width = 10; const int Grid_Height = 10; int Grid [Grid_Width][Grid_Height]; //2-D array to hold the grids I would prefer you wrap this in a class and create an instance of the class in main(). class Life { constexpr int Grid_Width = 10; constexpr int Grid_Height = 10; int Grid [Grid_Width][Grid_Height]; //2-D array to hold the grids public: Life() // Initialize here once. // etc }; Rather than using a C-Array: int Grid [Grid_Width][Grid_Height]; I would probably go with a std::vector<> I would probably use bool rather than int for storage. I think this would work (But I am not going to look it up). But the standard optimizes space for std::vector<bool> and not all functionality works exactly the same, so if it does not work as expected change bool to int. std::vector<std::vector<bool>> grid; // // In constructor Life() : grid(Grid_Width, std::vector<int>(Grid_Height, false)); {} This makes things like copying simpler and your updateGrid could have one loop removed with and simply assign the arrays. //update the old grid with the new grid grid = std::move(newGrid); In the update grid I would have done it slightly differently. I would have initialized all the members to 0. Then the code only needs to worry about updating the cells that are going to be live. I think this simplifies the code. And use a named function to make the decision. bool isAlive(int currentState, int liveNeighbours) { return (currentState == 1 && (liveNeighbours == 2 || liveNeighbours == 3) || (currentState == 0 && liveNeighbours == 3); }
{ "domain": "codereview.stackexchange", "id": 45582, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, beginner, game-of-life", "url": null }
c++, beginner, game-of-life void updateGrid(){ // Initialize grid to all zero. int newGrid[Grid_Width][Grid_Height] = {0}; // Find live squares. for(auto i=0; i<Grid_Width; ++i){ for(auto j=0; j<Grid_Height; ++j){ int liveNeighbours = countliveNeighbour(i,j); if (isAlive(grid[i][j], liveNeighbours)) { newGrid[i][j] = 1; } } } //update the old grid with the new grid for(auto i=0; i<Grid_Width; ++i){ for(auto j=0; j<Grid_Height; ++j){ Grid[i][j]=newGrid[i][j]; } } }
{ "domain": "codereview.stackexchange", "id": 45582, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, beginner, game-of-life", "url": null }
python, graph Title: Graphs for distributing rewards Question: I want to be able to distribute a total reward among referral network, where the distribution diminishes according to the depth of the network but the total sum of distributed rewards equals the initial total reward. I have attempted to use Graphs as a way to solve this. With the assumptions that: Give a fixed percentage of the total reward to the direct referrer. Distribute the remaining reward down the referral chain in decreasing amounts. The goal is for Node1 to receive 20% of the total reward off the top, with the remaining 80% distributed among all nodes, with decreasing amounts based on their distance from Node1. I want to also be able to support circular referrals and self referrals. Code: import networkx as nx import matplotlib.pyplot as plt def distribute_rewards( graph: nx.DiGraph, start_node: str, total_reward: float, direct_referral_ratio: float, decrease_factor: float ) -> None: """ Distributes rewards within a referral network. Args: graph (nx.DiGraph): The referral network graph. start_node (str): The node from which distribution starts. total_reward (float): Total reward amount to distribute. direct_referral_ratio (float): Ratio of the total reward given to the start node. decrease_factor (float): Factor by which the reward decreases at each level. """ nx.set_node_attributes(graph, 0, 'reward') direct_reward = total_reward * direct_referral_ratio graph.nodes[start_node]['reward'] = direct_reward remaining_reward = total_reward - direct_reward level_weights: dict[int, float] = {} queue: list[tuple[str, int]] = [(start_node, 0)] visited: set[str] = {start_node} while queue: node, level = queue.pop(0) level_weights.setdefault(level, 0) level_weights[level] += decrease_factor ** level
{ "domain": "codereview.stackexchange", "id": 45583, "lm_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, graph", "url": null }
python, graph for neighbor in graph.successors(node): if neighbor not in visited: visited.add(neighbor) queue.append((neighbor, level + 1)) total_weight = sum(level_weights.values()) level_rewards = { level: (remaining_reward * weight) / total_weight for level, weight in level_weights.items() } for node in graph.nodes: level = nx.shortest_path_length(graph, source=start_node, target=node) if level in level_rewards: num_nodes_at_level = sum( 1 for n in graph.nodes if nx.shortest_path_length(graph, source=start_node, target=n) == level ) graph.nodes[node]['reward'] += level_rewards[level] / num_nodes_at_level def create_complex_graph(max_levels: int) -> nx.DiGraph: """ Creates a binary tree graph representing a referral network. Args: max_levels (int): The maximum depth of the referral network. Returns: nx.DiGraph: The generated referral network graph. """ graph = nx.DiGraph() for level in range(max_levels): for i in range(2**level): parent = f'Node{2**level + i}' children = [f'Node{2**(level + 1) + 2*i}', f'Node{2**(level + 1) + 2*i + 1}'] for child in children: graph.add_edge(parent, child) return graph def visualize_graph(graph: nx.DiGraph): layout = nx.spring_layout(graph, k=0.5, iterations=20) node_sizes = [graph.nodes[node]['reward'] / 10 for node in graph] # Draw nodes and edges nx.draw_networkx_nodes(graph, layout, node_size=node_sizes, node_color='skyblue', edgecolors='black') nx.draw_networkx_edges(graph, layout, arrows=True) # Draw node labels nx.draw_networkx_labels(graph, layout, font_size=8) # Remove axis for a cleaner look and display the graph plt.axis('off') plt.show()
{ "domain": "codereview.stackexchange", "id": 45583, "lm_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, graph", "url": null }
python, graph # Remove axis for a cleaner look and display the graph plt.axis('off') plt.show() def main() -> None: max_levels = 5 total_reward = 3500 direct_referrer = 'Node1' # From the POV that Node1 is the direct referrer. direct_referral_ratio = 0.2 # 20% decrease_factor = 0.5 # 50% graph = create_complex_graph(max_levels) distribute_rewards(graph, direct_referrer, total_reward, direct_referral_ratio, decrease_factor) for node in sorted(graph.nodes, key=lambda x: int(x.lstrip('Node'))): print(f"{node}: Reward = {graph.nodes[node]['reward']:.2f}") visualize_graph(graph) if __name__ == "__main__": main() Edit As requested here is a screenshot of the graph. It was created using create_complex_graph(max_levels=5) and I arbitrarily chose max_level=5 which generates 63 nodes. For context, the nodes on the graph represent people to be rewarded and the edges represent referrals. See below: Edit 2 Given this is a reward/referral network, as a priority I want to accommodate the distribution of rewards up the referral chain from Node1 because the upstream direction identifies who initiated the referral chain and reveals the network of referrals that led to a specific user's inclusion in the system. Distributing a fixed percentage to Node1. Distributing the remaining reward upwards through the referral chain. Limiting the distribution by either the remaining reward, a maximum number of referral levels, the absence of further predecessors. import networkx as nx import matplotlib.pyplot as plt def create_simple_graph(): graph = nx.DiGraph() graph.add_edge('Node0', 'Node1') # Node0 refers Node1 return graph def create_complex_graph(): graph = nx.DiGraph()
{ "domain": "codereview.stackexchange", "id": 45583, "lm_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, graph", "url": null }
python, graph def create_complex_graph(): graph = nx.DiGraph() graph.add_edge('Node0', 'Node1') # Node0 refers Node1 (Level 1) graph.add_edge('Node-1', 'Node0') # Node-1 refers Node0 (Level 2) graph.add_edge('Node-2', 'Node-1') # Node-2 refers Node-1 (Level 3) graph.add_edge('Node-3', 'Node-2') graph.add_edge('Node-4', 'Node-3') graph.add_edge('Node-5', 'Node-4') graph.add_edge('Node-6', 'Node-5') graph.add_edge('Node-7', 'Node-6') # Up to Node-7, making it 7 levels upstream. return graph def visualize_graph(graph: nx.DiGraph): pos = nx.spring_layout(graph) labels = nx.get_node_attributes(graph, 'reward') nx.draw( graph, pos, with_labels=True, labels={ node: f"{node}\nReward: {reward:.2f}" for node, reward in labels.items() }, node_size=5000, node_color='skyblue' ) plt.show() def distribute_rewards( graph: nx.DiGraph, start_node: str, total_reward: float, start_node_ratio: float, upward_referral_ratio: float, max_referral_levels: int ) -> None: nx.set_node_attributes(graph, 0, 'reward') graph.nodes[start_node]['reward'] = total_reward * start_node_ratio remaining_reward = total_reward - graph.nodes[start_node]['reward'] # Start with the assumption that all directly and indirectly referred nodes need some reward # We will first focus on distributing rewards to the start node and its direct and indirect referrers # Initialize a queue to process nodes level by level (breadth-first) queue = [(start_node, 0)] visited = set() while queue: current_node, level = queue.pop(0) if level > 0: # Calculate and distribute reward reward_for_node = (remaining_reward * upward_referral_ratio) / (2 ** (level - 1)) graph.nodes[current_node]['reward'] += reward_for_node remaining_reward -= reward_for_node
{ "domain": "codereview.stackexchange", "id": 45583, "lm_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, graph", "url": null }
python, graph if level < max_referral_levels: for predecessor in graph.predecessors(current_node): if predecessor not in visited: queue.append((predecessor, level + 1)) visited.add(predecessor) def main(): graph = create_complex_graph() distribute_rewards( graph, 'Node1', # Start Point 1000, # Total Reward 0.33, # 33% of total reward goes to the start node 0.1, # 10% of the remaining reward distributed upwards per level 7 # Maximum levels to go up in the referral chain ) for node in graph.nodes: print(f"{node}: Reward = ${graph.nodes[node]['reward']:.2f}") visualize_graph(graph) if __name__ == "__main__": main() See the graph below which at the moment is a tree structure. I plan to extend this solution to support self-referrals (Node1, referring themselves) and reverse-referrals so I think keeping it as a graph is probably a sane thing to do.
{ "domain": "codereview.stackexchange", "id": 45583, "lm_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, graph", "url": null }
python, graph Answer: The bounty says you're "looking for an answer from a reputable source", but it's unclear what you mean by that. Is there a specific question you want a reputable answer to? The algorithm you've written is depth-first search; it's canonical and typical and fine. From a theoretical CS perspective my only quibble would be that, in theory, you should be able to use the one search for all of your graph traversal. Instead you're following up with nx.shortest_path_length (and then doing that again in a nested loop). Since you're building your own DFS process, it's probably possible to re-write it to do everything you want, but I'm pretty sure we're going to find a networkx tool that will simplify the whole problem. ... and yes: bfs_layers will serve. I was hoping for some functional-style traversal process we could use to do everything at once; it's probably there I just didn't find it. With a single call to bfs_layers, you'll get a data structure that can replace your whole while queue:... and all your calls to nx.shortest_path_length. There are some other aspects of your code that I would have written differently, but IDK how much time you want to spend polishing this. A detail I didn't understand until I started testing: The root node gets their "direct" amount plus their exponential-proportionate share of the remainder. That actually answers several questions so I assume it's on purpose. Consider calling the "direct" share a "bonus", to make this more clear. from dataclasses import dataclass from typing import Sequence @dataclass(frozen=True) class WeightedLevel: rate: float nodes: Sequence[str] def distribute_rewards( graph: nx.DiGraph, start_node: str, total_reward: float, direct_referral_ratio: float, decrease_factor: float ) -> None: """ Distributes rewards within a referral network.
{ "domain": "codereview.stackexchange", "id": 45583, "lm_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, graph", "url": null }
python, graph Args: graph: The referral network graph. start_node: The node from which distribution starts. total_reward: Total reward amount to distribute. direct_referral_ratio: Ratio of the total reward given to the start node. decrease_factor: Factor by which the reward decreases at each level. """ nx.set_node_attributes(graph, 0, 'reward') direct_reward = total_reward * direct_referral_ratio remaining_reward = total_reward - direct_reward visited: set[str] = set() def dedupe(layer: list[str]) -> list[str]: # there's probably a better way deduped = [n for n in layer if n not in visited] visited.update(deduped) return deduped levels = [WeightedLevel(decrease_factor ** i, nodes) for (i, nodes) in enumerate(map(dedupe, nx.bfs_layers(graph, start_node))) if nodes] weight_value = remaining_reward / sum(wl.rate * len(wl.nodes) for wl in levels) for wl in levels: reward = weight_value * wl.rate for node in wl.nodes: graph.nodes[node]['reward'] = reward graph.nodes[start_node]['reward'] += direct_reward
{ "domain": "codereview.stackexchange", "id": 45583, "lm_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, graph", "url": null }
java, spring Title: Using java streams to handle incoming API requests Question: I am using the java stream API to handle incoming requests my employee service. A few questions I had are: Does using the streams API in the way I'm using it below affect the performance of the application? I have not seen any tutorials using the streams API in the way I am using it. So is it bad practice to use streams this way? Does using streams this way make the code less readable? public Response<EmployeeDto> saveEmployee(NewEmployeeRequest request) { boolean isEmployeeEmailExisting = employeeRepository.existsByEmail(request.email()); if (isEmployeeEmailExisting) { log.error("Employee with email {} already exists", request.email()); throw new ApplicationException(HttpStatus.CONFLICT, "Employee Already Exists", null); } EmployeeDto employeeDto = Stream.of(request) .map(employeeMapper::mapToEmployee) .map(employeeRepository::save) .map(employeeMapper::mapToDto) .findFirst() .get(); return Response.successfulResponse(HttpStatus.CREATED.value(), "Successful", employeeDto); } Answer: A "stream" is like a list or a queue; what you're doing is intelligible, but kind of silly because there's only ever one item. Judging from the alternative you post in the comments, it looks like the insight you're missing is that you can nest function calls. EmployeeDto employeeDto = employeeMapper.mapToDto( employeeRepository.save( employeeMapper.mapToEmployee(request))); Judging from your function names, there are probably a lot of other things that could be refactored too. For future reference, here on Code Review it's pretty normal to post very large blocks of code, sometimes multiple whole files, so that responders can see the whole context of what you're trying to do.
{ "domain": "codereview.stackexchange", "id": 45584, "lm_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, spring", "url": null }
python, game, curses Title: Python Breakout game Question: I came from C# background with strong OOP approach. I've decided to learn Python and Breakout game is a way to cover the basics of Python. I'll be really glad for any feedback and general opinion about my coding style and me using Python. Game also on github: https://github.com/bartex-bartex/BreakoutClone Running game for visualization: https://imgur.com/a/CWQwyhD run.py from curses import wrapper from game import Game def main(): game = Game() wrapper(game.start) if __name__ == '__main__': main() game.py from time import sleep from typing import Tuple import curses import helpers.helpers as helper from board import Board from sprite import Sprite from ball import Ball from tile import Tile from helpers.rectangle import Rectangle class Game: _WELCOME_MESSAGE = "Press SPACE to begin!" _FRAME_TIME = 1 / 10 def __init__(self) -> None: self.score = 0 def _arrange_tiles(self, rows_count, tile_width, tile_height, space_between_tiles, map_width, map_height, offset_from_left, offset_from_top): tiles = [] n = int((map_width - 2 - offset_from_left) / (tile_width + space_between_tiles)) # number of tiles in row for i in range(rows_count): ith_row_tiles = [] for j in range(n): # tile upper-left corner coordination tile_x = 1 + offset_from_left + j * (tile_width + 2) tile_y = 1 + offset_from_top + i * (tile_height + 1) # leave some space between player and tiles if tile_y > map_height - 8: break ith_row_tiles.append(Tile(Rectangle(tile_x, tile_y, tile_width, tile_height), i)) tiles.append(ith_row_tiles) return tiles
{ "domain": "codereview.stackexchange", "id": 45585, "lm_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, game, curses", "url": null }
python, game, curses def get_tiles_amount_left(self) -> int: not_broken = 0 for tile_row in self.tiles: for tile in tile_row: if tile.is_broken == False: not_broken += 1 return not_broken def _setup_curses(self, screen) -> Tuple[int, int]: curses.curs_set(False) # do not show cursor y, x = screen.getmaxyx() # get terminal wymiary screen.resize(y, x) # resize "virtual" terminal to original terminal return x, y def _initialize_game_objects(self, x, y): board = Board(x, y) sprite = Sprite(x, y) ball = Ball(sprite) self.tiles = self._arrange_tiles(3, 5, 1, 2, x, y, 3, 2) self.begin_tiles_count = self.get_tiles_amount_left() return board, sprite, ball def _draw_map(self, screen, board, ball, sprite, tiles = None, redraw_border = False): board.draw_ball(screen, ball) board.draw_sprite(screen, sprite) # In theory, border should be drawn only at the beginning if redraw_border == True: board.draw_border(screen) # None -> nothing to update if tiles != None: board.draw_tiles(tiles, screen) def _wait_for_user_start(self, screen, x, y): helper.display_center(self._WELCOME_MESSAGE, y - 2, screen, x) key = None while key != ord(' '): key = screen.getch() helper.display_center(' ' * len(self._WELCOME_MESSAGE), y - 2, screen, x) screen.nodelay(True) # .getch() doesn't wait for key def _handle_user_input(self, screen, board, sprite): key = screen.getch() curses.flushinp()
{ "domain": "codereview.stackexchange", "id": 45585, "lm_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, game, curses", "url": null }
python, game, curses if key == curses.KEY_RIGHT: sprite.move_right(board.width) return False elif key == curses.KEY_LEFT: sprite.move_left() return False elif key == ord('q'): return True def _display_win_message(self, screen, x, y): helper.display_center('You win!', int(y / 2), screen, x) helper.display_center(f'Your score is {self.score}', int(y / 2) + 1, screen, x) helper.display_center("Press 'q' to leave", int(y / 2) + 2, screen, x) def _display_lose_message(self, screen, x, y): helper.display_center('You lose...', int(y / 2), screen, x) helper.display_center(f'Your score is {self.score}', int(y / 2) + 1, screen, x) helper.display_center("Press 'q' to leave", int(y / 2) + 2, screen, x) def _wait_for_user_exit(self, screen): screen.nodelay(False) while True: key = screen.getch() if key == ord('q'): break def start(self, screen): x, y = self._setup_curses(screen) board, sprite, ball = self._initialize_game_objects(x, y) self._draw_map(screen, board, ball, sprite, self.tiles, True) self._wait_for_user_start(screen, x, y) update_tiles = False while True: if update_tiles == True: self._draw_map(screen, board, ball, sprite, self.tiles) else: self._draw_map(screen, board, ball, sprite) quit_game = self._handle_user_input(screen, board, sprite) if quit_game == True: break
{ "domain": "codereview.stackexchange", "id": 45585, "lm_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, game, curses", "url": null }
python, game, curses continue_game, update_tiles = ball.update(sprite, self.tiles, x, y, self) if continue_game == False: self._display_lose_message(screen, x, y) break elif self.begin_tiles_count == self.score: self._display_win_message(screen, x, y) break sleep(self._FRAME_TIME) self._wait_for_user_exit(screen) board.py from typing import List import curses from enums.colors_enum import Color from enums.directions_enum import Direction from tile import Tile class Board: def __init__(self, width, height) -> None: self.width = width self.height = height self._prepare_colors() def _prepare_colors(self): curses.use_default_colors() # Thanks to that -1 is transparent curses.init_pair(Color.SPRITE.value, curses.COLOR_RED, -1) # Sprite curses.init_pair(Color.BALL.value, curses.COLOR_BLUE, -1) # Ball curses.init_pair(Color.TILE.value, curses.COLOR_GREEN, -1) # Tile def draw_border(self, screen): screen.border('|', '|', '-', '-', '+', '+', '+', '+') def draw_sprite(self, screen, sprite): screen.addstr(sprite.y, sprite.x, "█" * sprite.length, curses.color_pair(Color.SPRITE.value)) if sprite.current_direction == Direction.LEFT: # remove most right sprite cells screen.addstr(sprite.y, sprite.x + sprite.length, ' ' * sprite.movement_speed) elif sprite.current_direction == Direction.RIGHT: # remove most left sprite cells screen.addstr(sprite.y, sprite.x - sprite.movement_speed, ' ' * sprite.movement_speed) def draw_ball(self, screen, ball): screen.addstr(ball.y - ball.move_vector[1], ball.x - ball.move_vector[0], " ") screen.addstr(ball.y, ball.x, "⬤", curses.color_pair(Color.BALL.value))
{ "domain": "codereview.stackexchange", "id": 45585, "lm_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, game, curses", "url": null }
python, game, curses def draw_tiles(self, tiles: List[List[Tile]], screen: curses.window): for tile_row in tiles: for tile in tile_row: for i in range(tile.rect.height): if tile.is_broken == False: screen.addstr(tile.rect.y + i, tile.rect.x, "█" * tile.rect.width, curses.color_pair(Color.TILE.value)) else: screen.addstr(tile.rect.y + i, tile.rect.x, " " * tile.rect.width) sprite.py import helpers.helpers as helper from enums.directions_enum import Direction class Sprite: _DEFAULT_LENGTH = 6 _DEFAULT_MOVEMENT_SPEED = 2 def __init__(self, map_width, map_height) -> None: self.length = self._DEFAULT_LENGTH self.movement_speed = self._DEFAULT_MOVEMENT_SPEED self.current_direction = None self.x, self.y = self._calculate_start_position(map_width, map_height) def _calculate_start_position(self, map_width, map_height): x = helper.calculate_center(map_width, self.length) y = map_height - 3 return (x, y) def move_right(self, map_width): if self.x + self.length < map_width - self.movement_speed: self.current_direction = Direction.RIGHT self.x += self.movement_speed def move_left(self): if self.x - 1 > self.movement_speed: self.current_direction = Direction.LEFT self.x -= self.movement_speed ball.py from typing import List from typing import Tuple import helpers.helpers as helpers from sprite import Sprite from tile import Tile from helpers.rectangle import Rectangle class Ball: def __init__(self, sprite) -> None: self._calculate_start_position(sprite) self.move_vector = [-1, -1]
{ "domain": "codereview.stackexchange", "id": 45585, "lm_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, game, curses", "url": null }
python, game, curses def _calculate_start_position(self, sprite: Sprite): # Based ball position upon sprite position self.x = sprite.x + helpers.calculate_center(sprite.length, 1) self.y = sprite.y - 1 def update(self, sprite: Sprite, tiles: List[List[Tile]], map_width, map_height, game) -> Tuple[bool, bool]: next_x, next_y = self.x + self.move_vector[0], self.y + self.move_vector[1] updated_tile = False if next_y == map_height - 1: # check for D boundary collision return False, False elif next_x == 0 or next_x == map_width - 1: # check for L, R boundary collision self.move_vector = [self.move_vector[0] * -1, self.move_vector[1]] elif next_y == 0: # check for U boundary collision self.move_vector = [self.move_vector[0], self.move_vector[1] * -1] elif helpers.is_collision(next_x, next_y, Rectangle(sprite.x, sprite.y, sprite.length, 1)): # check - sprite for collision self.move_vector = [self.move_vector[0], self.move_vector[1] * -1] else: for tile_row in tiles: for tile in tile_row: if tile.is_broken == False and helpers.is_collision(next_x, next_y, tile.rect): tile.is_broken = True self.move_vector = [self.move_vector[0], self.move_vector[1] * -1] game.score += 1 updated_tile = True self.x += self.move_vector[0] self.y += self.move_vector[1] return True, updated_tile tile.py from helpers.rectangle import Rectangle class Tile: def __init__(self, rect: Rectangle, row: int) -> None: self.rect = rect self.row = row self.is_broken = False helpers.py from helpers.rectangle import Rectangle def is_collision(x, y, area: Rectangle) -> bool: return (area.x <= x <= area.x + area.width and area.y <= y <= area.y + area.height)
{ "domain": "codereview.stackexchange", "id": 45585, "lm_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, game, curses", "url": null }
python, game, curses def display_center(text, row, screen, screen_width): """ :param str text: Text to display :param int row: Display row, 1-based-index :param window screen: Curses screen on which to display :param int screen_width: The width of emulated screen """ x = calculate_center(screen_width, len(text)) screen.addstr(row, x, text) def calculate_center(width, object_length = 1) -> int: """ Calculate x position at which the text should begin. :param int width: Display screen width :param int object_length: How long is displayed object :return int: x position """ if object_length < 1: raise Exception('Width should be >= 1') if object_length == 1: return int((width - 1) // 2) else: return int((width + 1) // 2 - (object_length // 2)) rectangle.py class Rectangle: def __init__(self, x, y, width, height): self.x = x self.y = y self.width = width self.height = height colors_enum.py from enum import Enum class Color(Enum): SPRITE = 1 BALL = 2 TILE = 3 directions_enum.py from enum import Enum class Direction(Enum): RIGHT = 1 LEFT = 2 Answer: Wow, no import pygame, this is strictly a colorful curses project. A bold design move! The animated demo image looks great. As does the source code. old-style annotations from typing import Tuple ... def _setup_curses(self, screen) -> Tuple[int, int]:
{ "domain": "codereview.stackexchange", "id": 45585, "lm_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, game, curses", "url": null }
python, game, curses I completely understand why you would write that, as it appears in lots of introductory materials and is a big improvement over what came before. In modern usage we prefer to avoid using the typing module, especially for common containers like list and tuple. So def ... -> Tuple[int, int]: becomes def ... -> tuple[int, int]: nit, typo: Last word in # tile upper-left corner coordination should probably be coordinate. _arrange_tiles() has some magic numbers, but they seem Fine and probably aren't worth giving names to. Shortening ith_row_tiles to just row would be OK. negative names if tile.is_broken == False: not_broken += 1 In get_tiles_amount_left() the negated identifier, and the sense of .is_broken rather than tile.exists, seem inconvenient. Humans do better when reasoning about variables stated in the positive, rather than the negative. In many languages, including python, booleans work like integers. Consider using sum(). I will just note this example in passing: >>> sum([True, False, True]) 2 Also, even if you change nothing else, prefer to phrase this conditional as if not tile.is_broken: keyword args self.tiles = self._arrange_tiles(3, 5, 1, 2, x, y, 3, 2) I'm sure that is correct. It is not easy to read. There is ample opportunity for a maintenance engineer to accidentally mess it up while making an edit. Consider using any of these techniques to simplify the call. Combine pairs of args to form a single (width, height) tuple arg. Explicitly name e.g. ... , offset_from_top=2) at the call site. Put kw default argument value in the signature, e.g. offset_from_top=2, and then caller is free to omit it. Define a new @dataclass which tracks some related dimensions, so we pass in fewer args.
{ "domain": "codereview.stackexchange", "id": 45585, "lm_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, game, curses", "url": null }
python, game, curses helper design def _initialize_game_objects(self, ...): board = ... sprite = ... ball = ... self.tiles = ... self.begin_tiles_count = ... return board, sprite, ball I like your habitual use of helpers. This is a well named helper. But we invoke it for two reasons: for side effects on self, and for three game objects. It's not exactly bad, but it's a slightly surprising style. singleton comparison _draw_map() does this: if tiles != None: Prefer if tiles is not None, which is comparing addresses (comparing id(tiles) against id(None)) instead of comparing content. Better still, just use if tiles:. Python's truthiness rules thankfully are pretty simple. Later, in start(), please replace if update_tiles == True: with a simple if update_tiles:. Both mypy and humans can easily see the variable is of type bool. Feel free to add an annotation if you want to be even more explicit. API design if update_tiles == True: self._draw_map(screen, board, ball, sprite, self.tiles) else: self._draw_map(screen, board, ball, sprite) That seems a little weird. Recommend you just unconditionally ask for (board, ball, sprite) to be drawn, and then let the caller worry about conditionally drawing tiles if they exist. dataclass class Tile: def __init__(self, rect: Rectangle, row: int) -> None: self.rect = rect self.row = row ... This is just a @dataclass. Consider converting it to one, so it's slightly simpler. Similarly for Rectangle. Also, I found area slightly hard to read here: def is_collision(x, y, area: Rectangle) -> bool:
{ "domain": "codereview.stackexchange", "id": 45585, "lm_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, game, curses", "url": null }
python, game, curses I think of "area" as a scalar real-valued quantity, as opposed e.g. to a region, a shape, a box, or a rect. docstring begins with a sentence The docstring for calculate_center() is perfect. It begins with an English sentence that gives its single responsibility, and goes on to explain the details. The signature even reveals some of the typing details! Consider using $ mypy --strict *.py, if you choose to spruce up some of those signatures. (Full disclosure: I also tend to use a @beartype class Foo: decorator on some of my classes, for runtime checking.) In contrast, I found the display_center() docstring kind of "meh", and I was sad to find no type annotations in the signature. Your identifiers are great, and with annotations there would be almost nothing left for the docstring to say. We could maybe rename screen -> curses_screen, IDK. And the fact that row is 1-origin is a valuable remark to retain. Currently we have a 4-line description of a 2-line helper, and that's even after eliding the mandatory introductory sentence. I love to see a helpful docstring, but in this case it seems to be quicker to just read the code. enum auto() These are perfectly fine as-is: class Color(Enum): SPRITE = 1 BALL = 2 TILE = 3 ... class Direction(Enum): RIGHT = 1 LEFT = 2 In cases where we only care about unique values, assigning e.g. RIGHT = auto() suffices. In the particular case of sprite colors, you might have assigned curses.COLOR_RED to SPRITE. In any event, no need for an _enum suffix on these module names. This application is coded in an admirably clear style and achieves its design goals. I would be willing to delegate or accept maintenance tasks on it.
{ "domain": "codereview.stackexchange", "id": 45585, "lm_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, game, curses", "url": null }
c++, game, console Title: Terminal based game: Part 2 Question: Follow up to: Terminal based game Finished up the framework. Still sticking with the X-Term based version. As I want a very simple framework to use for teaching (not this part initially). But my next question is the snake game implemented using this class. #ifndef THORSANVIL_GAMEENGINE_GAME_H #define THORSANVIL_GAMEENGINE_GAME_H #include <iostream> #include <signal.h> #include <unistd.h> #include <termios.h> #include <sys/select.h> static volatile sig_atomic_t done = 0; extern "C" void signalHandler(int signal) { if (!done) { done = signal; } } namespace ThorsAnvil::GameEngine { bool installHandler(int signal) { struct sigaction action; sigemptyset(&action.sa_mask); action.sa_flags = 0; action.sa_handler = signalHandler; int result = sigaction(signal, &action, nullptr); return result == 0; } class Game { using Time = std::chrono::time_point<std::chrono::high_resolution_clock>; using Duration = std::chrono::duration<double, std::micro>; using Step = std::chrono::duration<double, std::milli>; static constexpr char clearScreen[] = "\033[2J"; static constexpr char moveToZeroZero[] = "\033[0;0H"; static constexpr char hideCursor[] = "\033[?25l"; static constexpr char showCursor[] = "\033[?25h"; bool gameOver; termios originalConfig; Time nextDrawTime; Time nextStepTime; Duration durationDrawTime; Duration durationStepTime; Duration timeNeeded; int sleep;
{ "domain": "codereview.stackexchange", "id": 45586, "lm_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++, game, console", "url": null }
c++, game, console int sleepTime() { Time now = std::chrono::high_resolution_clock::now(); Duration sleepForDraw = nextDrawTime - now - timeNeeded; Duration sleepForStep = nextStepTime - now; Duration smallestSleep = sleepForDraw < sleepForStep ? sleepForDraw : sleepForStep; int microSeconds = smallestSleep.count(); return microSeconds > 0 ? microSeconds : 1; } void draw() { Time lastDrawTime = std::chrono::high_resolution_clock::now(); std::cout << moveToZeroZero; drawFrame(); std::cout << "Sleep: " << sleep << " \n"; durationDrawTime = std::chrono::high_resolution_clock::now() - lastDrawTime; timeNeeded = durationDrawTime + durationStepTime; nextDrawTime = lastDrawTime + std::chrono::milliseconds(redrawRateMilliSeconds()); } void input() { if (done) { gameOver = true; return; } fd_set input; FD_ZERO(&input); FD_SET(STDIN_FILENO, &input); sleep = sleepTime(); timeval timeout{sleep / 1'000'000, sleep % 1'000'000}; if (select(STDIN_FILENO + 1, &input, nullptr, nullptr, &timeout) > 0) { char key = std::cin.get(); handleInput(key); } } void logic() { int timeUp = (nextStepTime - std::chrono::high_resolution_clock::now()).count();
{ "domain": "codereview.stackexchange", "id": 45586, "lm_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++, game, console", "url": null }
c++, game, console if (timeUp <= 0) { Time lastStepTime = std::chrono::high_resolution_clock::now(); handleLogic(); durationStepTime = std::chrono::high_resolution_clock::now() - lastStepTime; timeNeeded = durationDrawTime + durationStepTime; nextStepTime = lastStepTime + std::chrono::milliseconds(gameStepTimeMilliSeconds()); } } protected: virtual void drawFrame() = 0; virtual int gameStepTimeMilliSeconds() {return 500;} virtual int redrawRateMilliSeconds() {return gameStepTimeMilliSeconds();} virtual void handleInput(char k) { if (k == 'Q') { gameOver = true; } } virtual void handleLogic() {} void setGameOver() { gameOver = true; } void newGame() { gameOver = false; } public: Game() : gameOver(false) , sleep(0) { if (!installHandler(SIGINT) || !installHandler(SIGHUP) || !installHandler(SIGTERM)) { throw std::runtime_error("Fail: Installing signal handlers"); } termios config; if (tcgetattr(STDIN_FILENO, &originalConfig) != 0 || tcgetattr(STDIN_FILENO, &config) != 0) { throw std::runtime_error("Fail: Getting keyboard state"); } config.c_lflag &= ~(ICANON | ECHO); config.c_cc[VMIN] = 1; /* Blocking input */ config.c_cc[VTIME] = 0; if (tcsetattr(STDIN_FILENO, TCSANOW, &config) != 0) { throw std::runtime_error("Fail: Setting keyboard state"); } } virtual ~Game() { tcsetattr(STDIN_FILENO, TCSAFLUSH, &originalConfig); } void run() { std::cout << clearScreen << hideCursor; while (!gameOver) {
{ "domain": "codereview.stackexchange", "id": 45586, "lm_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++, game, console", "url": null }
c++, game, console while (!gameOver) { draw(); input(); logic(); } std::cout << showCursor; } }; } #endif Not 100% confident in the chrono stuff. Any feedback on how to do that better really appreciated. Also: I am not sure about if I should have two timers. One for display refresh gameStepTimeMilliSeconds() and one for step refresh gameStepTimeMilliSeconds(). Their interactions seems to be minor but anybody with experience in this area would love to get input on that. Note: The linked Snake game has a draw time (unoptimized) for a brute force draw of the screen of around 950 micro seconds. So potentially we could do 1000 frames a second. This weekend I will explore the timings of an optimized draw (i.e. only updating the characters that would change).
{ "domain": "codereview.stackexchange", "id": 45586, "lm_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++, game, console", "url": null }
c++, game, console Answer: Missing #includes My compiler complains about a lot of undefined functions and types, because you forgot to add all the necessary #include statements. Since this is a header only, create a .cpp file that only includes your header, and try to compile it to an object file. Use std::chrono::steady_clock Unfortunately, it is not well-defined what kind of clock std::chrono::high_resolution_clock actually is. It is best to avoid it. Instead, use std::chrono::steady_clock; it is guaranteed to be steady (ie, doesn't have jumps because of NTP updates, daylight savings time changes or leap seconds), and likely has the same resolution as std::chrono::high_resolution_clock anyway. Avoid specifying time resolution unless really necessary You are dealing with explicit milliseconds and microseconds way too early. Try to keep durations in unspecified std::chrono::duration variables for as long as possible. You should only convert it to a concrete value at the last possible moment, which is right before calling select(). I recommend using this pattern: using Clock = std::chrono::steady_clock; using Time = Clock::time_point; using Duration = Clock::duration; using Rep = Duration::rep; … Duration sleepTime() { auto now = Clock::now(); auto sleepForDraw = nextDrawTime - now - timeNeeded; auto sleepForStep = nextStepTime - now; return std::min(sleepForDraw, sleepForStep); } void input() { … auto sleep_us = std::max(Rep{1}, std::chrono::duration_cast<std::chrono::microseconds>(sleepTime()).count()); timeval timeout{sleep / 1'000'000, sleep % 1'000'000}; … }
{ "domain": "codereview.stackexchange", "id": 45586, "lm_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++, game, console", "url": null }
c++, game, console Note how much simpler sleepTime() is now. Also, why was there a Step type to begin with? You are not using it anywhere. Issues with select() It is possible for select() to return 1 even if there is no character available to read from std::cin. Another issue that is more likely to occur is that std::cin is allowed to buffer its input. Consider that I press two keys in very short succession; they might both get read into std::cin's underlying stream buffer at the same time. So at first select() returns 1, and you call std::cin.get() which will return the first key. But when you call select() again, since both keys have already been read into a buffer, it will wait for a third key to be pressed. There is no way you can safely mix select() with std::cin(). The best you can do without an external library is to make the POSIX filedescriptor 0 non-blocking, and then to read() characters from it. Move setup and cleanup to the constructor and destructor In run() you hide the cursor and clear the screen before doing the actual run loop, and then afterwards you show the cursor again. These things should be done in the constructor and destructor instead. Consider what happens if an exception is thrown while the game is running. If you really want to keep it inside run(), then use an RAII object to manage the cursor visibility state.
{ "domain": "codereview.stackexchange", "id": 45586, "lm_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++, game, console", "url": null }
c++, console, snake-game Title: Terminal Base Snake Question: Based on this Framework Terminal based game: Part 2 A game that uses std::cout to print the board and std::cin to get keyboard input dynamically (using the framework linked). Allowing absolute beginners to quickly correct a simple text based animated game. Here is my version of the snake game: #include "ThorsAnvil/Game/Game.h" struct Location { int x; int y; bool operator==(Location const& rhs) const { return x == rhs.x && y == rhs.y; } friend std::ostream& operator<<(std::ostream& str, Location const& data) { return str << data.x << " , " << data.y; } }; enum Direction {Stop, Up, Down, Left, Right}; class Snake { using SLocation = std::vector<Location>; Direction direction; SLocation location; public: Snake(Location const& start) : direction{Stop} , location{1, start} { location.reserve(100); } char check(Location pos) { auto find = std::find(std::begin(location) , std::end(location), pos); if (find == std::begin(location)) { switch (direction) { case Stop: return '$'; case Up: return 'A'; case Down: return 'V'; case Left: return '<'; case Right: return '>'; } } if (find != std::end(location)) { return '@'; } return ' '; } void changeDirection(Direction d) { direction = d; }
{ "domain": "codereview.stackexchange", "id": 45587, "lm_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++, console, snake-game", "url": null }
c++, console, snake-game bool move() { if (direction != Stop) { int s = std::size(location); for (int loop = s; loop > 1; --loop) { location[loop - 1] = location[loop - 2]; } } switch (direction) { case Up: --location[0].y; break; case Down: ++location[0].y; break; case Left: --location[0].x; break; case Right: ++location[0].x; break; default: break; } auto find = std::find(std::begin(location) + 1, std::end(location), location[0]); return find == std::end(location); } void grow() { location.emplace_back(location.back()); } Location const& head() const { return location[0]; } int size() const { return location.size(); } }; class SnakeGame: public ThorsAnvil::GameEngine::Game { static constexpr int width = 20; static constexpr int height = 20; static constexpr double speedInceaseFactor = 0.92; int score; char key; Snake snake; Location cherry; char getChar(Location const& pos) { if (pos.y == 0 || pos.y == height - 1 || pos.x == 0 || pos.x == width -1) { return '#'; } if (pos == cherry) { return '%'; } char s = snake.check(pos); if (s != ' ') { return s; } return ' '; }
{ "domain": "codereview.stackexchange", "id": 45587, "lm_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++, console, snake-game", "url": null }
c++, console, snake-game virtual int gameStepTimeMilliSeconds() override { return 500 * std::pow(speedInceaseFactor, snake.size()); } virtual void drawFrame() override { std::cout << "Snake V1.0\n"; for (int y = 0; y < height; ++y) { for (int x = 0; x < width; ++x) { std::cout << getChar({x, y}); } std::cout << "\n"; } std::cout << "Score: " << score << " LastKey: " << key << "\n"; std::cout << "Step: " << gameStepTimeMilliSeconds() << " \n"; std::cout << std::flush; } virtual void handleInput(char k) override { key = k; Game::handleInput(key); switch (key) { case 'q': snake.changeDirection(Up); break; case 'a': snake.changeDirection(Down); break; case 'o': snake.changeDirection(Left); break; case 'p': snake.changeDirection(Right); break; default: break; } } bool snakeHitWall() { Location const& head = snake.head(); return head.y == 0 || head.y == height -1 || head.x == 0 || head.x == width -1; } void handleLogic() override { bool moveOk = snake.move(); if (!moveOk || snakeHitWall()) { std::cout << "Move: " << moveOk << "\n" << "Head: " << snake.head() << " \n" << "Wall: " << snakeHitWall() << "\n"; setGameOver(); } if (snake.head() == cherry) { snake.grow(); score++; cherry = {(rand() % (width - 2)) +1 , (rand() % (height - 2)) +1}; } } public: SnakeGame() : score(0) , key(' ') , snake{{width/2, height/2}} , cherry{(rand() % (width - 2)) +1 , (rand() % (height - 2)) +1} {} }; int main() { SnakeGame snake; snake.run(); }
{ "domain": "codereview.stackexchange", "id": 45587, "lm_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++, console, snake-game", "url": null }
c++, console, snake-game int main() { SnakeGame snake; snake.run(); } Brute force draw of the screen takes 900 micro seconds. Note: that's a grid of 20 * 20 so a small screen. Will look at what an optimized draw looks like this weekend (where I only update head and tail of the snake every drawFrame()` Answer: Missing #includes The code you posted doesn't compile without adding additional #include statements, for example cmath for the math functions, <algorithm> for std::find(), and so on. Make Direction an enum class Make it a habit to always use enum class instead of enum, unless you really need the latter. An enum class adds extra type-safety. Naming things What's a SLocation? Secure location? Static location? Snake location? If you avoid abbreviating names, others won't have to guess. Even the latter is not really appropriate, as it's not a single location. Maybe BodyLocations is better? That it's the body of a snake is clear from the context. Avoid specifying time resolution unless really necessary As I also mentioned in the review of part 2 of your game engine, you are dealing with explicit milliseconds way too early. Try to keep durations in unspecified std::chrono::duration variables for as long as possible. Of course, here you need to pass in the initial step time. So do it like this: class SnakeGame: public ThorsAnvil::GameEngine::Game { using Clock = std::chrono::steady_clock; using Duration = Clock::duration; Duration stepTime = std::chrono::milliseconds(500); … virtual Duration gameStepTime() override { return stepTime; } … void handleLogic() override { … if (snake.head() == cherry) { stepTime *= speedInceaseFactor; … } } … };
{ "domain": "codereview.stackexchange", "id": 45587, "lm_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++, console, snake-game", "url": null }
c++, console, snake-game Drawing is very inefficient I understand why you wrote the code like you did, but I want to point out that it has some inefficiencies that get larger as the snake gets longer. For every part of the frame that is not a wall, you have to iterate over the whole vector of body locations to find out what character to draw. It's the inverse problem of Space Invaders! Consider storing the whole frame in a single std::string, and then just updating those characters that need to be updates (the head, the tail and the cherry), and then just print that string to std::cout in one go. You could also make it an array of strings, one element per line, for a simpler way to address it using x and y coordinates.
{ "domain": "codereview.stackexchange", "id": 45587, "lm_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++, console, snake-game", "url": null }
lisp, racket, tower-of-hanoi Title: Tower of Hanoi in Racket Question: I'm in the early stages of learning Racket, and decided to have a go at the tower of Hanoi. I did this without any reference whatsoever, so everything is up for review, including the algorithm as well as my code. In order to move n disks from a from peg to a to peg, we need to... move the top n-1 disks from from to free move the remaining single disk from from to to move n-1 disks from free to to You then do exactly the same for the next n-1 pegs, and keep repeating until you've finished. This is clearly a recursive algorithm. In order to work out which is the free peg, I realised that if you number the pegs 1, 2 and 3, then the sum of all three is always 6, so the number of the free peg is going to be 6 - (from + to). This led to my first utility function... (define (free-peg from to) (- 6 (+ from to))) Then I needed a function to move a tower of n disks to one peg to another. Following the three steps shown above, I came up with this... (define (move-tower n from to) (if (= n 0) empty (append (move-tower (- n 1) from (free-peg from to)) ; step 1 (list (list from to)) ; step 2 (move-tower (- n 1) (free-peg from to) to))) ; step 3 ) I then needed to call this function, passing in the number of disks, and the start and end peg numbers. This gave me the following... (define (hanoi n) (define (free-peg from to) (- 6 (+ from to))) (define (move-tower n from to) (if (= n 0) empty (append (move-tower (- n 1) from (free-peg from to)) (list (list from to)) (move-tower (- n 1) (free-peg from to) to))) ) (move-tower n 1 3)) This seems to work correctly, and gives a list of 2-tuples, each of which tells you the from and to peg for that step. For example, a 3 disk solution is... '((1 3) (1 2) (3 2) (1 3) (2 1) (2 3) (1 3))
{ "domain": "codereview.stackexchange", "id": 45588, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "lisp, racket, tower-of-hanoi", "url": null }
lisp, racket, tower-of-hanoi Anyone able to comment on my code? Specifically, I run out of memory when I give it a large number of disks. I've been reading about tail recursion, but don't understand it well enough to know if it would help me here. Would that enable me to run this with bigger numbers? Thanks for any advice you can give. Remember, I'm very new at Racket (and Lisp in general), so please explain in words of one syllable! Answer: Regarding Style It would probably be more idiomatic to use a named let form in place of the internal define form for move-tower. This might complicate future memoization if you choose to use a ready-made library procedure to memoize the recursive process, but that won't be a problem for us. Regarding the Basic Design The idea to use free-peg is clever, but I think that it obfuscates the overall procedure a bit; this can be made significantly simpler and clearer, in my opinion, by using three parameters for the peg designators. These designators can then be used directly in the recursive calls to show more clearly what is happening. With this change, there is no need for any internal definitions. To simplify the procedure calls you can make these peg designator parameters optional, providing default values. This also allows the caller to specify particular designators as desired, e.g., a caller may prefer to use 'a, 'b, and 'c. Here is such a procedure with defaults that match the OP scheme: (define (hanoi-list-slow n (start 1) (dest 3) (temp 2)) (if (zero? n) '() (append (hanoi-list-slow (- n 1) start temp dest) (list (list start dest)) (hanoi-list-slow (- n 1) temp dest start))))
{ "domain": "codereview.stackexchange", "id": 45588, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "lisp, racket, tower-of-hanoi", "url": null }
lisp, racket, tower-of-hanoi Regarding Performance Both the OP procedure hanoi and the above procedure hanoi-list-slow do a lot of work that duplicates previous work. The easiest way to see this may be to write out an expansion of the recursive algorithm into single moves. ;;; To move: ;;; 4 disks from 1 to 3 ;;; ;;; We must calculate: ;;; 3 from 1 to 2 ;;; 2 from 1 to 3 (duplicated below) ;;; 1 from 1 to 2 ;;; 1 from 1 to 3 ;;; 1 from 2 to 3 ;;; 1 from 1 to 2 ;;; 2 from 3 to 1 ;;; 1 from 3 to 2 ;;; 1 from 3 to 1 ;;; 1 from 2 to 1 ;;; 1 from 1 to 3 ;;; 3 from 2 to 3 ;;; 2 from 2 to 1 ;;; 1 from 2 to 3 ;;; 1 from 2 to 1 ;;; 1 from 3 to 1 ;;; 1 from 2 to 3 ;;; 2 from 1 to 3 (duplicate moves) ;;; 1 from 1 to 2 ;;; 1 from 1 to 3 ;;; 1 from 2 to 3
{ "domain": "codereview.stackexchange", "id": 45588, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "lisp, racket, tower-of-hanoi", "url": null }
lisp, racket, tower-of-hanoi Here you can see that the sequence of single moves required to move 2 disks from peg 1 to peg 3 is calculated twice by the recursive algorithm. The amount of duplication will grow very quickly as the number of disks grows. A classic solution to this problem is to save the results of recursive procedure calls so that later calls can look these results up before making a new, potentially expensive, recursive call. This technique is called memoization. Another answer here has pointed this out and suggested a Racket package (memoize, documentation here) that provides a convenient way to memoize procedures, but this is not difficult to do so let's just rewrite hanoi-list-slow so that it is memoized. This may look complicated, but there isn't that much to understand, and it is good to be able to memoize your own procedures when necessary: (define (hanoi-list-memo n (start 1) (dest 3) (temp 2)) (let ((memo '())) (let move-disks ((n n) (start start) (dest dest) (temp temp)) (if (zero? n) '() (let* ((memo-tag (list n start dest temp)) (memo-entry (assoc memo-tag memo))) (if memo-entry (cdr memo-entry) ; return result if already memoized ; otherwise calculate a new result (let* ((moves-so-far (append (move-disks (- n 1) start temp dest) (list (list start dest)) (move-disks (- n 1) temp dest start))) (new-memo (cons memo-tag moves-so-far))) ; memoize the new result (set! memo (cons new-memo memo)) ; return the new result moves-so-far)))))))
{ "domain": "codereview.stackexchange", "id": 45588, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "lisp, racket, tower-of-hanoi", "url": null }
lisp, racket, tower-of-hanoi The above procedure uses a named let form. This could as easily be written to use an internal define to create a local move-disks procedure, but this style is both more idiomatic in Racket (and in Scheme) and more clear in my opinion. The fundamental change is that hanoi-list-memo itself is no longer a recursive procedure, but it wraps a let form which keeps a list of results as memo, and this let form then wraps the recursive procedure defined in a named let form. This internal move-disks procedure works as before, except that it looks in memo to see if it has been called previously with the current arguments; if so it doesn't need to calculate the result for the current call, but it can just return the previously saved result. Otherwise it does calculate the result and saves it for future calls. The memo list itself is an association list that is filled with pairs which contain a tag in the car position that identifies the arguments associated with a result; the result is stored in the cdr position of each pair. Association lists are time-honored lisp data structures composed of key-value pairs that are perfect for this sort of thing, and Racket provides the assoc procedure to facilitate searching an association list by key. When n is zero move-disks returns an empty list of moves, as before. Otherwise move-disks searches for a key (memo-tag) constructed from the current arguments. If this key is found move-disks just returns the saved result. Otherwise it calculates the result in the same way as the original hanoi-list-slow procedure, then creates a new entry for the memo list, and finally adds that entry to the memo list before returning the new result. Lets look at a few timings. Here is a simple procedure to test the contestants: (define (test-hanoi hanoi-fn n (tests-left 10) (heater 2) (tests-done 0) (moves 0) (sum-real 0)) (collect-garbage) (if (zero? tests-left)
{ "domain": "codereview.stackexchange", "id": 45588, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "lisp, racket, tower-of-hanoi", "url": null }
lisp, racket, tower-of-hanoi (moves 0) (sum-real 0)) (collect-garbage) (if (zero? tests-left) (printf "Average real time over ~A tests for ~A disks, ~A moves: ~A ms~%~%" tests-done n moves (exact->inexact (/ sum-real tests-done))) (let-values (((hanoi-length cpu-ms real-ms gc-ms) (time-apply hanoi-fn (list n)))) (if (zero? heater) (test-hanoi hanoi-fn n (- tests-left 1) 0 (+ tests-done 1) (length (first hanoi-length)) (+ sum-real real-ms)) (test-hanoi hanoi-fn n tests-left (- heater 1) 0 0 0)))))
{ "domain": "codereview.stackexchange", "id": 45588, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "lisp, racket, tower-of-hanoi", "url": null }
lisp, racket, tower-of-hanoi And here are some timings: hanoi.rkt> (test-hanoi hanoi-op 20 50) Average real time over 50 tests for 20 disks, 1048575 moves: 309.9 ms hanoi.rkt> (test-hanoi hanoi-list-slow 20 50) Average real time over 50 tests for 20 disks, 1048575 moves: 285.12 ms hanoi.rkt> (test-hanoi hanoi-list-memo 20 50) Average real time over 50 tests for 20 disks, 1048575 moves: 68.56 ms hanoi.rkt> (test-hanoi hanoi-memoize 20 50) Average real time over 50 tests for 20 disks, 1048575 moves: 89.82 ms
{ "domain": "codereview.stackexchange", "id": 45588, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "lisp, racket, tower-of-hanoi", "url": null }
lisp, racket, tower-of-hanoi The first test is the of original OP definition; it compares with the test of hanoi-list-slow defined above in this answer. Repeated tests seem to show these two as about the same in terms of timings. The third test is of the memoized hanoi-list-memo procedure defined above in this answer; it compares with the memoized procedure defined in another answer here (and named hanoi-memoize in my testing code). Repeated tests seem to show hanoi-list-memo consistently beating hanoi-memoize in timings. I'm not sure why this is, but I suspect that it has to do with the implementation of memoization in the memoize package. I haven't looked at the implementation; if it uses hash tables instead of association lists it may be at a disadvantage when a relatively small number of calls need to be memoized. In any case, this provides a reason to be able to implement memoization for yourself; sometimes a simple implementation will outperform a more general implementation found in a library. This of course holds for most any library procedure. Regarding Memory OP has said: "I run out of memory when I give it a large number of disks."
{ "domain": "codereview.stackexchange", "id": 45588, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "lisp, racket, tower-of-hanoi", "url": null }
lisp, racket, tower-of-hanoi Regarding Memory OP has said: "I run out of memory when I give it a large number of disks." This is not a problem that could be solved by writing tail recursions. The fundamental problem is that the OP procedure is generating a list of single moves required to move a stack of disks from one peg to another. This list must be stored in memory, and its size is not related to the size of the call stack. As we know, this number grows very fast. In fact, for n disks, 2ⁿ-1 single moves are required. For n = 25 the result list contains 33,554,431 entries (single moves); assuming that each entry pair is comprised of two 64 bit pointers that is about 512MB of memory. Increasing n by one will double this requirement. I am not sure how much dynamic heap memory Racket makes available, but this is probably around that limit. There may be a way to increase the amount of available memory in Racket (I am unaware of it) but as we noted, this could only allow a small increase in the magnitude of n. If the OP wants to return a list of moves, I am afraid that they are pretty much stuck with the memory limitations of their system (assuming that it is possible to grow the Racket dynamic heap size). But, if OP would settle for simply recording a list of moves, it would be possible to write that list to a file instead of to memory. That might start with something like this: (define (hanoi-list-fprint out n (start 1) (dest 3) (temp 2)) (if (zero? n) (fprintf out "") (begin (hanoi-list-fprint out (- n 1) start temp dest) (fprintf out "(~A ~A)~%" start dest) (hanoi-list-fprint out (- n 1) temp dest start))))
{ "domain": "codereview.stackexchange", "id": 45588, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "lisp, racket, tower-of-hanoi", "url": null }
memory-optimization, trie, zig Title: Autocompletion trie for English words in zig Question: I am trying to write a program that creates a Trie from a list of all English words, and then when run provides completions for a given prefix. Basically for each node I allocate a list of 255 null chars, and if a node has a child at a certain character, I set the node at index of the character as an int to have a value and it's own children. It's pretty fast right now as I'm embedding the list of words into the program to avoid reading from a file. It currently has a max memory footprint of 2G when running. Is there some optimization I could make to decrease the amount of memory I use? Heres the link for the word list: link const std = @import("std"); const NodePool = std.ArrayList(Trie.Node); const data = @embedFile("words_alpha.txt"); const Trie = struct { pool: NodePool, allocator: std.mem.Allocator, pub const Node = struct { end: bool, children: [256]?*Node, }; pub fn init(allocator: std.mem.Allocator) !Trie { return Trie{ .allocator = allocator, .pool = try NodePool.initCapacity(allocator, 3494707), }; } pub fn deinit(self: *Trie) void { self.pool.deinit(); } pub fn alloc_node(self: *Trie) !*Node { const node = Node{ .end = false, .children = [_]?*Node{null} ** 256, }; try self.pool.append(node); return &(self.pool.items[self.pool.items.len - 1]); } pub fn add(self: *Trie, root: *Node, slice: []const u8) !void { if (slice.len == 0) { return; } const index: usize = @intCast(slice[0]); if (root.children[index] == null) { var node = try self.alloc_node(); if (slice.len == 1) { node.end = true; } root.children[index] = node; } try self.add(root.children[index].?, slice[1..]); }
{ "domain": "codereview.stackexchange", "id": 45589, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "memory-optimization, trie, zig", "url": null }
memory-optimization, trie, zig try self.add(root.children[index].?, slice[1..]); } pub fn get_sub_tree(self: *Trie, root: *Node, slice: []const u8) *Node { var node = root; var str = slice[0..]; while (str.len > 0) { const index: usize = @intCast(str[0]); if (node.children[index] == null) { break; } node = node.children[index].?; str = str[1..]; } _ = self; return node; } pub fn get_autocompletion(self: *Trie, root: ?*Node, writer: anytype, ac_buffer: *std.ArrayList(u8)) !void { if (root) |r| { if (r.end) { try writer.print("{s}\n", .{ac_buffer.items}); } var i: usize = 0; while (i < r.children.len) : (i += 1) { try ac_buffer.append(@intCast(i)); try self.get_autocompletion(r.children[i], writer, ac_buffer); _ = ac_buffer.pop(); } } } }; pub fn main() !void { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; defer _ = gpa.deinit(); const allocator = gpa.allocator(); var stdout = std.io.getStdOut(); var stdin = std.io.getStdIn(); defer stdin.close(); defer stdout.close(); const writer = stdout.writer(); const reader = stdin.reader(); var trie = try Trie.init(allocator); defer trie.deinit(); const root = try trie.alloc_node(); // Read wordlist and create trie var itr = std.mem.splitScalar(u8, data, '\r'); var next = itr.next(); while (next) |n| { try trie.add(root, n[1..]); //next = try file.reader().readUntilDelimiterOrEof(&buf, '\r'); next = itr.next(); } // Event Loop while (true) { try writer.print("Enter prefix: ", .{}); const slice = try reader.readUntilDelimiterAlloc( allocator, '\n', 20, ); defer allocator.free(slice);
{ "domain": "codereview.stackexchange", "id": 45589, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "memory-optimization, trie, zig", "url": null }
memory-optimization, trie, zig // If nothing is entered exit if (slice.len == 0) { break; } const node = trie.get_sub_tree(root, slice); // Buffer that writer !! var words = std.ArrayList(u8).init(allocator); var temp = std.ArrayList(u8).init(allocator); defer temp.deinit(); defer words.deinit(); try trie.get_autocompletion(node, words.writer(), &temp); try writer.print("{s}", .{words.items}); try writer.print("\n", .{}); } } Answer: One way you can cut down on memory usage is by only using the set of printable characters instead of the whole ASCII charset. In the children array, 32 should map to 0, 65 should map to 33, and so on. This brings down the size for each Node's children from 256 to 95. The mapping itself is quite simple, simply subtract 32 when storing the character, and add 32 when printing it. And of course, 32 should be some named, not naked, constant in your code. You could also look at using a dynamically growing hash table. As the requirement is to only print English words, you can further eliminate most special characters (judging from this), and some other printable symbols which may not be part of your data-set, and adjust the mapping accordingly. (If it gets too complicated, use some sort of a map). Side-note: I did something similar in C some time ago that might be of interest (algorithm-wise): Trie Implementation, Autocompletion, and Graph Visualization In my application, changing the children array from 255 to 95 brought down the struct's size (the struct contained a bool field and the children array) from 1028 bytes to 384 bytes (I used 32-bit integers to store the indices in a dynamically growing pool of nodes. Previously, I was using 64-bit pointers, and the struct size had went down from 2056 bytes to 768 bytes). I should expect a similar reduction in your implementation too.
{ "domain": "codereview.stackexchange", "id": 45589, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "memory-optimization, trie, zig", "url": null }
programming-challenge, haskell, interview-questions Title: Last Stone Weight Problem in Haskell using list `insert` Question: Background Saw this problem on TheJobOverflow which seems to be a LeetCode question. It bothered me that the "challenge" of this problem was to recognize the need for a specific data-type (in this case a MaxHeap/PriorityQueue). I did another, more complicated solution, that uses folding Problem You are given a list of stones' weights (positive integer numbers); While there are at least two stones in the list, take the two heaviest stones and smash them together; if the weights were equal, both stones are destroyed; otherwise the lighter stone gets destroyed and the heavier one becomes the difference of the two values. You know need to consider this "remainder" stone as well as all the other stones The process ends when there is one or no stones in the list, and the result is either the last remaining stone, or zero if there are no stones left. Notes The main problem that you need to solve for here is the fact that, at all times, you need perfect knowledge/information on the state of the list. You need to know EXACTLY which two stones are CURRENTLY the two heaviest. WHILE adding to the list of known stones. As you smash stones you will inevitably be left with a remainder stone that you need to put somewhere. The new stone might now be the heaviest or the lightest, you don't know yet and you now need to keep track of it. The Reference Solution (written in CPP) uses a MaxHeap/PriorityQueue as it is the most efficient way to keep the maximum sized stone (integer) in a convenient position while being able to add to the structure in efficient time. Personal Goals
{ "domain": "codereview.stackexchange", "id": 45590, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "programming-challenge, haskell, interview-questions", "url": null }
programming-challenge, haskell, interview-questions Personal Goals Attempt to not use special data types outside of base lib. (There is a Heap package on Hackage, but can we do it without it?) Attempt Idiomatic Haskell (nothing too fancy) Attempt a "naive" approach (could a beginner stumble upon this with a rudimentary grasp of Haskell?) Should be performant (probably won't be better than the cpp implementation but should be about as fast and show the same time complexity The Code naiveLastStone :: (Num a, Ord a) => [a] -> a naiveLastStone = proccess . revSort where revCompare = flip compare revSort = sortBy revCompare revInsert = insertBy revCompare proccess [] = 0 proccess [x] = x proccess (x:y:ls) | n == 0 = proccess ls | otherwise = proccess $ revInsert n ls where n = x - y Explanation Init naiveLastStone :: (Num a, Ord a) => [a] -> a naiveLastStone = proccess . revSort compose the process with the reverse sort we process the list in order, heaviest to smallest Helpers revCompare = flip compare revSort = sortBy revCompare revInsert = insertBy revCompare idiomatic acceding sort and insert process first the base cases: empty list means return 0 and one stone left means return it. proccess [] = 0 proccess [x] = x then the actual processing of the list | n == 0 = proccess ls | otherwise = proccess $ revInsert n ls where n = x - y We are operating on the presumption that the list is ordered, large to small. The first 2 items will be the largest, and the second largest. (we need to keep the list sorted as we work with it) If remainder is 0, the rocks were destroyed and we process the next rocks | else The remainder rock exists, we now need to put it into the the list in the correct position. We use insert (using our acceding revInsert) as it has the property of keeping a sorted list, sorted. Our list is now in the correct order for the next iteration. Performance Checked against TheJobOverflow cpp solution
{ "domain": "codereview.stackexchange", "id": 45590, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "programming-challenge, haskell, interview-questions", "url": null }
programming-challenge, haskell, interview-questions Performance Checked against TheJobOverflow cpp solution code time array size cpp (-O3) ~0.8s 10 000 000 cpp (-O3) ~2.5s 20 000 000 cpp (-O3) ~3.8s 40 000 000 cpp (-O3) ~8.0s 80 000 000 cpp (-O3) ~10.0s 100 000 000 cpp (-O3) ~30.0s 800 000 000 haskell (-O2) ~0.5s 10000 haskell (-O2) ~2.5 20000 haskell (-O2) ~11.3s 40000 haskell (-O2) ~60.3s 80000 Sadly my solution is showing O(n^2) as apposed to the O(n log n) of the cpp solution. Personal Goals Met Yes Yes Yes No^2 Answer: Our first question should be "why is it O(N^2)?" The sort seems to be a merge-sort; I trust that it's O(n log(n)). But insert is noted as O(N), and you're calling it O(N) times, so it's a good bet that this is the/a problem. I don't actually have a good solution for you. In order to have an O(log(N)) insert, you'll need at minimum an O(1)-indexing data structure, preferably an always-sorted array or maybe a tree. I can't find any such thing in base. My only suggestion might be to unpack the source code for sort to somehow perform the rock-smashing during merging? Could be tricky...
{ "domain": "codereview.stackexchange", "id": 45590, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "programming-challenge, haskell, interview-questions", "url": null }
python, game, machine-learning, 2048 Title: Minimal AlphaGo algorithm implementation for game 2048, connect4 Question: I'm writing tutorial code to help high school students understand the MuZero algorithm. There are two main requirements for this code. The code needs to be simple and easy for any student to understand. The code needs to be flexible enough so that students can implement it for their own game projects without changing the core code. Here is the code repository: https://github.com/fnclovers/Minimal-AlphaZero/tree/master To write this code, I followed these criteria: For flexibility: Students need to modify the Game class to define their game environment, the Action class to define in-game actions, and the Network class for inference, in order to apply the MuZero algorithm to their own game. Game class: This core class must provide four functions: 1) Check for a terminal condition (def terminal(self) -> bool:), 2) Return a list of possible actions (def legal_actions(self) -> List[Action]:), 3) Perform an action in the game (def apply(self, action: Action):), 4) Create an image that stores the board state for reasoning and learning (def make_image(self, state_index: int):). Network class: The Network class has to infer four things: value, reward, policy, and hidden. Value means the sum of future rewards, reward is the current reward, policy is the probability of choosing each action, and hidden is the hidden network for inferring the next state. Students need to implement two functions: initial_inference, where the game image is provided, and recurrent_inference, where the subsequent actions are provided. For simplicity: To make the code easy to understand, we kept only the core algorithm (900 lines of code). At the same time, we support multiple CPUs and GPUs so that reinforcement learning algorithms that require hours of training can be trained in a feasible time. However, I would like to find a way to write the MuZero algorithms more concisely and easily.
{ "domain": "codereview.stackexchange", "id": 45591, "lm_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, game, machine-learning, 2048", "url": null }
python, game, machine-learning, 2048 Please review the code from the following perspective: Is the code simple enough for high school students to look at and easily understand the MuZero algorithm? Is the code flexible enough to allow students to add their own games to the project? (Sample Game class and Network class for explanation. See more code on github) class Game(object): """A single episode of interaction with the environment.""" def __init__(self, action_space_size: int, discount: float): self.environment = Environment() # Game specific environment. self.history = ( [] ) # history of prev actions; used for recurrent inference for training self.rewards = [] # rewards of prev actions; used for training dynamics network self.child_visits = ( [] ) # child visit probabilities; used for training policy network self.root_values = [] self.action_space_size = action_space_size self.discount = discount def terminal(self) -> bool: # Game specific termination rules. pass def legal_actions(self) -> List[Action]: # Game specific calculation of legal actions. return [] def apply(self, action: Action): reward = self.environment.step(action) self.rewards.append(reward) self.history.append(action) def store_search_statistics(self, root: Node): sum_visits = sum(child.visit_count for child in root.children.values()) action_space = (Action(index) for index in range(self.action_space_size)) self.child_visits.append( [ root.children[a].visit_count / sum_visits if a in root.children else 0 for a in action_space ] ) self.root_values.append(root.value()) def make_image(self, state_index: int): # Game specific feature planes. return []
{ "domain": "codereview.stackexchange", "id": 45591, "lm_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, game, machine-learning, 2048", "url": null }
python, game, machine-learning, 2048 def make_target(self, state_index: int, num_unroll_steps: int, td_steps: int): # The value target is the discounted root value of the search tree N steps # into the future, plus the discounted sum of all rewards until then. targets = [] for current_index in range(state_index, state_index + num_unroll_steps + 1): bootstrap_index = current_index + td_steps if bootstrap_index < len(self.root_values): value = self.root_values[bootstrap_index] * self.discount**td_steps else: value = 0 for i, reward in enumerate(self.rewards[current_index:bootstrap_index]): value += ( reward * self.discount**i ) # pytype: disable=unsupported-operands if current_index > 0 and current_index <= len(self.rewards): last_reward = self.rewards[current_index - 1] else: last_reward = 0 if current_index < len(self.root_values): # 1) image[n] --> pred[n], value[n], hidden_state[n] # 2) hidden_state[n] + action[n] --> reward[n], pred[n+1], value[n+1], hidden_state[n+1] targets.append( (value, last_reward, self.child_visits[current_index], True) ) else: # States past the end of games are treated as absorbing states. targets.append( (value, last_reward, [0] * self.action_space_size, False) ) return targets def to_play(self, state_index: int = None) -> Player: return Player() def action_history(self) -> ActionHistory: return ActionHistory(self.history, self.action_space_size) def print_game(self, state_index: int): pass def get_score(self, state_index: int): return len(self.history)
{ "domain": "codereview.stackexchange", "id": 45591, "lm_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, game, machine-learning, 2048", "url": null }
python, game, machine-learning, 2048 def get_score(self, state_index: int): return len(self.history) class NetworkOutput(typing.NamedTuple): value: np.ndarray reward: np.ndarray policy_logits: np.ndarray hidden_state: Any class Network(object): def __init__(self): self.n_training_steps = 0 def initial_inference(self, image, player) -> NetworkOutput: # representation + prediction function return NetworkOutput(0, 0, {}, []) def recurrent_inference(self, hidden_state, action) -> NetworkOutput: # dynamics + prediction function return NetworkOutput(0, 0, {}, []) def get_weights(self): # Returns the weights of this network. return [] def set_weights(self, weights): # Sets the weights of this network. pass def training_steps(self) -> int: # How many steps / batches the network has been trained for. return self.n_training_steps def increment_training_steps(self): self.n_training_steps += 1 def update_weights( self, config: MuZeroConfig, optimizer: optim.Optimizer, batch, ): # Update the weights of this network given a batch of data. return 0
{ "domain": "codereview.stackexchange", "id": 45591, "lm_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, game, machine-learning, 2048", "url": null }
python, game, machine-learning, 2048 Answer: You aim to teach folks to write good code. A noble goal! deps Before a student can run or enhance this codebase, they first need to get over some installation hurdles. This is a common hangup for python newbies, and worth devoting some care to. First we must clone the repo. But it is huge, something I will touch on below. Then we have some text to wade through. It is well organized and not too long, so we'll soon find the how to run section. In my opinion it's better to offer the user short commands which will definitely succeed the first time and which reveal a path for exploring what longer interior commands do. Here, I encourage you to do that with a Makefile, or if need be with a brief bash script that uses set -x so it is nearly as self explanatory as a make run. In particular, there's no reason for the student to attend to the administrivia of unpacking pickles in the crucial initial minutes where we're trying to show them something cool, quickly, to pull them in. Beware the danger of someone becoming a little frustrated before they're hooked, and wandering off to other pursuits. The text completely ignores this detail: $ python -c 'import numpy, torch'
{ "domain": "codereview.stackexchange", "id": 45591, "lm_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, game, machine-learning, 2048", "url": null }
python, game, machine-learning, 2048 We hope it will silently succeed. If it doesn't, we should offer some sort of venv / poetry advice. Ideally a makefile would automatically notice deficiencies and correct them. requirements.txt I don't know what interpreter version(s) you target, and more importantly what versions of numpy and torch you have tested against. You must add a conda environment.yml, a venv requirements.txt, or poetry.lock file to the repo. Else the codebase is unmaintainable. CI / CD Consider publishing this package on PyPI, and taking advantage of the icons they can auto-generate via continuous-integration continuous-deployment workflows. Or leverage GitHub's support for automatic workflows that will run unit tests for you. Remember, this isn't just about making life easy for you as a developer. It's about instilling confidence in a student some months down the road who hits a speedbump and needs the courage to persevere and make things work. repo URL Students use copy-n-paste all the time, and don't always include citations. Put at least one homepage URL, such as for the github repo, in your README.md. Then folks using a fork won't be confused. early win Consider adding a doc/ directory that includes example run transcripts and images. Invite the student to quickly reproduce such results, then make some trivial change like altering the discount rate, to see revised results. It is in this way that you will pull folks in and send them on their hacking journey. serialized NN size Your muzero_2048.pkl is more than 520 MiB. I claim a github repo is not the appropriate place to put that. Or at least, keep your source repo "small" and banish giant binary pickles to another repo or some other download location. GitHub offers e.g. LFS support. Many pip-installed packages use the requests package to transparently cache binary assets without the end user needing to really worry about them. evolution Git deals with diff-able text much better
{ "domain": "codereview.stackexchange", "id": 45591, "lm_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, game, machine-learning, 2048", "url": null }
python, game, machine-learning, 2048 end user needing to really worry about them. evolution Git deals with diff-able text much better than with opaque binary blobs, especially as they evolve over time. Every student that forks or clones your repo will need to download the giant binary history, even after the original pickles have rev'd or been deleted. format Pickle is not my favorite format. Consider adopting PyArrow's .parquet file format, which offers better support for compression and zero-copy access. python3 classes class Game(object):
{ "domain": "codereview.stackexchange", "id": 45591, "lm_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, game, machine-learning, 2048", "url": null }
python, game, machine-learning, 2048 Maybe you had some didactic goal related to inheritance when you wrote that? Or maybe it's just boilerplate copy-n-paste? In python2 that line distinguishes a "new-style" class MRO from an earlier scheme. In python3 there's no different behavior to distinguish between, so it's better to simply write class Game: In particular, it is better to train students to write that. zomg we see this everywhere. Global cleanup across three files, please. comments self.history = ( [] ) # history of prev actions; used for recurrent inference for training Thank you for using black; I truly do appreciate it. But here the formatting is rather mangled. Black is essentially suggesting that you instead author these two lines of code: # history of prev actions; used for recurrent inference for training self.history = [] Similarly for child_visits. Consider arranging for $ make lint to run the black formatter. Also, elide the uninformative "Game specific environment" remark. If need be, beef up this docstring instead: class Environment(object): """The environment MuZero is interacting with.""" Or if you feel the class name is too vague (I don't!) then rename to GameEnvironment. lint Recommend you routinely use ruff check *.py. if state_index == None: Prefer is None here in this GameConnect4 to_play() method. Yeah, I know, it's a slightly odd python thing related to singletons, sorry. But linters are here to help! pre-condition self.discount = discount A student might plausibly mess this up, and it's easy to validate that it's in the unit interval. Consider adding an assert or a conditional raise ValueError pass def terminal(self) -> bool: # Game specific termination rules. pass
{ "domain": "codereview.stackexchange", "id": 45591, "lm_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, game, machine-learning, 2048", "url": null }
python, game, machine-learning, 2048 Teaching students about the pass keyword should be deferred as long as possible, as it is one of the less intuitive aspects of the python grammar. I can't tell you how many times I have seen it inappropriately embedded in if / else clauses, alone or with other statements. Or incorrectly attempting to break out of a loop. If you can satisfy syntax rules with something else, I recommend doing that. I might even put an ... Ellipsis object there, which we evaluate and then discard the value. Here, turning the comment into a """docstring""" seems the best option. abc This raises another question: should we maybe raise a diagnostic that explains the student's obligation to supply some sensible implementation for the method? Should this class perhaps be an abstract base class? parallel lists This appears to be Fortran-style COMMON declared parallel arrays: def apply(self, action: Action): reward = ... self.rewards.append(reward) self.history.append(action) That is, I think that rewards[i] and history[i] always refer to the same time step. But I'm not sure; the code doesn't make it clear. Consider using this instead: from collections import namedtuple HistoryRecord = namedtuple("HistoryRecord", "action, reward") ... self.history.append(HistoryRecord(action, reward)) ZeroDivisionError sum_visits = sum(child.visit_count for child in root.children.values()) I imagine it is possible to prove that this sum is always positive. It isn't obvious to me that that will be so. Let's just say that the subsequent ... / sum_visits expression makes me nervous. comments are not docstrings def make_target(self, state_index: int, num_unroll_steps: int, td_steps: int): # The value target is the discounted root value of the search tree N steps # into the future, plus the discounted sum of all rewards until then.
{ "domain": "codereview.stackexchange", "id": 45591, "lm_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, game, machine-learning, 2048", "url": null }