text
stringlengths
1
2.12k
source
dict
html Each <select> has a javascript event handler attached to it so that when it's changed, an AJAX request is sent to the server to update the database that the row should now have a different value for that column. The code itself works, but because each table row contains so much extra HTML defining the possible options in the <select>'s, and which option is currently chosen, just the selects alone more than double the size of the table in terms of filesize. Without the two <select> columns, when my HTML page loads, the browser's dev tools tells me the html page is about 1.5MB. With the two <select> columns, it's closer to 5MB. Because there are multiple tables on the page, this effect compounds, and my final HTML page is about 10MB in size, and takes several seconds for the browser to download. I use datatables to make the table with the thousands of rows manageable for the user, but the entire table still needs to be downloaded before datatables can make it presentable. There is a way to make datatables use server-side processing, so that the page doesn't need to load the entire table all at once, and I've used that successfully before on other tables, but that comes with its own difficulties. Is there a simple way to stop this html size explosion? Or is server-side processing my only path? Answer: Since your page already relies on Javascript, you could populate the combo boxes in Javascript as well. Basically you need to define two sets of key/value pairs: column_3_choices column_4_choices
{ "domain": "codereview.stackexchange", "id": 43108, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "html", "url": null }
html column_3_choices column_4_choices You can have these embedded inside your HTML page, then use the onload event to populate the combo boxes on the browser. This would reduce the amount of generated HTML browser-side. However performance could be a problem if you have so many rows but it's something you can try. To be honest I doubt that performance will be so much better but that is easy to try and doesn't take a lot of effort. Regarding page size, I assume your webserver is sending gzipped content but if in doubt verify. Even if the final page is 10 Mb in size, it doesn't mean that 10 Mb were transferred or have to be transferred. It should be much less than that. My gut feeling is that rendering a large page with forms is inevitably going to burden the browser (and the speed of rendering can vary a lot from one browser to another, so be sure to test with different browsers). It could even be the bottleneck in your application. You could test your site with cURL to simply measure the response time from your server, without any rendering of HTML on screen or Javascript code being executed. See how it does. In my opinion, a table with thousands of rows is problematic. This is the thing I would want to change. Does the user really need all to see all that information at once? I would try a different approach: refresh the table with Ajax as per user filters. I am not sure this is what you call server-side processing, but maybe the datatable can be tweaked in that direction, at least you can add some handlers to improve it. In the meantime, try to identify the bottleneck to decide where your efforts should go first:
{ "domain": "codereview.stackexchange", "id": 43108, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "html", "url": null }
html how long it takes for your Django app to fetch the data (presumably from a table using SQL or ORM) => test the SQL individually or run an execution plan on your DBMS how long it takes for the browser to fetch the page from the server => use curl for that finally how long it takes for the browser to render the page after it's fetched => your browser should have some profiling tools, for example the developer tools in Firefox and probably Chrome. Bonus: datatable has caching features of its own, maybe you could capitalize on them for your need?
{ "domain": "codereview.stackexchange", "id": 43108, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "html", "url": null }
python, random Title: Purely Random Numbers Generator Question: I think the best Random Number on the Planet is PI. I wrote a code that generates a list of pseudo-random numbers in Python. Then it treats this list as positions of digits in Pi and then outputs digits at those positions. I am expecting someone to tell me that this method is NOT RANDOM ENOUGH. import random # Read all decimal places of PI from the file # and store as a string of 1 Million digits with open("piDigits.txt", 'r') as f: pidecimals = f.read() f.close() # Generate a list of random numbers # Treat each random number as a position in the expansion of Pi # Go to that position and pick up a particular number of digits of Pi # Output the results as a list def generate_random_array(nums, lengthofnum): randomnumbers=[] random_array = random.sample(range(1,len(pidecimals)-lengthofnum), nums) for i in range(0, nums): randomnumbers.append(pidecimals[random_array[i]:random_array[i]+lengthofnum]) print(randomnumbers) # Main Program mychoice = int(input("How many random numbers do you want? ")) mylength = int(input("How many digits in each random number? ")) generate_random_array(mychoice, mylength) Sample Output: How many random numbers do you want? 10000 How many digits in each random number? 2 ['55', '37', '93', '63', '36', '35', '72', '81', '01', '46', '90', '98', '31', '38', '65', '57', '10', '42', '07', '72', '11', '68', '48', '33', '08', '43', '28', '64', '75', '48', '00', '37', '74', '05', '97', '72', ,...] After the discussion in the comments below, I did a further experiment. I generated a series of quantum random numbers using the quantumrandom library. Then I extracted the decimal part of it and then extracted some digits from it. Then I tested for the same string being present in PI. VOILA! They did!!! import quantumrandom as qr with open("piDigits.txt", 'r') as f: pidecimals = f.read() f.close() maxrange = int(input("Enter Maxmimum of Range ")) count = 0
{ "domain": "codereview.stackexchange", "id": 43109, "lm_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, random", "url": null }
python, random maxrange = int(input("Enter Maxmimum of Range ")) count = 0 for i in range (0,maxrange): myx = qr.randint() decimalstring = str(myx) substring = decimalstring[2:7] if substring in pidecimals: count += 1 print(f"Quantum digit sequence {substring} found in Pi") print(f"Quantum digit sequences found in Pi {count} times out of {maxrange}") For 5 digits and 10 quantum random numbers... Enter Maxmimum of Range 10 Quantum digit sequence 39467 found in Pi Quantum digit sequence 58304 found in Pi Quantum digit sequence 11932 found in Pi Quantum digit sequence 93949 found in Pi Quantum digit sequence 68543 found in Pi Quantum digit sequence 84222 found in Pi Quantum digit sequence 10429 found in Pi Quantum digit sequence 12771 found in Pi Quantum digit sequence 70878 found in Pi Quantum digit sequence 08628 found in Pi Quantum digit sequences found in Pi 10 times out of 10 For 6 digits and 10 quantum random numbers: Enter Maxmimum of Range 10 Quantum digit sequence 122453 found in Pi Quantum digit sequence 817349 found in Pi Quantum digit sequence 719539 found in Pi Quantum digit sequence 609292 found in Pi Quantum digit sequence 824750 found in Pi Quantum digit sequence 833676 found in Pi Quantum digit sequences found in Pi 6 times out of 10 The program also finds sequences if I truncate the random from the end - so it matches the second half of the quantum number to a sequence in PI. Maybe that is all that PI is - juxtaposition of quantum random numbers. :) Answer: The fundamental premise of this solution is incorrect. The existing PRNG (random.sample) is defined thus:
{ "domain": "codereview.stackexchange", "id": 43109, "lm_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, random", "url": null }
python, random Almost all module functions depend on the basic function random(), which generates a random float uniformly in the semi-open range [0.0, 1.0). Python uses the Mersenne Twister as the core generator. It produces 53-bit precision floats and has a period of 2**19937-1. The underlying implementation in C is both fast and threadsafe. The Mersenne Twister is one of the most extensively tested random number generators in existence. Using that as the index for lookup in a substitution table of fixed digits whose distribution is uniform - no matter what they are, pi or otherwise - does not increase entropy. So it's incorrect to say that it's more (or less) random than random.sample(); it's exactly as random as random.sample(). It's just slower, occupies more memory and disk space. Don't do this. If you want something "more random": why? If it's frivolous, just use the built-in random module. If it's for security purposes, use secrets.
{ "domain": "codereview.stackexchange", "id": 43109, "lm_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, random", "url": null }
go, concurrency, amazon-web-services Title: Read bunch of files in parallel and populate concurrent map Question: I am trying to read bunch of S3 parquet files in parallel from a S3 bucket. After reading all these files, I am populating my products and productCatalog concurrent map. This happens during server startup and then I have getters method GetProductMap and GetProductCatalogMap to return these maps which be used by main application threads. My getters method will be called by lot of application threads concurrently so idea is populate these maps during server startup (then also periodically from a background thread using ticker) and then access it via getters from main application threads so I want to be in atomic state when writes happen, it is immediately accessed by reader threads. type clientRepo struct { s3Client *awss3.S3Client deltaChan chan string done chan struct{} err chan error wg sync.WaitGroup cfg *ParquetReaderConfig products *cmap.ConcurrentMap productCatalog *cmap.ConcurrentMap } type fileChannel struct { fileName string index int } Below is my loadFiles method which given a path find all the files I need to read in parallel. I am using errgroup here to communicate error states across goroutines. Idea is very simple here - Find all the files from S3 bucket and then read them in parallel. Populate my internal maps and then use those internal maps to populate my concurrent map. func (r *clientRepo) loadFiles(path string, spn log.Span) error { var err error bucket, key, err := awss3.ParseS3Path(path) if err != nil { return err } var files []string files, err = r.s3Client.ListObjects(bucket, key, ParquetFileExtension) if err != nil { return err }
{ "domain": "codereview.stackexchange", "id": 43110, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "go, concurrency, amazon-web-services", "url": null }
go, concurrency, amazon-web-services spn.Infof("Loading files from %s. Total files: %d", path, len(files)) start := time.Now() fileChan := make(chan fileChannel) g, ctx := errgroup.WithContext(context.Background()) for i := 0; i < runtime.NumCPU()-2; i++ { workerNum := i g.Go(func() error { for file := range fileChan { if err := r.read(spn, file.fileName, bucket); err != nil { spn.Infof("worker %d failed to process %s : %s", workerNum, file, err.Error()) return err } else if err := ctx.Err(); err != nil { spn.Infof("worker %d context error in worker: %s", workerNum, err.Error()) return err } } spn.Infof("worker %d processed all work on channel", workerNum) return nil }) } func() { for idx, file := range files { select { case fileChan <- fileChannel{fileName: file, index: idx}: continue case <-ctx.Done(): return } } }() close(fileChan) err = g.Wait() if err != nil { return err } spn.Info("Finished loading all files. Total duration: ", time.Since(start)) return nil } Here is read method which reads each file, deserializes them into ClientProduct struct and then I iterate over that to populate my internal maps. And then from those internal maps, I populate my concurrent map. I am not sure whether I need to do this - Maybe collect all these data in a channel and then populate it in read method but it can increase memory footprint by a lot so that's why I went with this design. func (r *clientRepo) read(spn log.Span, file string, bucket string) error { var err error var products = make(map[string]*definitions.CustomerProduct) var productCatalog = make(map[string]map[int64]bool)
{ "domain": "codereview.stackexchange", "id": 43110, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "go, concurrency, amazon-web-services", "url": null }
go, concurrency, amazon-web-services fr, err := pars3.NewS3FileReader(context.Background(), bucket, file, r.s3Client.GetSession().Config) if err != nil { return errs.Wrap(err) } defer xio.CloseIgnoringErrors(fr) pr, err := reader.NewParquetReader(fr, nil, int64(r.cfg.DeltaWorkers)) if err != nil { return errs.Wrap(err) } if pr.GetNumRows() == 0 { spn.Infof("Skipping %s due to 0 rows", file) return nil } for { rows, err := pr.ReadByNumber(r.cfg.RowsToRead) if err != nil { return errs.Wrap(err) } if len(rows) <= 0 { break } byteSlice, err := json.Marshal(rows) if err != nil { return errs.Wrap(err) } var productRows []ClientProduct err = json.Unmarshal(byteSlice, &productRows) if err != nil { return errs.Wrap(err) }
{ "domain": "codereview.stackexchange", "id": 43110, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "go, concurrency, amazon-web-services", "url": null }
go, concurrency, amazon-web-services for i := range productRows { var flatProduct definitions.CustomerProduct err = r.Convert(spn, &productRows[i], &flatProduct) if err != nil { return errs.Wrap(err) } if flatProduct.StatusCode == definitions.DONE { continue } products[strconv.FormatInt(flatProduct.ProductId, 10)] = &flatProduct for _, catalogId := range flatProduct.Catalogs { catalogValue := strconv.FormatInt(int64(catalogId), 10) if v, ok := productCatalog[catalogValue]; ok { v[flatProduct.ProductId] = true } else { productCatalog[catalogValue] = map[int64]bool{flatProduct.ProductId: true} } } } } for k, v := range products { r.products.Set(k, v) } for k, v := range productCatalog { r.productCatalog.Upsert(k, v, func(exists bool, valueInMap interface{}, newValue interface{}) interface{} { m := newValue.(map[int64]bool) var updatedMap map[int64]bool if valueInMap == nil { // New value! updatedMap = m } else { typedValueInMap := valueInMap.([]int64) updatedMap = m for _, k := range typedValueInMap { updatedMap[k] = true } } a := make([]int64, 0, len(m)) for k := range m { a = append(a, k) } return a }) } return nil } And these are my getter methods which will be accessed by main application threads: func (r *clientRepo) GetProductMap() *cmap.ConcurrentMap { return r.products } func (r *clientRepo) GetProductCatalogMap() *cmap.ConcurrentMap { return r.productCatalog }
{ "domain": "codereview.stackexchange", "id": 43110, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "go, concurrency, amazon-web-services", "url": null }
go, concurrency, amazon-web-services func (r *clientRepo) GetProductCatalogMap() *cmap.ConcurrentMap { return r.productCatalog } Note: My products map is made of productId as the key and value as flatProduct. But my productCatalog map is made of catalogId as the key and unique list of productIds as the value. Here is the concurrent map I am using - https://github.com/orcaman/concurrent-map And here is the upsert method which I am using - https://github.com/orcaman/concurrent-map/blob/master/concurrent_map.go#L56 I am using this parquet library to read all these S3 files. Problem Statement I am looking for ideas to see if there is anything that can be improved in above design or the way I am populating my maps. Opting for code review to see if anything can be improved which can improve some performance or reduce memory footprints. Answer: Avoid worker pools The loadFiles method spawns runtime.NumCPU()-2 goroutines to act as workers in a pool. This is a pattern you are probably familiar with from other languages where threads are OS threads, and so it's better for efficiency if each thread can be scheduled on a separate CPU core. However, in go, goroutines are lightweight and already distributed across OS threads, so it makes less sense to limit the number of threads in this way. In particular if some of the worker goroutines are blocked waiting on I/O, some CPU cores will be sitting idle. There are good reasons to limit the number of concurrent goroutines, usually related to file descriptor limit and memory usage. However using the number of CPUs to limit the number of goroutines is a code smell. I would recommend a concurrency pattern we saw in a previous question, namely limiting the number of active goroutines using a semaphore. Then loadFiles would look something like func (r *clientRepo) loadFiles(ctx context.Context, path string, spn log.Span) error { // Load list of files as before. files := ...
{ "domain": "codereview.stackexchange", "id": 43110, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "go, concurrency, amazon-web-services", "url": null }
go, concurrency, amazon-web-services g, ctx := errgroup.WithContext(ctx) // sem acts as a semaphore to limit the number of concurrent goroutines. sem := make(chan struct{}, 100) for _, file := range files { select { case <-ctx.Done(): break case sem <- struct{}{}: } file := file g.Go(func() error { defer func() { <-sem }() return r.read(spn, file.fileName, bucket) }) } if err := g.Wait(); err != nil { return err } spn.Info("Finished loading all files. Total duration: ", time.Since(start)) return nil } A few other minor comments Pass context as a parameter Both loadFiles and read should take context as a parameter instead of calling context.Background. This gives the flexibility to add a timeout or cancellation later. Avoid nested maps. Nested maps can require a lot of allocations. In read, consider making productCatalog a flat map with a struct key type. In fact, you could consider inserting directly into the concurrent map without constructing a separate map locally. Then read would look something like func (r *clientRepo) read(ctx context.Context, spn log.Span, file string, bucket string) error { // Initialize the reader as before. pr := ... for { rows, err := pr.ReadByNumber(r.cfg.RowsToRead) if err != nil { return err } if len(rows) <= 0 { break } byteSlice, err := json.Marshal(rows) if err != nil { return err } var productRows []ClientProduct err = json.Unmarshal(byteSlice, &productRows) if err != nil { return err }
{ "domain": "codereview.stackexchange", "id": 43110, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "go, concurrency, amazon-web-services", "url": null }
go, concurrency, amazon-web-services for i := range productRows { // Going with the idea that Convert returns // a CustomerProduct. flatProduct, err := r.Convert(spn, productRows[i]) if err != nil { return err } if flatProduct.StatusCode == definitions.DONE { continue } r.products.Set(strconv.Itoa(flatProduct.ProductId, 10), flatProduct) for _, catalogId := range flatProduct.Catalogs { catalogValue := strconv.FormatInt(int64(catalogId), 10) r.productCatalog.Upsert(catalogValue, flatProduct.ProductId, func(exists bool, valueInMap interface{}, newValue interface{}) interface{} { productID := newValue.(int64) if valueInMap == nil { return []int64{productID} } oldIDs := valueInMap.([]int64) for _, id := range oldIDs { if id == productID { // Already exists, don't add duplicates. return oldIDs } } return append(oldIDs, productID) }) } } } return nil } This uses a linear scan to check for duplicate product IDs, so it will be faster than allocating a map if the number of IDs is small. Up to you to test the performance of this suggestion. Avoid "getters" The GetProductMap and GetProductCatalogMap methods are unnecessary boilerplate. Just make products and productCatalog exported fields.
{ "domain": "codereview.stackexchange", "id": 43110, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "go, concurrency, amazon-web-services", "url": null }
java, algorithm, comparative-review, tree, benchmarking Title: Comparing two general LCA algorithms in Java Question: Now I have two algorithms solving a problem: given a general (multi-way) tree, and any array of node names, find the the node that is the deepest common ancestor. LCAComputer.java: package com.github.coderodde.generallca; /** * This interface specifies the API for methods computing multiple node LCAs. * * @author Rodion "rodde" Efremov * @version 1.6 (Mar 19, 2022) */ public interface LCAComputer { GeneralTreeNode computeLowestCommonAncestor(GeneralTree tree, String... nodeNames); } LCAComputerV1.java: package com.github.coderodde.generallca.impl; import com.github.coderodde.generallca.GeneralTree; import com.github.coderodde.generallca.GeneralTreeNode; import com.github.coderodde.generallca.LCAComputer; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects;
{ "domain": "codereview.stackexchange", "id": 43111, "lm_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, algorithm, comparative-review, tree, benchmarking", "url": null }
java, algorithm, comparative-review, tree, benchmarking /** * This class provides a method for computing general lowest common ancestors. * For each query node {@code n}, the algorithm computes the path from * {@code n} to the root node. Then, it marches along all the paths upwards * towards the root node incrementing the counts of each visited nodes. The * first node whose counter reaches the number of query nodes, is the LCA. * * @author Rodion "rodde" Efremov * @version 1.6 (Mar 18, 2022) */ public final class LCAComputerV1 implements LCAComputer { public GeneralTreeNode computeLowestCommonAncestor(GeneralTree tree, String... nodeNames) { List<List<GeneralTreeNode>> paths = new ArrayList<>(nodeNames.length); for (int i = 0; i < nodeNames.length; ++i) { GeneralTreeNode node = tree.getNode(nodeNames[i]); Objects.requireNonNull( node, "There is no node with name '" + nodeNames[i] + "'."); paths.add(getPathToRoot(node)); } Map<GeneralTreeNode, Integer> visitedMap = new HashMap<>(); for (List<GeneralTreeNode> path : paths) { for (GeneralTreeNode node : path) { visitedMap.put(node, visitedMap.getOrDefault(node, 0) + 1); if (visitedMap.get(node) == nodeNames.length) { return node; } } } throw new IllegalStateException("Should not get here."); } private List<GeneralTreeNode> getPathToRoot(GeneralTreeNode node) { List<GeneralTreeNode> path = new ArrayList<>(); while (node != null) { path.add(node); node = node.getParent(); } return path; } } LCAComputerV2.java package com.github.coderodde.generallca.impl;
{ "domain": "codereview.stackexchange", "id": 43111, "lm_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, algorithm, comparative-review, tree, benchmarking", "url": null }
java, algorithm, comparative-review, tree, benchmarking LCAComputerV2.java package com.github.coderodde.generallca.impl; import com.github.coderodde.generallca.GeneralTree; import com.github.coderodde.generallca.GeneralTreeNode; import com.github.coderodde.generallca.LCAComputer; import java.util.Arrays; /** * * This class provides a method for computing general lowest common ancestors. * The algorithm moves all the query nodes to the level of the shallowest node, * and keeps moving all the nodes until they all visit a single node, which is * a LCA. * * @author Rodion "rodde" Efremov * @version 1.6 (Mar 19, 2022) */ public final class LCAComputerV2 implements LCAComputer { @Override public GeneralTreeNode computeLowestCommonAncestor(GeneralTree tree, String... nodeNames) { GeneralTreeNode[] nodes = new GeneralTreeNode[nodeNames.length]; for (int i = 0; i < nodes.length; ++i) { nodes[i] = tree.getNode(nodeNames[i]); } Arrays.sort( nodes, (n1, n2) -> { return Integer.compare(n1.getDepth(), n2.getDepth()); }); int minimumDepth = nodes[0].getDepth(); for (int i = 1; i < nodes.length; ++i) { while (nodes[i].getDepth() > minimumDepth) { nodes[i] = nodes[i].getParent(); } } // Here, nodes points to the visited nodes at the minimum depth: while (!visitingOnlyOneNode(nodes)) { for (int i = 0; i < nodes.length; ++i) { nodes[i] = nodes[i].getParent(); } } return nodes[0]; } private boolean visitingOnlyOneNode(GeneralTreeNode[] nodes) { for (int i = 0; i < nodes.length - 1; ++i) { if (nodes[i] != nodes[i + 1]) { return false; } } return true; } }
{ "domain": "codereview.stackexchange", "id": 43111, "lm_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, algorithm, comparative-review, tree, benchmarking", "url": null }
java, algorithm, comparative-review, tree, benchmarking GeneralTreeNode.java: package com.github.coderodde.generallca; import java.util.Objects; /** * This class implements a node for general trees. It allows any number of * child nodes. * * @author Rodion "rodde" Efremov * @version 1.6 (Mar 18, 2022) */ public final class GeneralTreeNode { private final String name; private final int depth; private GeneralTreeNode parent; GeneralTreeNode(String name, int depth, GeneralTreeNode parent) { this.name = name; this.depth = depth; this.parent = parent; } public int getDepth() { return depth; } public String getName() { return name; } public GeneralTreeNode getParent() { return parent; } public void setParent(GeneralTreeNode parent) { this.parent = parent; } @Override public boolean equals(Object o) { if (!(o instanceof GeneralTreeNode)) { return false; } GeneralTreeNode other = (GeneralTreeNode) o; return name.equals(other.name); } @Override public int hashCode() { // Generated by NetBeans IDE 12.6 int hash = 7; hash = 19 * hash + Objects.hashCode(this.name); return hash; } } GeneralTree.java: package com.github.coderodde.generallca; import java.util.HashMap; import java.util.Map; import java.util.Objects;
{ "domain": "codereview.stackexchange", "id": 43111, "lm_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, algorithm, comparative-review, tree, benchmarking", "url": null }
java, algorithm, comparative-review, tree, benchmarking import java.util.HashMap; import java.util.Map; import java.util.Objects; /** * * @author rodde */ public final class GeneralTree { private final Map<String, GeneralTreeNode> treeNodeMap = new HashMap<>(); private GeneralTreeNode root; public GeneralTreeNode getNode(String name) { return treeNodeMap.get(name); } public void addRootNode(String name) { Objects.requireNonNull(name, "The node name is null."); if (treeNodeMap.containsKey(name)) { throw new IllegalArgumentException( "The node named '" + name + "' is already in this tree."); } root = new GeneralTreeNode(name, 0, null); treeNodeMap.put(name, root); } public void addNode(String childNodeName, String parentNodeName) { GeneralTreeNode parentNode = treeNodeMap.get(parentNodeName); Objects.requireNonNull(parentNode, "The parent node is null."); GeneralTreeNode childNode = new GeneralTreeNode( childNodeName, parentNode.getDepth() + 1, parentNode); treeNodeMap.put(childNodeName, childNode); } } BenchmarkApp.java: package com.github.coderodde.generallca; import com.github.coderodde.generallca.impl.LCAComputerV1; import com.github.coderodde.generallca.impl.LCAComputerV2; import java.util.ArrayList; import java.util.List; import java.util.Random;
{ "domain": "codereview.stackexchange", "id": 43111, "lm_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, algorithm, comparative-review, tree, benchmarking", "url": null }
java, algorithm, comparative-review, tree, benchmarking public final class BenchmarkApp { private static final int NUMBER_OF_TREE_NODES = 1000_000; private static final int NUMBER_OF_QUERIES = 100_000; private static final int MAXIMUM_QUERY_LENGTH = 50; private final long seed; private final GeneralTree tree = new GeneralTree(); private final LCAComputer lcaComputerV1 = new LCAComputerV1(); private final LCAComputer lcaComputerV2 = new LCAComputerV2(); public BenchmarkApp(long seed) { this.seed = seed; buildTree(); } public void warmup() { doRun(false); } public void benchmark() { doRun(true); } private void doRun(boolean print) { Random random = new Random(seed); List<GeneralTreeNode> result1 = new ArrayList<>(NUMBER_OF_QUERIES); List<GeneralTreeNode> result2 = new ArrayList<>(NUMBER_OF_QUERIES); String[][] queries = getQueries(); long startTime = System.currentTimeMillis(); for (int i = 0; i < NUMBER_OF_QUERIES; ++i) { result1.add( lcaComputerV1.computeLowestCommonAncestor( tree, queries[i])); } long endTime = System.currentTimeMillis(); if (print) { long duration = endTime - startTime; System.out.println( lcaComputerV1.getClass().getSimpleName() + " in " + duration + " milliseconds."); } startTime = System.currentTimeMillis(); for (int i = 0; i < NUMBER_OF_QUERIES; ++i) { result2.add( lcaComputerV2.computeLowestCommonAncestor( tree, queries[i])); } endTime = System.currentTimeMillis(); if (print) {
{ "domain": "codereview.stackexchange", "id": 43111, "lm_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, algorithm, comparative-review, tree, benchmarking", "url": null }
java, algorithm, comparative-review, tree, benchmarking } endTime = System.currentTimeMillis(); if (print) { long duration = endTime - startTime; System.out.println( lcaComputerV2.getClass().getSimpleName() + " in " + duration + " milliseconds."); System.out.println("Algorithms agree: " + result1.equals(result2)); } } private void buildTree() { Random random = new Random(this.seed); List<GeneralTreeNode> createdNodeList = new ArrayList<>(); tree.addRootNode("Root"); GeneralTreeNode root = tree.getNode("Root"); createdNodeList.add(root); for (int i = 1; i < NUMBER_OF_TREE_NODES; ++i) { String childName = Integer.toString(i); int index = random.nextInt(createdNodeList.size()); GeneralTreeNode parentNode = createdNodeList.get(index); tree.addNode(childName, parentNode.getName()); createdNodeList.add(tree.getNode(childName)); } } private String[][] getQueries() { String[][] queries = new String[NUMBER_OF_QUERIES][]; for (int i = 0; i < NUMBER_OF_QUERIES; ++i) { queries[i] = generateQuery(); } return queries; } private String[] generateQuery() { Random random = new Random(this.seed); int queryLength = random.nextInt(MAXIMUM_QUERY_LENGTH) + 1; String[] query = new String[queryLength]; for (int i = 0; i < query.length; ++i) { query[i] = Integer.toString(random.nextInt(NUMBER_OF_TREE_NODES)); } return query; } }
{ "domain": "codereview.stackexchange", "id": 43111, "lm_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, algorithm, comparative-review, tree, benchmarking", "url": null }
java, algorithm, comparative-review, tree, benchmarking Demo.java: package com.github.coderodde.generallca; public final class Demo { public static void main(String[] args) { long seed = System.currentTimeMillis(); System.out.println("--- Seed = " + seed + " ---"); BenchmarkApp app = new BenchmarkApp(seed); System.out.println(">>> Warming up..."); app.warmup(); System.out.println(">>> Warming up done."); System.out.println(); System.out.println(">>> Benchmarking..."); app.benchmark(); System.out.println(">>> Benchmarking done."); } } LCAComputerTest.java: package com.github.coderodde.generallca; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; public class LCAComputerTest {
{ "domain": "codereview.stackexchange", "id": 43111, "lm_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, algorithm, comparative-review, tree, benchmarking", "url": null }
java, algorithm, comparative-review, tree, benchmarking public class LCAComputerTest { final LCAComputer lcaComputer; public LCAComputerTest(LCAComputer lcaComputer) { this.lcaComputer = lcaComputer; } @Test public void testComputeLowestCommonAncestor() { GeneralTree tree = new GeneralTree(); tree.addRootNode("A"); tree.addNode("B", "A"); tree.addNode("C", "A"); tree.addNode("D", "B"); tree.addNode("E", "B"); tree.addNode("F", "C"); tree.addNode("G", "C"); tree.addNode("H", "G"); tree.addNode("I", "G"); tree.addNode("J", "G"); // A // / \ // / \ // B C // / \ / \ // D E F G // /|\ // H I J assertEquals(tree.getNode("A"), lcaComputer.computeLowestCommonAncestor(tree, "D", "H")); assertEquals(tree.getNode("G"), lcaComputer.computeLowestCommonAncestor(tree, "I", "H", "J")); assertEquals(tree.getNode("C"), lcaComputer.computeLowestCommonAncestor(tree, "F", "G")); assertEquals(tree.getNode("A"), lcaComputer.computeLowestCommonAncestor( tree, "D", "H", "G", "F")); } } LCAComputerV1Test.java: package com.github.coderodde.generallca; import com.github.coderodde.generallca.impl.LCAComputerV1; public class LCAComputerV1Test extends LCAComputerTest { public LCAComputerV1Test() { super(new LCAComputerV1()); } }
{ "domain": "codereview.stackexchange", "id": 43111, "lm_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, algorithm, comparative-review, tree, benchmarking", "url": null }
java, algorithm, comparative-review, tree, benchmarking LCAComputerV2Test.java: package com.github.coderodde.generallca; import com.github.coderodde.generallca.impl.LCAComputerV2; public class LCAComputerV2Test extends LCAComputerTest { public LCAComputerV2Test() { super(new LCAComputerV2()); } } Critique request Please, tell me anything that comes to mind. Thank you in advance. Answer: Programming "against" interfaces - way to go. In LCAComputer I'd appreciate a definition whether for a node n and its parent p the LCA is p or p's parent. (I'd prefer LCAfinder & lowestCommonAncestor().  I'm undecided whether I'd prefer a bunch of nodes over a bunch of names - have both?  If I was into Java stream processing, I'd ponder to offer just pair of whatever. ) GeneralTree & GeneralTreeNode: I'd appreciate interfaces. I'm used to tree operations to start at the root/a node in case of recursive ones. I expect to be able to iterate the children of a node. LCAComputerV1&2 I see collecting items to process instead of processing them right away. In visitingOnlyOneNode() (foundLCA()?), I might use if (nodes.length <= 1) return true; final GeneralTreeNode first = nodes[0]; for (int i = 1 ; i < nodes.length ; i++) { if (nodes[i] != first) { return false; } }
{ "domain": "codereview.stackexchange", "id": 43111, "lm_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, algorithm, comparative-review, tree, benchmarking", "url": null }
java, algorithm, comparative-review, tree, benchmarking Keeping it simple performed well with Random moved to getQueries(): /* - pick a champion * - for every possible challenger, find LCA * - early out on <code>champion.getDepth()</code> 0 */ public GeneralTreeNode computeLowestCommonAncestor(GeneralTree tree, String... nodeNames) { if (null == tree || null == nodeNames || 0 == nodeNames.length) return null; GeneralTreeNode champion = tree.getNode(nodeNames[nodeNames.length-1]); for (String name: nodeNames) { GeneralTreeNode challenger = tree.getNode(name); while (champion.getDepth() < challenger.getDepth()) challenger = challenger.getParent(); while (challenger.getDepth() < champion.getDepth()) champion = champion.getParent(); while (champion != challenger) { champion = champion.getParent(); challenger = challenger.getParent(); } if (0 == champion.getDepth()) return champion; } return champion; }
{ "domain": "codereview.stackexchange", "id": 43111, "lm_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, algorithm, comparative-review, tree, benchmarking", "url": null }
c++, algorithm, simulation, union-find Title: Percolation threshold simulation using C++ Question: I am studying Algorithms by Princeton University. The first week assignment is to simulate percolation by using Java. https://coursera.cs.princeton.edu/algs4/assignments/percolation/specification.php Since I am learning C++, I'm using C++ to do the assignment. Unfortunately, there is no grader for C++. Therefore, I came to here to ask for code review. Core algorithm (from course website) The core algorithm is weighted quick union with path compression. The WeightedQuickUnionUF class represents a union–find data type (also known as the disjoint-sets data type). It supports the classic union and find operations, along with a count operation that returns the total number of sets. The union–find data type models a collection of sets containing n elements, with each element in exactly one set. The elements are named 0 through n–1.Initially, there are n sets, with each element in its own set.The canonical element of a set (also known as the root) is one distinguished element in the set. Here is a summary of the operations: root(p) returns the canonical element(root) of the set containing p. It compress the path by updating the parent of p to its grandparent. The connected operation returns the same value for two elements if and only if they are in the same set. WeightedUnion(p, q) merges the set containing element p with the set containing element q. That is, if p and q are in different sets, replace these two sets with a new set that is the union of the two. count() returns the number of sets. Percolation
{ "domain": "codereview.stackexchange", "id": 43112, "lm_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, simulation, union-find", "url": null }
c++, algorithm, simulation, union-find Percolation Model a percolation system using an n-by-n grid of sites. Each site is either open or blocked. A full site is an open site that can be connected to an open site in the top row via a chain of neighboring (left, right, up, down) open sites. The system percolates if there is a full site in the bottom row. In other words, a system percolates if we fill all open sites connected to the top row and that process fills some open site on the bottom row. Goal Find the threshold that the system will percolate. That is, the percentage of open site in the system for it to be percolated WeightedQuickUnionUF.h #pragma once #include <vector> class WeightedQuickUnionUF{ private: std::vector<int> parent; //parent link(site indexed) std::vector<int> sz; //size of component for roots(site indexed) / no of element in tree int count_; //number of components/tree public: WeightedQuickUnionUF(int n); int count()const; //return no of component bool connected(int p, int q); //check if their components' are equal void WeightedUnion(int p, int q); //merge trees tgt, smaller tree becomes child of larger tree private: int root(int p); //return root of p }; WeightedQuickUnionUF.cpp #include "WeightedQuickUnionUF.h" WeightedQuickUnionUF::WeightedQuickUnionUF(int n){ count_ = n; parent.reserve(n); for (int i = 0; i < n; i++){ parent.push_back(i); } sz.reserve(n); for (int i = 0; i < n; i++){ sz.push_back(i); } } int WeightedQuickUnionUF::count()const{ return count_; } int WeightedQuickUnionUF::root(int p){ while (p != parent[p]){ //chase parent pointer until it reaches root => parent = parent's root => parent = root parent[p] = parent[parent[p]]; //change root of p to its grandparent: path-compression p = parent[p]; //go to grandparent } return p; } bool WeightedQuickUnionUF::connected(int p, int q){ return root(p) == root(q); }
{ "domain": "codereview.stackexchange", "id": 43112, "lm_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, simulation, union-find", "url": null }
c++, algorithm, simulation, union-find bool WeightedQuickUnionUF::connected(int p, int q){ return root(p) == root(q); } void WeightedQuickUnionUF::WeightedUnion(int p, int q){ int rootP = root(p); int rootQ = root(q); if (rootP == rootQ) return; if (sz[rootP] < sz[rootQ]){ parent[rootP] = rootQ; sz[rootQ] += sz[rootP]; } else { parent[rootQ] = rootP; sz[rootP] += sz[rootQ]; } --count_; } gen_uf.h #pragma once #include <random> int rand_uf(int range_from, int range_to); //generate random number gen_uf_im.cpp #include "gen_uf.h" #include <random> int rand_uf(int range_from, int range_to){ static std::random_device r1; //static: ensure only one seed in runtime static std::default_random_engine reng(r1()); //seed the random engine std::uniform_int_distribution<> distr(range_from, range_to); //initialize the range for the distribution return distr(reng); //transform the random unsigned int generated by reng into an int } Percolation.h #pragma once #include <vector> #include <iostream> #include "WeightedQuickUnionUF.h" #include "gen_uf.h" class Percolation: private WeightedQuickUnionUF{ private: //n^2 site std::vector<int> grid; //size of grid, 5-by-5 grid has size 5 int sz_grid; const int m_open = 1; const int closed = 0; //top virtual site int top; //bottom virtual site int bottom; int numberOfOpenSites_; public: //create n-by-n grid, with all sites initially closed Percolation(int n); //open the site (row, col) if it is not open already void open(int row, int col); // is the site (row, col) open? bool isOpen(int row, int col)const; // is the site (row, col) Full? bool isFull(int row, int col); // return the number of open site int numberOfOpenSites()const; // does the system percolates? bool percolates(); //Monte Carlo Simulation double testPercolateThreshold(); };
{ "domain": "codereview.stackexchange", "id": 43112, "lm_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, simulation, union-find", "url": null }
c++, algorithm, simulation, union-find //Monte Carlo Simulation double testPercolateThreshold(); }; Percolation.cpp #include "Percolaton.h" #include "WeightedQuickUnionUF.h" #include "gen_uf.h" #include <vector> #include <iostream> Percolation::Percolation(int n): WeightedQuickUnionUF(n * n + 2) { sz_grid = n; numberOfOpenSites_ = 0; grid.reserve(n * n); for (int i = 0; i < n * n; i++){ //n^2 complexity grid.push_back(closed); //initially all sites are closed } top = n * n; //top virtual site bottom = n * n + 1; //bottom virtual site int bot_tmp_ix = n * (n - 1) + 0; //bottom edge starts from [n - 1][0] for (int i = 0; i < n; i++){ WeightedUnion(i, top); //connect top edge and top WeightedUnion(bot_tmp_ix, bottom); //connect bottom edge and bottom bot_tmp_ix++; } } void Percolation::open(int row, int col){ //row:1 col:0 for size 5 = grid[5] // = size(row) + col = 5(1) + 0 int ix = sz_grid * row + col; if (!isOpen(row, col)) grid[ix] = m_open; ++numberOfOpenSites_; //connect to up, left, right, down sites if they are opened if ((row - 1) >= 0){ //up if(isOpen(row - 1, col)){ int up_ix = sz_grid * (row - 1) + col; WeightedUnion(ix, up_ix); } } if ((col - 1) >= 0){ //left if(isOpen(row, col - 1)){ int left_ix = sz_grid * row + (col - 1); WeightedUnion(ix, left_ix); } } if ((col + 1) <= sz_grid - 1){ //right if(isOpen(row, col + 1)){ int right_ix = sz_grid * row + (col + 1); WeightedUnion(ix, right_ix); } } if ((row + 1) <= sz_grid - 1){ //down if(isOpen(row + 1, col)){ int down_ix = sz_grid * (row + 1) + col; WeightedUnion(ix, down_ix); } } } bool Percolation::isOpen(int row, int col)const{ int ix = sz_grid * row + col; if (grid[ix] == m_open) return true; else return false; }
{ "domain": "codereview.stackexchange", "id": 43112, "lm_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, simulation, union-find", "url": null }
c++, algorithm, simulation, union-find bool Percolation::isFull(int row, int col){ int ix = sz_grid * row + col; return connected(ix, top); } int Percolation::numberOfOpenSites()const{ return numberOfOpenSites_; } bool Percolation::percolates(){ return connected(top, bottom); } double Percolation::testPercolateThreshold(){ while (!percolates()){ int row = rand_uf(0, sz_grid - 1); int col = rand_uf(0, sz_grid - 1); if (!isOpen(row, col)){ open(row, col); } } double threshold = numberOfOpenSites() / static_cast<double>(sz_grid * sz_grid); return threshold; } PercolationStat.h #pragma once #include "Percolaton.h" class PercolationStat{ private: double thresholdSum; int size; int trials; public: //perform independent trials on a n-by-n grid PercolationStat(int sz, int times); //sample mean of percolation threshold double PercolationMean(); }; PercolationStat.cpp #include "PercolationStat.h" #include "Percolaton.h" PercolationStat::PercolationStat(int sz, int times): size(sz), trials(times) { thresholdSum = 0; for (int i = 0; i < times; i++){ Percolation p(sz); thresholdSum += p.testPercolateThreshold(); } } double PercolationStat::PercolationMean(){ return thresholdSum / trials; } ufmain.cpp #include <iostream> #include "WeightedQuickUnionUF.h" #include "Percolaton.h" #include "gen_uf.h" #include "PercolationStat.h" using namespace std; int main(){ int size; cout << "Enter the size(N) of percolation grid(N-by-N):"; cin >> size; cout << "Enter number of time of simulation:"; int time; cin >> time; PercolationStat pStat(size, time); cout << "Mean: " << pStat.PercolationMean() << endl; }
{ "domain": "codereview.stackexchange", "id": 43112, "lm_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, simulation, union-find", "url": null }
c++, algorithm, simulation, union-find PercolationStat pStat(size, time); cout << "Mean: " << pStat.PercolationMean() << endl; } Answer: Use std::size_t for sizes, counts and indices You are using int to store sizes, counts and indices, however an int might not be large enough to store all possible sizes and indices of data structures that fit into memory. The proper type to use is std::size_t. Make a habit of using this instead of int. Note that this is also the type that is returned by many standard library container functions like std::vector::size(), and if you were to use int yourself, you would get compiler warnings when trying to compare those with the results of the STL functions. Consider merging parent and sz into one std::vector parent and sz should always have the same length, and the elements have to be in the same order. While it is working like you have written, you can enforce this by creating a small struct and make a single std::vector out of that: class WeightedQuickUnionUF { struct Node { std::size_t parent; std::size_t sz; }; std::vector<Node> nodes; ... }; Then you can initialize it like so: WeightedQuickUnionUF::WeightedQuickUnionUF(std::size_t n) { count_ = n; nodes.reserve(n); for (std::size_t i = 0; i < n; ++i) { nodes.push_back({i, i}); } }
{ "domain": "codereview.stackexchange", "id": 43112, "lm_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, simulation, union-find", "url": null }
c++, algorithm, simulation, union-find And instead of writing root(p) you write nodes(p).root. Naming things While most names are chosen quite well, there are some inconsistencies. You have the issue that some member variable names clash with corresponding member function names. To avoid these clashes, in some cases you add an underscore at the end of the variable, in others you prefix the variable with m_. For non-clashing variable names you don't use any prefix or postfix. I recommend that instead you have a uniform way of naming all your member variables; either use the _ postfix or the m_ prefix. Another issue is that some member functions start with a capital, others don't. It doesn't matter which style you use, but use it consistently. If you go for starting with a lower case letter, then of course the constructors are excluded from this rule as they have to match the name of the class exactly. Composition versus inheritance Inheritance is good when you have is-a relationships, for example a dog is an animal. However, can you say that a percolation is a weighted quick union algorithm? I recommend you don't let Percolation inherit from WeightedQuickUnionUF, but rather just make the latter a private member variable. Storing grid more efficiently For grid, you only store whether each grid site is open or closed. Thus, a bool would suffice. A bool normally only takes one byte instead of the typical 4 bytes for an int, but std::vector<bool> is often specialized such that it takes only one bit per element. (This has its drawbacks, but it's perfect for what you want to do.) Don't use classes unnecessarily Coming from Java you might think that everything needs to be in a class. However, in C++ you can have stand-alone functions, and I recommend you use them if you don't need a class. For example, PercolationStat does all its work in the constructor, and then you have a single member function to get the results out of it. This can be written much simpler as a single function instead:
{ "domain": "codereview.stackexchange", "id": 43112, "lm_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, simulation, union-find", "url": null }
c++, algorithm, simulation, union-find double percolationStat(std::size_t sz, std::size_t times) { double thresholdSum = 0;
{ "domain": "codereview.stackexchange", "id": 43112, "lm_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, simulation, union-find", "url": null }
c++, algorithm, simulation, union-find for (std::size_t i = 0; i < times; ++i) { ... } return thresholdSum / times; } Related to this, I would move testPercolateThreshold() out of it and make it a stand-alone function. It can look like: double testPercolateThreshold(std::size_t sz) { Percolation p(sz); while (!p.percolates()) { ... } return p.numerOfOpenSites() / static_cast<double>(sz * sz); } This reduces the responsibilties of class Percolation. Use '\n' instead of std::endl Prefer using '\n' instead of std::endl; the latter is equivalent to the former, but also forces the output to be flushed, which is usually not necessary and might hurt performance. Unnecessary if-statements Instead of if (condition) return true; else return false, just write return condition. In open(), you check if isOpen() is false. However, in testPercolateThreshold() you do the same before calling isOpen(). So one of those tests is redundant. It might be safer to have open() return immediately if isOpen() is true, then it can be called unconditionally without corrupting the state.
{ "domain": "codereview.stackexchange", "id": 43112, "lm_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, simulation, union-find", "url": null }
python, python-3.x, programming-challenge, balanced-delimiters Title: Programming Challenge - Capturing Bracket Levels Question: I don't have a formal description for this problem, but here are the parameters: Given a string S check that each opening bracket has a matching closing bracket. Any nesting violations are invalid. Assume multiple nested sets of similar brackets are invalid. Because the nesting level matters and we can't just arbitrarily count brackets, my solution is to generate an array of substrings that contain each bracket level and check for violations. Is there a way to make this more efficient? bracket_levels.py import re def hasClosedBrackets(s: str) -> bool: brackets = dict([('(', ')'), ('[', ']'), ('{', '}'), ('<', '>')]) for (opener, closer) in brackets.items(): pattern = r'(?<=\{}).+?(?=\{})'.format(opener, closer) for match in re.findall(pattern, s): for (o,c) in brackets.items(): if match.count(o) != match.count(c): return False return True # The first four test cases are true, the last four are false for test in ['(){}[]', '()[{}]', '<as>df', '(<[{a}s]>d)f', '()[{]}', '<as(>df)', '{as<df}', '(())',]: print(test, ':', hasClosedBrackets(test)) Output (){}[] : True ()[{}] : True <as>df : True (<[{a}s]>d)f : True ()[{]} : False <as(>df) : False {as<df} : False (()) : False Answer: Unfortunately, your current strategy is doomed by its optimism. Why? Because the regular expression is premised on checking only those portions of the string containing matching brackets. Parts of the string not enclosed by matching brackets are ignored. And if those parts contain any bracket characters, they will slip through the cracks. For example, all of these invalid strings return true: ( { [ < ) } ] > (] (((( ({[< )}]>({[< The internet has lots of discussion of a classic, and quite elegant, algorithm for this problem, using a stack (a Python list will do the trick). Ditch the regex; append and pop will do everything you need.
{ "domain": "codereview.stackexchange", "id": 43113, "lm_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, programming-challenge, balanced-delimiters", "url": null }
javascript, classes, enum Title: JavaScript Class with a Fixed Set of Instances Question: I am looking to write a JavaScript class BasicType with five fixed instances INT, FLOAT, STRING, BOOL, ANYTHING. It should be impossible to create any additional instances. The instances themselves should have a single enumerable, non-configurable, non-writable property called name. Printing these instances with console.log, which delegates to util.inspect, should show the class name and name, for example: > console.log(BasicType.BOOL) BasicType { name: 'bool' } > BasicType.BOOL.name = "zoolean" TypeError: Cannot assign to read only property 'name' of object '#<BasicType>' > new BasicType("int") Error: Basic type objects cannot be constructed I've managed to make this work! Unfortunately my code is long and verbose and repetitive: export class BasicType { static INT = Object.create(BasicType.prototype, { name: { value: "int", enumerable: true }, }); static FLOAT = Object.create(BasicType.prototype, { name: { value: "float", enumerable: true }, }); static BOOL = Object.create(BasicType.prototype, { name: { value: "bool", enumerable: true }, }); static STRING = Object.create(BasicType.prototype, { name: { value: "string", enumerable: true }, }); static ANYTHING = Object.create(BasicType.prototype, { name: { value: "anything", enumerable: true }, }); constructor() { throw new Error("Basic type objects cannot be constructed"); } } The feedback I am looking for is:
{ "domain": "codereview.stackexchange", "id": 43114, "lm_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, classes, enum", "url": null }
javascript, classes, enum The feedback I am looking for is: Is there a way to iterate through the five values? I don't see how since I have to declare the static properties. Maybe defineProperties (though this works with a single object) or maybe there is a static initializer construct? Is the throwing an error in the constructor the acceptable way to do this in JavaScript? Or is the very idea of fixing the number of instances antithetical to JavaScript? Is the class construct correct here? Maybe they should just be objects? I thought of this but then the util.inspect would have to be hacked to make it look like all the objects in the enclosing application (yes, it is a compiler), and doing type analysis with .constructor also would not work without hacking. So I kind of like using class here, but if there is a better way, I would love to see it. I know this is ES2022 but Node and modern browsers already support static and I am fine using it. Any ES2022 forms are appreciated! Answer: I do not understand the purpose of this object BasicType. You ask. "Is there a way to iterate through the five values? " Yes using Object.entries(BasicType) "Is the throwing an error in the constructor the acceptable way to do this in JavaScript?" No. In JS or any other language. Don't create a thing that has no purpose. "Is the class construct correct here?" No, though I am unsure as to the purpose of BasicType "Maybe they should just be objects? ... then the util.inspect would have to be hacked... ...and doing type analysis with .constructor also would not work without hacking..."
{ "domain": "codereview.stackexchange", "id": 43114, "lm_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, classes, enum", "url": null }
javascript, classes, enum Yes class defines a function (typeof BasicType === "function") and a function is an object. Why would inspect need to be hacked? util.inspect inspects objects. And I don't know why you use a constructor to analysis type. You can create a more robust object that can not be modified directly using Object.freeze Example In example I create a class BasicType and a similar object called BType. They look and act similarly however BType can not be changed while BasicType can not be trusted as the class syntax provides no security. In the example I make BType a function. This is just to provide a similar constructor. Ideally if you did not need a constructor you would make the BType an object. see BTypeO class BasicType { static INT = Object.create(BasicType.prototype, {name: { value: "int", enumerable: true }}); static FLOAT = Object.create(BasicType.prototype, {name: { value: "float", enumerable: true }}); constructor() { throw new Error("Basic type objects cannot be constructed"); } } const BType = (()=> { const name = (name) => Object.freeze({name: name.toLowerCase()}) return Object.freeze( Object.assign(function (){ throw new Error("Foo bar") }, ["INT","FLOAT"].reduce((obj, type) => (obj[type] = name(type), obj), {} ))); })(); // As typeof object. Example only const BTypeO = (()=> { const name = (name) => Object.freeze({name: name.toLowerCase()}) return Object.freeze(["INT","FLOAT"].reduce((obj, type) => (obj[type] = name(type), obj), {})); })(); // Proxy handler to replace unprotected identifiers (eg BasicType) const proxyHdlr = {get(t, p) {console.log("Proxy trapping ", p); return {name: "foo"}}}; console.log("--General properties BasicType, BType------------------------"); console.log("BasicType is typeof " + typeof BasicType); console.log("BType is typeof " + typeof BType); console.log("Iterate BasicType", Object.entries(BasicType) + ""); console.log("Iterate BType", Object.entries(BType) + "");
{ "domain": "codereview.stackexchange", "id": 43114, "lm_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, classes, enum", "url": null }
javascript, classes, enum try{ new BasicType() } catch(e) { console.log("BasicType constructor error: " + e.message) } try{ new BType() } catch(e) { console.log("BType constructor error: " + e.message) } console.log("--Accessing BasicType------------------------"); BasicType.INT.name = "monkeys"; console.log("BasicType.INT.name = " + BasicType.INT.name); // Still here delete BasicType.INT; // can delete try{ console.log(BasicType.INT.name) } catch(e){ console.log(e.message) }; // will throw error as INT is undefined BasicType.INT = {name: "monkey"}; // can modify / replace / alter console.log("BasicType.INT.name = " + BasicType.INT.name); BasicType = new Proxy(BasicType, proxyHdlr); // class name is writable and can silently be trapped console.log("BasicType.FLOAT.name = " + BasicType.FLOAT.name); // all access is now named foo console.log("--Accessing BType------------------------"); BType.INT.name = "monkeys"; // can not rename console.log("BType.INT.name = " + BType.INT.name); // Still here delete BType.INT; // can not delete console.log("BType.INT.name = " + BType.INT.name); // Still here BType.INT = {name: "monkey"}; // can not assign console.log("BType.INT.name = " + BType.INT.name); // Still here try{ BType = new Proxy(BType, proxyHdlr)} catch(e){ console.log("assign to BType error: " + e.message) }; // is const and can not overwrite console.log("BType.FLOAT.name = " + BType.FLOAT.name);
{ "domain": "codereview.stackexchange", "id": 43114, "lm_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, classes, enum", "url": null }
python, python-3.x, programming-challenge, strings, balanced-delimiters Title: follow-up - Checking Nested Bracket Levels in Strings Programming Challenge Question: A follow-up to this question, this post improves on test case issues. To restate problem parameters, a given string S is considered closed if it: Has a matching opening and closing bracket or no brackets at all Respects bracket nesting levels Has no more than at least one of each bracket type in it Note that the strings can contain any characters. Is there a way to this program more efficient? bracket_levels.py import re BRACKETS = dict([ ('(', ')'), ('[', ']'), ('{', '}'), ('<', '>') ]) def hasClosedBrackets(s: str) -> bool: L = len(s) if L == 0: return False if L == 1: return not (s in BRACKETS.keys() or s in BRACKETS.values()) S = s[:] def checkSubstring(sub: str): for (o, c) in BRACKETS.items(): if (o in sub and c in sub and sub.index(c) < sub.index(o)) or (sub.count(o) != sub.count(c)): return False return True for (o, c) in BRACKETS.items(): pattern = r'(?<=\{}).+?(?=\{})'.format(o, c) for match in re.findall(pattern, S): S.replace(match, '') if not checkSubstring(match): return False return checkSubstring(S) if __name__ == '__main__': tests = list(BRACKETS.keys()) tests.extend(list(BRACKETS.values())) tests += [ 'a', '(]', '((((', '({[<', ')}]>({[<', '}{', '(())', '()[{]}', 'abc', '(<[{a}s]>d)f', '<as>df', '()[{}]', '(){}[]' ] for test in tests: print(test, ':', hasClosedBrackets(test))
{ "domain": "codereview.stackexchange", "id": 43115, "lm_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, programming-challenge, strings, balanced-delimiters", "url": null }
python, python-3.x, programming-challenge, strings, balanced-delimiters for test in tests: print(test, ':', hasClosedBrackets(test)) Output ( : False [ : False { : False < : False ) : False ] : False } : False > : False a : True (] : False (((( : False ({[< : False )}]>({[< : False }{ : False (()) : False ()[{]} : False abc : True (<[{a}s]>d)f : True <as>df : True ()[{}] : True (){}[] : True Answer: Here's one opportunity to save cycles. The patterns for the brackets are getting compiled every time hasClosedBrackets is called. Something like this could be added right after BRACKETS is defined: brackets_compiled = { (o, c): re.compile(r"(?<=\{}).+?(?=\{})".format(o, c)) for o, c in BRACKETS.items() } Then the following three lines can be modified: From: for (o, c) in BRACKETS.items(): pattern = r'(?<=\{}).+?(?=\{})'.format(o, c) for match in re.findall(pattern, S): To: for (o, c), pattern in brackets_compiled.items(): for match in pattern.findall(S): With this, the patterns are compiled once and that can be looped through each time. This can also be changed to the following if (o, c) aren't needed: for pattern in brackets_compiled.values(): for match in pattern.findall(S):
{ "domain": "codereview.stackexchange", "id": 43115, "lm_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, programming-challenge, strings, balanced-delimiters", "url": null }
python, performance, matplotlib Title: Auto-fitting text into boxes in matplotlib Question: Task I tried to code a treemap function in matplotlib, and one of the challenges is auto-fitting text into boxes of different sizes in the treemap, similar to R's package ggfittext. My Code My implementation is as follows: import matplotlib.patches as mpatches
{ "domain": "codereview.stackexchange", "id": 43116, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, matplotlib", "url": null }
python, performance, matplotlib def text_with_autofit(ax, txt, xy, width, height, *, transform=None, ha='center', va='center', min_size=1, show_rect=False, **kwargs): if transform is None: transform = ax.transData # Different alignments gives different bottom left and top right anchors. x_data = {'center': (xy[0] - width/2, xy[0] + width/2), 'left': (xy[0], xy[0] + width), 'right': (xy[0] - width, xy[0])} y_data = {'center': (xy[1] - height/2, xy[1] + height/2), 'bottom': (xy[1], xy[1] + height), 'top': (xy[1] - height, xy[1])} (x0, y0) = transform.transform((x_data[ha][0], y_data[va][0])) (x1, y1) = transform.transform((x_data[ha][1], y_data[va][1])) # rectange region size to constrain the text in pixel rect_width = x1 - x0 rect_height = y1- y0 fig = ax.get_figure() dpi = fig.dpi rect_height_inch = rect_height / dpi # Initial fontsize according to the height of boxes fontsize = rect_height_inch * 72 text = ax.annotate(txt, xy, ha=ha, va=va, xycoords=transform, **kwargs) # Adjust the fontsize according to the box size, and this is the slow part. while fontsize > min_size: text.set_fontsize(fontsize) bbox = text.get_window_extent(fig.canvas.get_renderer()) if bbox.width < rect_width: break; fontsize -= 1 if show_rect: rect = mpatches.Rectangle((x_data[ha][0], y_data[va][0]), width, height, fill=False, ls='--') ax.add_patch(rect) return text Examples import matplotlib.pyplot as plt fig, ax = plt.subplots(2, 1) # In the box with the width of 0.4 and the height of 0.4 at (0.5, 0.5), add the text. text_with_autofit(ax[0], "Hello, World! How are you?", (0.5, 0.5), 0.4, 0.4, show_rect=True)
{ "domain": "codereview.stackexchange", "id": 43116, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, matplotlib", "url": null }
python, performance, matplotlib # In the box with the width of 0.6 and the height of 0.4 at (0.5, 0.5), add the text. text_with_autofit(ax[1], "Hello, World! How are you?", (0.5, 0.5), 0.6, 0.4, show_rect=True) plt.show() The resulting figures are as follows: Problem The slow part is the while loop, which sets the font size, compares text width with the box's width and decreases the font size until the text width is less than box's width. With this code, when I plotted a treemap with 15 items, it took about several seconds, while without auto-fitting, the plotting is fast. I can't accept the performance. I wonder whether there are some ways to make the code more efficient. Any help is appreciated! Thanks! Answer: You don't need to loop. Once you have an initial rendered width from get_window_extent, you can scale the font proportionally to fit the bounding box. This is potentially more accurate as it is not constrained to an integer quantity. In the following example run, the adjusted font size was found to be 10.53: from typing import Optional, Literal import matplotlib.patches as mpatches import matplotlib.pyplot as plt from matplotlib.text import Annotation from matplotlib.transforms import Transform, Bbox def text_with_autofit( ax: plt.Axes, txt: str, xy: tuple[float, float], width: float, height: float, *, transform: Optional[Transform] = None, ha: Literal['left', 'center', 'right'] = 'center', va: Literal['bottom', 'center', 'top'] = 'center', show_rect: bool = False, **kwargs, ): if transform is None: transform = ax.transData # Different alignments give different bottom left and top right anchors. x, y = xy xa0, xa1 = { 'center': (x - width / 2, x + width / 2), 'left': (x, x + width), 'right': (x - width, x), }[ha] ya0, ya1 = { 'center': (y - height / 2, y + height / 2), 'bottom': (y, y + height), 'top': (y - height, y), }[va] a0 = xa0, ya0 a1 = xa1, ya1
{ "domain": "codereview.stackexchange", "id": 43116, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, matplotlib", "url": null }
python, performance, matplotlib x0, y0 = transform.transform(a0) x1, y1 = transform.transform(a1) # rectangle region size to constrain the text in pixel rect_width = x1 - x0 rect_height = y1 - y0 fig: plt.Figure = ax.get_figure() dpi = fig.dpi rect_height_inch = rect_height / dpi # Initial fontsize according to the height of boxes fontsize = rect_height_inch * 72 text: Annotation = ax.annotate(txt, xy, ha=ha, va=va, xycoords=transform, **kwargs) # Adjust the fontsize according to the box size. text.set_fontsize(fontsize) bbox: Bbox = text.get_window_extent(fig.canvas.get_renderer()) adjusted_size = fontsize * rect_width / bbox.width text.set_fontsize(adjusted_size) if show_rect: rect = mpatches.Rectangle(a0, width, height, fill=False, ls='--') ax.add_patch(rect) return text def main() -> None: fig, ax = plt.subplots(2, 1) # In the box with the width of 0.4 and the height of 0.4 at (0.5, 0.5), add the text. text_with_autofit(ax[0], "Hello, World! How are you?", (0.5, 0.5), 0.4, 0.4, show_rect=True) # In the box with the width of 0.6 and the height of 0.4 at (0.5, 0.5), add the text. text_with_autofit(ax[1], "Hello, World! How are you?", (0.5, 0.5), 0.6, 0.4, show_rect=True) plt.show() if __name__ == '__main__': main() It's so accurate, in fact, that you may want to introduce a padding quantity. A more direct, possibly faster method that doesn't necessarily have as much feature support (tex, etc.) is: from typing import Optional, Literal import matplotlib.patches as mpatches import matplotlib.pyplot as plt from matplotlib.font_manager import FontProperties, findfont, get_font from matplotlib.text import Annotation from matplotlib.transforms import Transform from matplotlib.backends.backend_agg import get_hinting_flag
{ "domain": "codereview.stackexchange", "id": 43116, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, matplotlib", "url": null }
python, performance, matplotlib def text_with_autofit( ax: plt.Axes, txt: str, xy: tuple[float, float], width: float, height: float, *, transform: Optional[Transform] = None, ha: Literal['left', 'center', 'right'] = 'center', va: Literal['bottom', 'center', 'top'] = 'center', show_rect: bool = False, **kwargs, ) -> Annotation: if transform is None: transform = ax.transData # Different alignments give different bottom left and top right anchors. x, y = xy xa0, xa1 = { 'center': (x - width / 2, x + width / 2), 'left': (x, x + width), 'right': (x - width, x), }[ha] ya0, ya1 = { 'center': (y - height / 2, y + height / 2), 'bottom': (y, y + height), 'top': (y - height, y), }[va] a0 = xa0, ya0 a1 = xa1, ya1 x0, _ = transform.transform(a0) x1, _ = transform.transform(a1) # rectangle region size to constrain the text in pixel rect_width = x1 - x0 fig: plt.Figure = ax.get_figure() props = FontProperties() font = get_font(findfont(props)) font.set_size(props.get_size_in_points(), fig.dpi) angle = 0 font.set_text(txt, angle, flags=get_hinting_flag()) w, _ = font.get_width_height() subpixels = 64 adjusted_size = props.get_size_in_points() * rect_width / w * subpixels props.set_size(adjusted_size) text: Annotation = ax.annotate(txt, xy, ha=ha, va=va, xycoords=transform, fontproperties=props, **kwargs) if show_rect: rect = mpatches.Rectangle(a0, width, height, fill=False, ls='--') ax.add_patch(rect) return text def main() -> None: fig, ax = plt.subplots(2, 1) # In the box with the width of 0.4 and the height of 0.4 at (0.5, 0.5), add the text. text_with_autofit(ax[0], "Hello, World! How are you?", (0.5, 0.5), 0.4, 0.4, show_rect=True)
{ "domain": "codereview.stackexchange", "id": 43116, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, matplotlib", "url": null }
python, performance, matplotlib # In the box with the width of 0.6 and the height of 0.4 at (0.5, 0.5), add the text. text_with_autofit(ax[1], "Hello, World! How are you?", (0.5, 0.5), 0.6, 0.4, show_rect=True) plt.show() if __name__ == '__main__': main()
{ "domain": "codereview.stackexchange", "id": 43116, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, matplotlib", "url": null }
c#, overloading Title: Almost identical methods to print an array, differing only by argument type Question: It's very basic. I'm learning C# and I want a method to print an array in a readable format. My array could be integers, doubles, or strings. I have implemented method overloading. From the fact that my method behaves the same way regardless of the input type is, I end up copying and pasting the same code and change the argument type. My question is, is repeating the code the one and only way to do it? I'm talking about convention here. What do professionals do with this kind of problem? static string PrintArray(int[] inputArray) { string s = String.Join(", ", inputArray); return s; } static string PrintArray(string[] inputArray) { string s = String.Join(", ", inputArray); return s; } static string PrintArray(double[] inputArray) { string s = String.Join(", ", inputArray); return s; } Answer: I end up copying and pasting the same code and change the argument type This is precisely why generic types have been invented. At their very core, generic type parameters are "type variables" where the caller (i.e. not the generic class/method itself) can decide what the specific type is. That String.Join method you are using already does this, as per the MSDN documentation. This is why you're able to pass in any kind of arrays. You can rework your methods to be a single generic method as well: static string PrintArray<T>(IEnumerable<T> inputArray) { string s = String.Join(", ", inputArray); return s; }
{ "domain": "codereview.stackexchange", "id": 43117, "lm_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#, overloading", "url": null }
c#, overloading Note that I've opted to use IEnumerable<T> because it allows for many types of collections (not just T[]) to be used. This is generally advisable when the code you're writing is not bound to a specific collection type. And then you can use this method as you see fit: PrintArray<int>(new int[] { 1, 2, 3 }); PrintArray<char>(new char[] { 'a', 'b', 'c' }); PrintArray<string>(new string[] { "abc", "def" }); PrintArray<Person>(new Person[] { new Person("John", "Smith"), new Person("Tom", "Jones") }); In cases where the generic type can be inferred from the parameters you pass into the method, the compiler no longer requires you to explicitly set the generic type. The above code can be reduced to: PrintArray(new int[] { 1, 2, 3 }); PrintArray(new char[] { 'a', 'b', 'c' }); PrintArray(new string[] { "abc", "def" }); PrintArray(new Person[] { new Person("John", "Smith"), new Person("Tom", "Jones") }); This is precisely why you didn't need to specify the generic type when calling String.Join, even though it is in fact a generic method. For your particular example, your method is really just a useless wrapper around the existing String.Join method. In this case, there is little purpose to having this additional method. Your method can be safely removed from the codebase; unless you intend to expand its logic in any way that String.Join does not already provide out of the box.
{ "domain": "codereview.stackexchange", "id": 43117, "lm_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#, overloading", "url": null }
python, python-3.x, numpy Title: numpy mean azimuth with functools.reduce
{ "domain": "codereview.stackexchange", "id": 43118, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x, numpy", "url": null }
python, python-3.x, numpy Question: From the left to the right column calculating the mean azimuth, and using that mean value to calculate the subsequent columns mean value data (azimuth radians)
{ "domain": "codereview.stackexchange", "id": 43118, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x, numpy", "url": null }
python, python-3.x, numpy DATA = [[-2.3843975194179015, -2.7958149137126727, -2.6810230389823926], [0.0, -0.33324870390860456, 1.9163397142483196], [-2.775696989543418, -2.6275328191212055, -3.0806691230131427], [-2.6165411867482886, -2.8296789582836546, -2.759783341076573], [-2.616424963417955, -2.350064069320187, -2.64689261457977], [1.104212457007189, -2.515201986722916, -2.2069283847977026], [-2.8856028734085193, -3.035199951833442, -2.9077720348345553], [-2.293023583373838, -2.740650128255022, -3.025816070768775], [-2.661380976757957, -2.696160756125776, -2.797445318924053], [-2.672558649603817, 1.1374747396080642, 0.49873606783869645], [-2.891086359150823, -2.534688380524549, -2.8613440140805824], [-2.1102972290491526, -2.7231458620637, 2.5363950091287175], [-2.7499793569484, -2.781083646511631, -2.620954273599801], [-2.5524999373379402, 3.0935259791770524, -3.0773177380372885], [1.823611047211595, -1.4712997025244356, 1.342893346423129], [-2.17176255369712, -1.8898609834910174, -2.268499047776501], [0.0, 0.3051469200248977, 0.0], [0.0, 2.686707754196432, 0.3181841090845195], [-2.013127032273615, -2.585833601042828, -2.2394210436859248], [-1.8632234178313352, 1.6384133633813605, 0.0], [0.0, -2.5772232960065735, -2.3263137464465733], [-2.7073814222954895, -2.6500018958867892, -2.6400076935381716], [2.6869128840921395, 0.0, 1.9253389809746972], [-2.2915544202470555, -2.623936997218667, -3.0737947196860658], [-3.070289814572786, 1.0808289734593535, -2.8021148149172457], [-2.4204628750723356, -1.8818522770306059, 1.6542127874142347], [-1.9368378050906847, 0.7201295933844157, -0.17929292417475493], [-2.595272316663131, -2.9438016727613667, -2.6436993422121198], [0.0, 0.2440343245870421, 2.444363530333403], [-2.1107094783452096, -2.218138330346221, -0.23776292567384266], [-2.608579570855172, -2.625201629076177, -2.5100755182494647], [-2.536785971275389, -2.4152229583675955, -2.7570482180653295], [-2.462458634843743, -2.588131847455644, 0.25493101832357806], [3.050624146100454,
{ "domain": "codereview.stackexchange", "id": 43118, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x, numpy", "url": null }
python, python-3.x, numpy [-2.462458634843743, -2.588131847455644, 0.25493101832357806], [3.050624146100454, -2.196117753263519, -2.66463670917082], [-2.80535723354294, -2.3745291584752883, -2.81889385577244], [0.0, 2.886624426749002, 0.018485826949280033], [-3.0495850181137567, -0.2673600226034394, -1.7137044666766026], [0.0, -1.294898562056998, -1.825024233632855], [-2.8304708163091155, -2.8662907738811017, -2.8824638579419415], [-2.8066970357210623, -2.6752770379771706, -2.9351942988074335], [0.0, 0.9298682819793824, -0.08811157028633422], [0.0, -2.568012404513931, 0.6884719675459386], [-3.0003195279475836, -3.0100041905183095, 2.997899232919756], [None, 0.0, 0.22184922358564446], [None, 2.0513956490022247, 0.0], [None, 3.139803691103381, -0.23697917750286965], [None, -2.314698060002942, -2.2962275991831933], [None, 0.0, 0.2470592881115847], [None, -2.2270407983925375, -2.379935787161442], [None, -2.7200551654310563, -3.013393418145732], [None, -2.9700772916183, -2.626022914672403], [None, None, -2.646662549139035], [None, None, -2.713921422380295], [None, None, 0.0], [None, None, -2.3713496027483574], [None, None, -2.826763915677864], [None, None, 2.4941269118667955], [None, None, -0.21200517436725835], [None, None, -0.47227943847233556], [None, None, 3.078678341388149], [None, None, 2.307358803457483]]
{ "domain": "codereview.stackexchange", "id": 43118, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x, numpy", "url": null }
python, python-3.x, numpy main.py import functools import numpy as np def _mean_reduction(col1: np.ndarray, col2: np.ndarray) -> np.ndarray: # where col1 is nan use the col2 value col1[np.isnan(col1)] = col2[np.isnan(col1)] mean_rads = ( np.arctan2(np.sin(col1)+np.sin(col2), np.cos(col1)+np.cos(col2))) return mean_rads def start(azi:np.ndarray) -> None: """calc mean azimuth""" # the 0 values are 99% likely an error in the data so nan them to ignore azi[azi == 0] = np.nan mean_rads = functools.reduce( _mean_reduction, # start ittr with the second column np.swapaxes(azi[:, 1:, np.newaxis], 0, 1), # init with first column azi[:, 0, np.newaxis] ) print(np.rint(np.rad2deg(np.column_stack([azi, mean_rads])) % 360)) if __name__ == '__main__': start(np.array(DATA, dtype=float))
{ "domain": "codereview.stackexchange", "id": 43118, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x, numpy", "url": null }
python, python-3.x, numpy if __name__ == '__main__': start(np.array(DATA, dtype=float)) result in degs [[223. 200. 206. 209.] [341. 341. 110. 45.] [201. 209. 183. 194.] [210. 198. 202. 203.] [210. 225. 208. 213.] [ 63. 216. 234. 187.] [195. 186. 193. 192.] [229. 203. 187. 201.] [208. 206. 200. 203.] [207. 65. 29. 82.] [194. 215. 196. 200.] [239. 204. 145. 183.] [202. 201. 210. 206.] [214. 177. 184. 190.] [104. 276. 77. 134.] [236. 252. 230. 237.] [ 17. 17. nan nan] [154. 154. 18. 86.] [245. 212. 232. 230.] [253. 94. nan nan] [212. 212. 227. 220.] [205. 208. 209. 208.] [154. nan 110. 110.] [229. 210. 184. 202.] [184. 62. 199. 161.] [221. 252. 95. 166.] [249. 41. 350. 337.] [211. 191. 209. 205.] [ 14. 14. 140. 77.] [239. 233. 346. 291.] [211. 210. 216. 213.] [215. 222. 202. 210.] [219. 212. 15. 295.] [175. 234. 207. 206.] [199. 224. 198. 205.] [165. 165. 1. 83.] [185. 345. 262. 263.] [286. 286. 255. 271.] [198. 196. 195. 196.] [199. 207. 192. 197.] [ 53. 53. 355. 24.] [213. 213. 39. 126.] [188. 188. 172. 180.] [ nan nan 13. 13.] [118. 118. nan nan] [180. 180. 346. 263.] [227. 227. 228. 228.] [ nan nan 14. 14.] [232. 232. 224. 228.] [204. 204. 187. 196.] [190. 190. 210. 200.] [ nan nan 208. 208.] [ nan nan 205. 205.] [ nan nan nan nan] [ nan nan 224. 224.] [ nan nan 198. 198.] [ nan nan 143. 143.] [ nan nan 348. 348.] [ nan nan 333. 333.] [ nan nan 176. 176.] [ nan nan 132. 132.]] Answer: This conditional reassignment: col1[np.isnan(col1)] = col2[np.isnan(col1)] can be replaced with the purpose-built np.nan_to_num(x=col1, nan=col2, copy=False)
{ "domain": "codereview.stackexchange", "id": 43118, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x, numpy", "url": null }
python, python-3.x, numpy can be replaced with the purpose-built np.nan_to_num(x=col1, nan=col2, copy=False) If your azi grows bigger than 3 in the small axis, you'll want to get rid of functools and instead use ufunc.reduce. Your use of reduce is needlessly complicated: you can let it use the default initialiser, and avoid slicing it yourself. You can replace swapaxes with a single .T. Suggested def _mean_reduction(col1: np.ndarray, col2: np.ndarray) -> np.ndarray: # where col1 is nan, use the col2 value np.nan_to_num(x=col1, nan=col2, copy=False) return np.arctan2( np.sin(col1) + np.sin(col2), np.cos(col1) + np.cos(col2), ) def start() -> None: """calc mean azimuth""" azi = np.array(DATA, dtype=float) # the 0 values are 99% likely an error in the data so nan them to ignore azi[azi == 0] = np.nan mean_rads = functools.reduce(_mean_reduction, azi.T) assert np.allclose(mean_rads, MEAN_RADS_EXPECTED, equal_nan=True) assert np.allclose(azi, AZI_EXPECTED, equal_nan=True) if __name__ == '__main__': start()
{ "domain": "codereview.stackexchange", "id": 43118, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x, numpy", "url": null }
c#, performance, collections Title: Faster way to find items from one list in another one Question: I would like to check if a string appears in a list of strings. For that, I have chosen the List<string> type, as follows: public List<string> list_statuses; // list_statuses gets filled with 173 entries // Regular execution of: string text_list = ...; // Mostly, this is an empty string int list_statuses_count = list_statuses == null? 0 : list_statuses.Count; int text_list_count = text_list == null? 0 : text_list.Count(); log.Debug($"Before the foreach: list_statuses contains [{list_statuses_count}] elements, " + "and textList contains [{text_list_count}] elements"); foreach (string entry2 in list_statuses) { if ((text_list == null) || (!text_list.Contains(entry2))) { // do_something(); } } log.Debug("After the foreach"); Examples of log entries: 2022-03-21 17:06:58.6534 | Debug | Before the foreach: list_statuses contains [173] elements, and textList contains [0] elements 2022-03-21 17:07:00.5896 | Debug | After the foreach => duration : ±2 seconds 2022-03-21 17:07:00.6455 | Debug | Before the foreach: list_statuses contains [173] elements, and textList contains [0] elements 2022-03-21 17:07:02.3970 | Debug | After the foreach => duration: ±2 seconds 2022-03-21 17:07:02.4416 | Debug | Before the foreach: list_statuses contains [173] elements, and textList contains [0] elements 2022-03-21 17:07:04.1687 | Debug | After the foreach => duration: ±2 seconds This piece of code is needed inside a server application. Waiting about 2 seconds for a simple search is quite long. Is there another way to run through a list of strings in another way? (Both the "list of strings" type and the "way to run" (foreach) may be replaced)
{ "domain": "codereview.stackexchange", "id": 43119, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, performance, collections", "url": null }
c#, performance, collections Answer: One way to boost the performance is to take advantage of sorting. So if you can sort the list_statuses and you can sort the split version of the text_list then the lookup could be faster IEnumerable<string> words = text_list.Split(" ").Distinct().OrderBy(w => w); IEnumerable<string> statuses = list_statuses.OrderBy(s => s); Note: I've added a Distinct call as well to make sure that all unique words a present only once. Finding all matches: var matches = words.Intersect(statuses); Finding the first match: var firstMatch = words.FirstOrDefault(statuses.Contains); If you want to reuse the ordered list_statuses multiple times then it would make sense to store the materialized version of it .
{ "domain": "codereview.stackexchange", "id": 43119, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, performance, collections", "url": null }
performance, beginner, c, image Title: Creation & pixel manipulation of 24 bit TARGA Question: I wrote this code to get familiar with structs in C. It allows the creation and exporting of a 24 bit TGA image and changing the color of individual pixels. My concern is the setPixel function, and how I could improve its performance. First the conversion from x,y to an array index, how can I minimize/eliminate the need for this? I think I could just use a two dimensional array. Second, is the setting of the pixel's RGB values. How could this be optimized? Would a single assignment for all three at once improve it? How would I do this? Lastly, I was wondering if there's anyway to make makeImage and saveImage less verbose. I wasn't able to find a better solution. #include <stdio.h> #include <stdlib.h> #include <stdint.h> #define HEADER_BYTES 18 // Ammount of bytes header should take up typedef struct TGAImg_t{ uint8_t idLength; // Length of image ID field (0-255) uint8_t colorMapType; // If a color map is present (1) or not (0) uint8_t imageType; // Compression and color types (0-3 and 9-11) uint16_t colorMapOrigin; // Index of first color map entry uint16_t colorMapLength; // Count of color map entries uint8_t colorMapEntrySize; // Number of bits in each color map entry. 16 for Targa 16, 24 for Targa 24... uint16_t xOrigin; // X coord of the lower left corner of the image uint16_t yOrigin; // Y coord of the lower left corner of the image uint16_t width; // Width of the image in pixels uint16_t height; // Height of the image in pixels uint8_t imagePixelSize; // Number of bits in a stored pixel index uint8_t imageDescriptorByte;// Document says to just keep this byte as 0 uint8_t imageDataField[0]; // Array of image pixels. } TGAImg; typedef struct RGB_t{ uint8_t red; uint8_t green; uint8_t blue; } RGB;
{ "domain": "codereview.stackexchange", "id": 43120, "lm_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, beginner, c, image", "url": null }
performance, beginner, c, image typedef struct RGB_t{ uint8_t red; uint8_t green; uint8_t blue; } RGB; TGAImg* makeImage(uint8_t idLength, uint8_t colorMapType, uint8_t imageType, uint16_t colorMapOrigin, uint16_t colorMapLength, uint8_t colorMapEntrySize, uint16_t xOrigin, uint16_t yOrigin, uint16_t width, uint16_t height, uint8_t imagePixelSize, uint8_t imageDescriptorByte){ // Allocate memory for header + image pixels (using info from header params) uint32_t dataFieldBytes = width * height * (imagePixelSize / 8); TGAImg* img = calloc(HEADER_BYTES + dataFieldBytes, 1 ); if (!img){ printf("ERROR: calloc fail for img @ makeImg"); exit(EXIT_FAILURE); } // Set header values img->idLength = idLength; img->colorMapType = colorMapType; img->imageType = imageType; img->colorMapOrigin = colorMapOrigin; img->colorMapLength = colorMapLength; img->colorMapEntrySize = colorMapEntrySize; img->xOrigin = xOrigin; img->yOrigin = yOrigin; img->width = width; img->height = height; img->imagePixelSize = imagePixelSize; img->imageDescriptorByte = imageDescriptorByte; return img; } // Writes contents of a TGAImg struct to a image of name imageName void saveImage(char imageName[], TGAImg* img){ FILE* imageFile = fopen(imageName, "wb");
{ "domain": "codereview.stackexchange", "id": 43120, "lm_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, beginner, c, image", "url": null }
performance, beginner, c, image fwrite(&img->idLength, sizeof(img->idLength), 1, imageFile); fwrite(&img->colorMapType, sizeof(img->colorMapType), 1, imageFile); fwrite(&img->imageType, sizeof(img->imageType), 1, imageFile); fwrite(&img->colorMapOrigin, sizeof(img->colorMapOrigin), 1, imageFile); fwrite(&img->colorMapLength, sizeof(img->colorMapLength), 1, imageFile); fwrite(&img->colorMapEntrySize, sizeof(img->colorMapEntrySize), 1, imageFile); fwrite(&img->xOrigin, sizeof(img->xOrigin), 1, imageFile); fwrite(&img->yOrigin, sizeof(img->yOrigin), 1, imageFile); fwrite(&img->width, sizeof(img->width), 1, imageFile); fwrite(&img->height, sizeof(img->height), 1, imageFile); fwrite(&img->imagePixelSize, sizeof(img->imagePixelSize), 1, imageFile); fwrite(&img->imageDescriptorByte, sizeof(img->imageDescriptorByte), 1, imageFile); fwrite(&img->imageDataField, img->width * img->height * (img->imagePixelSize / 8), 1, imageFile); fclose(imageFile); } void setPixel(TGAImg* img, RGB color, int x, int y){ uint32_t index = ((y * img->width) + x) * 3; // Convert x and y to index for array // Apply pixel change to all colors img->imageDataField[index] = color.blue; img->imageDataField[index+1] = color.green; img->imageDataField[index+2] = color.red; } Answer: Performance Row vs. Pixel In addition to the slow setPixel(), offer a setLine() that offers reduced repeated calculations in setting many pixels of the same color. Block vs. Pixel In addition to the slow setPixel(), offer a copyBlock() that offers reduced repeated calculations in setting a rectangle of pixels. Employ memcpy() when possible. Portability File vs. Code structures TGAImg is app to contain implementation specific padding and the TARGA file have a fixed (likely no padding) definition. This is easy to in C code if a some of extended language qualifier like packed is allowed. // typedef struct TGAImg_t{ typedef struct packed TGAImg_t{ // example
{ "domain": "codereview.stackexchange", "id": 43120, "lm_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, beginner, c, image", "url": null }
performance, beginner, c, image If no such language extension is available, it is work to write portable code. For the most part, code needs to reads the file header as an array of bytes and then form TGAImg one member at a time - as OP did with writing saveImage(). Endian Byte order may differ form file format to code. Various endian functions exist. // fwrite(&img->colorMapOrigin, sizeof(img->colorMapOrigin), 1, imageFile); uint16_t u16 = endian_host_to_file16(img->colorMapOrigin); fwrite(&u16, sizeof u16, 1, imageFile); Pedantic: int may be 16-bit. Various code needs to account for that. // void setPixel(TGAImg* img, RGB color, int x, int y){ void setPixel(TGAImg* img, RGB color, int_fast32_t, x, int_fast32_t y){ Lastly, I was wondering if there's anyway to make makeImage and saveImage less verbose. I wasn't able to find a better solution. Unclear why code does not simple use and let the caller fill in most members. TGAImg *makeImage(const TGAImg *init_values) Bug? Trouble when imagePixelSize is not a multiple of 8. Pixel depth 15 allowed. // uint32_t dataFieldBytes = width * height * (imagePixelSize / 8); // Possible solution - needs review. uint32_t dataFieldBytes = width * height * ((imagePixelSize + 7) / 8);
{ "domain": "codereview.stackexchange", "id": 43120, "lm_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, beginner, c, image", "url": null }
programming-challenge, haskell Title: Function to sum all Armstrong numbers within a range Question: I've tried to solve a challenge posted on a LinkedIn forum using Haskell - a language I'm still learning the basics of - and, while the code works correctly, I would like to get some feedback on the coding style, and learn what could be improved. The task is to add all Armstrong numbers within a range. An Armstrong (or narcissistic) number is a number that is equal to the sum of all its digits, each raised to the power of the length of its digits. For instance, 153 is an Armstrong number because \$1^3 + 5^3 + 3^3\$ equals 153. The range can be given in any order - that is 5 10 and 10 5 denote the same interval, that is, all numbers between 5 and 10 (boundaries included). And here's my code: digits :: (Integral n) => n -> [n] digits n | n < 10 = [n] | otherwise = digits (n `div` 10) ++ [n `mod` 10] numberLength :: Int -> Int numberLength = length . digits powerNumber :: Int -> [Int] powerNumber n = map (\d -> (d ^ exponent)) listOfDigits where exponent = numberLength n listOfDigits = digits n isArmstrong :: Int -> Bool isArmstrong a = a == sum (powerNumber a) sortEnds :: Int -> Int -> [Int] sortEnds a b = if a < b then [a, b] else [b, a] sumAllArmstrongNumber :: Int -> Int -> Int sumAllArmstrongNumber a b = sum([x | x <- [start..end], isArmstrong x]) where [start, end] = sortEnds a b Any feedback is much appreciated! Answer: I would like to get some feedback on the coding style, and learn what could be improved.
{ "domain": "codereview.stackexchange", "id": 43121, "lm_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", "url": null }
programming-challenge, haskell Answer: I would like to get some feedback on the coding style, and learn what could be improved. First of all, it's fantastic that all your functions have proper types, consistent indentation and style. Keep that in your future code style! Prefer divMod or quotRem If you use both y `div` x and y `mod` x for the same x and y then you should use divMod instead. Even better, use quotRem if possible. quotRem returns the same results for positive numbers but is slightly faster: digits :: (Integral n) => n -> [n] digits n | n < 10 = [n] | otherwise = let (q, r) = n `quotRem` 10 in digits q ++ [r] Cons; don't append There's one big drawback in the new digits function though: we're always appending a single element. This yields an \$\mathcal O(n^2)\$ algorithm, since (x:xs) ++ [y] = x : (xs ++ [y]). Instead, we should cons the new element on the rest of the list: digits :: (Integral n) => n -> [n] digits n | n < 10 = [n] | otherwise = let (q, r) = n `quotRem` 10 in r : digits q Note that this will return the digits in reverse order but that's fine. If you want the digits in the original order, consider using reverse on the result: digits :: (Integral n) => n -> [n] digits = reverse . go where go n = case n `quotRem` 10 of (0, r) -> [r] (q, r) -> r : go q I'm a fan of case for this style of quotRem usage, but that's just my personal opinion. Map vs pointfree vs comprehension Warning: this section and mostly about personal preference. In the following code, listOfDigits and expontent are defined and used once: powerNumber :: Int -> [Int] powerNumber n = map (\d -> (d ^ exponent)) listOfDigits where exponent = numberLength n listOfDigits = digits n I'd personally prefer digits n instead of listOfDigits, since it's only used as an argument for map: powerNumber n = map (\d -> (d ^ exponent)) $ digits n where exponent = numberLength n
{ "domain": "codereview.stackexchange", "id": 43121, "lm_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", "url": null }
programming-challenge, haskell Next (\d -> (d ^ exponent)) is (^exponent), which is preferred by some: powerNumber n = map (^exponent) $ digits n where exponent = numberLength n But in terms of readability, a list comprehension might even better: powerNumber :: Int -> [Int] powerNumber n = [ d ^ exponent | d <- digits n ] where exponent = numberLength n Add additional information in return types sortEnds :: Int -> Int -> [Int] sortEnds a b = if a < b then [a, b] else [b, a] The return type is slightly misleading: sortEnds always returns exactly two elements. So we should use a pair: sortEnds :: Int -> Int -> (Int, Int) sortEnds a b = if a < b then (a, b) else (b, a) Remove superfluous parentheses sumAllArmstrongNumber :: Int -> Int -> Int sumAllArmstrongNumber a b = sum([x | x <- [start..end], isArmstrong x]) where [start, end] = sortEnds a b I'd remove the explicit parentheses around sum's argument: sumAllArmstrongNumber :: Int -> Int -> Int sumAllArmstrongNumber a b = sum [x | x <- [start..end], isArmstrong x] where (start, end) = sortEnds a b
{ "domain": "codereview.stackexchange", "id": 43121, "lm_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", "url": null }
python, python-3.x Title: Finding the modal hue of an image Question: As part of my first python project, I needed to know what the dominant hue of an image was. I started with finding the modal hue of the image, but the results seemed really odd in images with pale/dark backgrounds. This lead me to applying a threshold to both the saturation and value channels of a HSV image, so as to ignore pale and dark colours before finding the mode of the remaining hues. I have tried to improve the speed by using numpy instead of a list comprehension, however this ended up being just over twice as slow. I would appreciate any improvements, especially towards performance, but also to making it more pythonic. from PIL import Image from scipy import stats def get_hue(image_path): """ Returns the modal hue of the image 0-360 after applying a saturation and value threshold of 30% If there are no pixels that pass the threshold, the value threshold is dropped down to 10% """ image = Image.open(image_path).convert("HSV") colours = image.getdata() s_threshold = 0.3*255 v_threshold = 0.1*255 filtered_colors = [x[0] for x in colours if x[1]> s_threshold and x[2] > s_threshold] if not filtered_colors: filtered_colors = [x[0] for x in colours if x[1] > s_threshold and x[2] > v_threshold] return ((stats.mode(filtered_colors).mode[0]/255)*360)//1 The Numpy Version from PIL import Image from scipy import stats import numpy as np
{ "domain": "codereview.stackexchange", "id": 43122, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x", "url": null }
python, python-3.x The Numpy Version from PIL import Image from scipy import stats import numpy as np def get_hue_numpy(image_path): """ Returns the modal hue of the image 0-360 after applying a saturation and value threshold of 30% If there are no pixels that pass the threshold, the value threshold is dropped down to 10% """ image = Image.open(image_path).convert("HSV") s_threshold = 0.3*255 v_threshold = 0.1*255 colours = np.array(image.getdata()) filtered_colors = colours[(colours[:,1] > s_threshold) & (colours[:,2] > s_threshold)][:,0] if not filtered_colors.any(): filtered_colors = colours[(colours[:,1] > s_threshold) & (colours[:,2] > v_threshold)][:,0] return ((stats.mode(filtered_colors).mode[0]/255)*360)//1 Answer: I have tried to improve the speed by using numpy instead of a list comprehension Your current solution uses two list comprehensions, and you haven't shown your Numpy attempt. I'll demonstrate what I consider to be idiomatic Numpy, which is indeed faster. Other points: Add PEP484 type hints. I don't see why you should effectively floor (though in an awkward way, with //1). Why not just return the float? If the caller doesn't like it, they can round(). Suggested import numpy as np from PIL import Image from scipy import stats def get_hue(image_path: str) -> float: """ Returns the modal hue of the image 0-360 after applying a saturation and value threshold of 30% If there are no pixels that pass the threshold, the value threshold is dropped down to 10% """ image = Image.open(image_path).convert("HSV") colours = np.array(image) def val_predicate(val): return colours[..., 2] > val*255 val_passes = val_predicate(0.3) if not np.any(val_passes): val_passes = val_predicate(0.1) sat_passes = colours[..., 1] > 0.3*255 filtered_hue = colours[np.bitwise_and(sat_passes, val_passes), 0] mode, count = stats.mode(filtered_hue) return mode / 255 * 360
{ "domain": "codereview.stackexchange", "id": 43122, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x", "url": null }
python, python-3.x Timing For a 1920x1080 914KiB JPG image, the old list comprehension method completes in 351 ms and the new one in 111 ms. Profiling I encourage you to learn cProfile. Your old numpy attempt shows, at the top, 14016 function calls (13519 primitive calls) in 0.670 seconds Ordered by: internal time ncalls tottime percall cumtime percall filename:lineno(function) 2 0.572 0.286 0.572 0.286 {built-in method numpy.array} This shows that it's a problem in the array construction itself. Drop your getdata() and the problem goes away.
{ "domain": "codereview.stackexchange", "id": 43122, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x", "url": null }
python-3.x, sympy Title: Systems of equations solver with sympy Question: So this is my first Python project and hoped for a bit of feedback. I'm trying to make a little program, where I can insert n equations and run a numerical solve. I ended up using tkinter for the GUI as it seemed very approachable, and sympy for the math part. I'm unsure if the overall structure of the program, is good or bad. And some functions caused me a bit of trouble. Especially the define_eqsys_vars I feel like became needlessly complicated. import tkinter as tk import sympy as sp from tkinter import Text def clean_input(x: str) -> list: temp = x.replace(' ', '').split('\n') cleaned = list(filter(None, temp)) return cleaned def create_res(x: str): split = x.split('=') res_eq = (sp.parse_expr(split[0], evaluate=False) - sp.parse_expr(split[1], evaluate=False)) return res_eq def define_eqsys_vars(eqsys: list): unique_vars = set() for eq in eqsys: unique_vars = unique_vars.union(eq.atoms(sp.Symbol)) # create a list with all symbols converted to text, and join - var() takes a string var_string = ', '.join([repr(eq) for eq in unique_vars]) variables = sp.var(var_string) return variables def create_eqsys(x: list) -> tuple: equation_system = [create_res(eq) for eq in x] variables = define_eqsys_vars(equation_system) return equation_system, variables def create_guess(eqsys: list) -> tuple: unique_vars = set() for eq in eqsys: unique_vars = unique_vars.union(eq.atoms(sp.Symbol)) guess = [1] * len(unique_vars) return tuple(guess) def solve_eqsys(eqsys, symbols, guess): result = sp.nsolve(tuple(eqsys), symbols, guess) return result def main(): # input, from tkinter window text_input = inputtxt.get("1.0", "end-1c") # clean text cleaned_text = clean_input(text_input)
{ "domain": "codereview.stackexchange", "id": 43123, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python-3.x, sympy", "url": null }
python-3.x, sympy # clean text cleaned_text = clean_input(text_input) # create system of equations and try to solve it eqsys, eqsys_vars = create_eqsys(cleaned_text) guess = create_guess(eqsys) solution = solve_eqsys(eqsys, eqsys_vars, guess) # text output Output.insert(tk.END, f"Solution: {solution}") return # Build GUI root = tk.Tk() toplabel = tk.Label(text="Start variable name with a letter") inputtxt = Text(root, height=30, width=50, bg="light yellow") Output = Text(root, height=30, width=25, bg="light cyan") Display = tk.Button(root, height=2, width=20, text="Solve system of equations", command=lambda: main()) toplabel.pack() inputtxt.pack() Display.pack() Output.pack() tk.mainloop() Answer: You shouldn't list() your filter. You can just return the iterable. Rather than forming a subtraction from your user's equation, why not just... form an equation, and use the default solve instead of nsolve? An Equality object can give you its free_symbols directly, which will be simpler than your use of atoms. Don't sp.var and don't form a string to give it - just use free_symbols directly. You don't need to make a (fairly unsafe, since it's uninformed) guess if you just call solve. Your application doesn't render very well for me - it fills the entire height of the screen. I haven't bothered to try fixing this. Don't leave state or setup code in the global namespace. The quickest fix in your case is to make main a closure. Suggested import tkinter as tk from typing import Iterable, Sequence import sympy as sp from tkinter import Text def clean_input(x: str) -> Iterable[str]: temp = x.replace(' ', '').split('\n') return filter(None, temp) def create_res(x: str) -> sp.Equality: lhs, rhs = x.split('=') res_eq = sp.Eq( sp.parse_expr(lhs, evaluate=False), sp.parse_expr(rhs, evaluate=False) ) return res_eq
{ "domain": "codereview.stackexchange", "id": 43123, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python-3.x, sympy", "url": null }
python-3.x, sympy def define_eqsys_vars(eqsys: Iterable[sp.Equality]) -> set[sp.Symbol]: unique_vars = set() for eq in eqsys: unique_vars |= eq.free_symbols return unique_vars def create_eqsys(x: list) -> tuple[ list[sp.Equality], set[sp.Symbol], ]: equation_system = [create_res(eq) for eq in x] variables = define_eqsys_vars(equation_system) return equation_system, variables def solve_eqsys(eqsys: Sequence[sp.Equality], symbols: Sequence[sp.Symbol]) -> dict: return sp.solve(eqsys, symbols) def setup() -> None: def main() -> None: # input, from tkinter window text_input = inputtxt.get("1.0", "end-1c") # clean text cleaned_text = clean_input(text_input) # create system of equations and try to solve it eqsys, eqsys_vars = create_eqsys(cleaned_text) solution = solve_eqsys(eqsys, eqsys_vars) # text output Output.insert(tk.END, f"Solution: {solution}") # Build GUI root = tk.Tk() toplabel = tk.Label(text="Start variable name with a letter") inputtxt = Text(root, height=30, width=50, bg="light yellow") Output = Text(root, height=30, width=25, bg="light cyan") Display = tk.Button( root, height=2, width=20, text="Solve system of equations", command=main, ) toplabel.pack() inputtxt.pack() Display.pack() Output.pack() tk.mainloop() if __name__ == '__main__': setup()
{ "domain": "codereview.stackexchange", "id": 43123, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python-3.x, sympy", "url": null }
javascript, comparative-review, react.js, dynamic-loading, constants Title: Constructing routes from imported URL constants Question: There is a file created with the project paths in a dictionary. Example: export const URL = { DASHBOARD: '/dashboard', SETTINGS: '/settings', PROFILE: '/profile', PRODUCTS: '/products/' }; And in the file where the routes are used, the urls are imported. A coworker and I are debating about two ways to write the code. One of us says that it is more readable import file and do destructuring. import { URL } from './urls.constants'; export default function ROUTES() { const { DASHBOARD, SETTINGS, PROFILE, PRODUCTS, etc.. } = URL; return ( ... <Route path={DASHBOARD} /> <Route path={SETTINGS} /> <Route path={PROFILE} /> <Route path={PRODUCTS } /> ... ); The other one of us says that is equal or more readable use the dictionary or enum. import { URL } from './urls.constants'; export default function ROUTES() { return ( ... <Route path={URL.DASHBOARD} /> <Route path={URL.SETTINGS} /> <Route path={URL.PROFILE} /> <Route path={URL.PRODUCTS } /> ... ); We know that both options are correct, but what is the best option regarding readability and clean code? Answer: Personally, I think that this comes down to developer preference, although, preference aside, you should be programming in a style that adheres to your company/team's style guide (if one exists). However, I do think that there's an another solution in there, but it depends upon an assumption that you haven't explicitly declared: Assuming that every URL in your URL dictionary needs to be registered via the <Route> element, could you not combine Object.entries() and .map() to dynamically generate the routes? import { URL } from './urls.constants'; export default function ROUTES() { return ( ... {Object.entries(URL).map(([name, path]) => <Route key={name} path={path} />)} ... ); }
{ "domain": "codereview.stackexchange", "id": 43124, "lm_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, comparative-review, react.js, dynamic-loading, constants", "url": null }
javascript, comparative-review, react.js, dynamic-loading, constants Again, this solution depends upon an assumption that I've made on your scenario. But hopefully, either way, it gives you something to think about!
{ "domain": "codereview.stackexchange", "id": 43124, "lm_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, comparative-review, react.js, dynamic-loading, constants", "url": null }
c#, .net, async-await, timeout Title: Concise handling of async tasks with timeouts in c# Question: Often I have async functions that I want to be able to time out, this timeout is independent of the greater scope of the application. However the function should also take into consideration the greater scope and thus needs to receive the CancellationToken that will indicate when the application scope or some other higher-level scope cancels. I haven't been able to find an easy/standard way to deal with this type of situation, so I decided to write a small extension method to create a new CancellationToken that will cancel once the original cancels but also after a timeout period. I created the following to be able to easily/concisely add a token with timeout to any task accepting a cancellation token: public static CancellationToken NewWithTimeout(this CancellationToken original, int millisecondTimeout) { // EDIT: From comment, this part can be condensed into: var src = CancellationTokenSource.CreateLinkedTokenSource(original); src.CancelAfter(millisecondTimeout); // CancellationTokenSource src = new(millisecondTimeout); // original.Register(src.Cancel); return src.Token; } public static CancellationToken NewWithTimeout(this CancellationToken original, TimeSpan timeout) { // EDIT: From comment, this part can be condensed into: var src = CancellationTokenSource.CreateLinkedTokenSource(original); src.CancelAfter(timeout); // CancellationTokenSource src = new(timeout); // original.Register(src.Cancel); return src.Token; }
{ "domain": "codereview.stackexchange", "id": 43125, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, .net, async-await, timeout", "url": null }
c#, .net, async-await, timeout Then I also added the following to facilitate creating methods that can be timed out. This way the method will explicitly show it expects a timeout and it will internally have access to the timeout passed in to be used internally. public class CancellationTokenWithTimeout { public CancellationToken Original { get; set; } public CancellationToken Combined { get; set; } public TimeSpan Timeout { get; set; } public CancellationTokenWithTimeout(int millisecondTimeout, CancellationToken original) { CancellationTokenSource src = new(millisecondTimeout); original.Register(src.Cancel); Original = original; Combined = src.Token; Timeout = TimeSpan.FromMilliseconds(millisecondTimeout); } public CancellationTokenWithTimeout(TimeSpan timeout, CancellationToken original) { CancellationTokenSource src = new(timeout); original.Register(src.Cancel); Original = original; Combined = src.Token; Timeout = timeout; } } public static class ExtensionMethods { public static CancellationTokenWithTimeout AddTimeout(this CancellationToken original, int millisecondTimeout) { return new CancellationTokenWithTimeout(millisecondTimeout, original); } public static CancellationTokenWithTimeout AddTimeout(this CancellationToken original, TimeSpan timeout) { return new CancellationTokenWithTimeout(timeout, original); } public static CancellationToken NewWithTimeout(this CancellationToken original, int millisecondTimeout) { CancellationTokenSource src = new(millisecondTimeout); original.Register(src.Cancel); return src.Token; }
{ "domain": "codereview.stackexchange", "id": 43125, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, .net, async-await, timeout", "url": null }
c#, .net, async-await, timeout public static CancellationToken NewWithTimeout(this CancellationToken original, TimeSpan timeout) { CancellationTokenSource src = new(timeout); original.Register(src.Cancel); return src.Token; } } With this implementation you can now do the following: public class SomeWorker : BackgroundService { private readonly ILogger<SomeWorker> _logger; public SomeWorker(ILogger<SomeWorker> logger) { _logger = logger; } protected override async Task ExecuteAsync(CancellationToken stoppingToken) { while (!stoppingToken.IsCancellationRequested) { _logger.LogInformation("SomeWorker running at: {time}", DateTimeOffset.Now); try { var longTask = DoSomethingAsync("Hello", stoppingToken.NewWithTimeout(2000)); await Task.Delay(1000, stoppingToken); _logger.LogInformation("One second has passed!"); await longTask; _logger.LogInformation("Long task is done."); }catch (OperationCanceledException ex) { if (stoppingToken.IsCancellationRequested) _logger.LogInformation("We got cancelled!"); else _logger.LogInformation("Task timed out!"); } _logger.LogInformation("Another Test with explicit timeout!");
{ "domain": "codereview.stackexchange", "id": 43125, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, .net, async-await, timeout", "url": null }
c#, .net, async-await, timeout } _logger.LogInformation("Another Test with explicit timeout!"); try { var longTask = DoSomethingAsyncWithTimeout("Hello", stoppingToken.AddTimeout(2000)); await Task.Delay(1000, stoppingToken); _logger.LogInformation("One second has passed!"); await longTask; _logger.LogInformation("Long task is done."); } catch (OperationCanceledException ex) { if (stoppingToken.IsCancellationRequested) _logger.LogInformation("We got cancelled!"); else _logger.LogInformation("Task timed out! This must have come from the inner task..."); } catch (TimeoutException timeout) { _logger.LogInformation("Task timed out! Either from the task or the inner task"); } } } public async Task<string> DoSomethingAsync(string param1, CancellationToken cancellationToken) { while (!cancellationToken.IsCancellationRequested) { (bool done, string result) = await SomeOtherAsync(cancellationToken.Combined); if (done) return result; } throw new TaskCanceledException(); }
{ "domain": "codereview.stackexchange", "id": 43125, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, .net, async-await, timeout", "url": null }
c#, .net, async-await, timeout } public async Task<string> DoSomethingAsyncWithTimeout(string param1, CancellationTokenWithTimeout cancellationToken) { while (!cancellationToken.Combined.IsCancellationRequested) { (bool _, string intermediateresult) = await SomeOtherAsync(cancellationToken.Combined); (bool done, string result) = await SomeOtherAsyncWithTimeout(intermediateresult, cancellationToken.Original, cancellationToken.Timeout); if (done) return result; } if (cancellationToken.Original.IsCancellationRequested) throw new TaskCanceledException(); else throw new TimeoutException(); } } I would like to know if there are any issues with this implementation and also if there's a similarly concise way of doing this without any custom extension. Or any improvements if this is a sensible thing to do. Answer: There is a .NET library called Polly, which defines a couple of generic resilience policies. The most well-known ones are Timeout, Retry and Circuit Breaker. The policies are used as decorators. You define how a policy should behave and then apply it to any arbitrary code. The sync and async codes are handled differently so you have to be aware of this when you define a policy. The Timeout policy can work in two modes: optimistic and pessimistic. The former one allows you to cancel the decorated method either by the user provided CancellationToken or by the timeout policy itself. public IAsyncPolicy CreateTimeoutConstraint(TimeSpan threshold) => Policy.TimeoutAsync(threshold, TimeoutStrategy.Optimistic); public async Task ExecuteMethodWithTimeConstraintAsync(CancellationToken userProvideToken) { var timeoutPolicy = CreateTimeoutConstraint(TimeSpan.FromSeconds(2)); await timeoutPolicy.ExecuteAsync(async (ct) => await SomeBackgroundTask(ct), userProvideToken); }
{ "domain": "codereview.stackexchange", "id": 43125, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, .net, async-await, timeout", "url": null }
c#, error-handling Title: Trying to assign property until the setter stops throwing the exception Question: Can I improve this code and make it more beautiful? For example, for expressions in ReadConsole method is ugly for me. string _name; public string Name { get => _name; set { // Only letters, whitespaces and '-' are avaiable if (value.All(c => char.IsLetter(c) || new string(" -").Contains(c))) _name = value; else throw new ArgumentException("Oops!"); } } internal void ReadConsole() { for (bool success=false; success == false;) { Console.Write("Enter Name (only letter, spaces or dash): "); try { Name = Console.ReadLine(); success = true; } catch (ArgumentException e) { Console.WriteLine(e.Message); } } } Answer: You can simplify it by using a private method to validate the input, if true, would set the Name property to the input and return true, otherwise false. Next, declare a private readonly char[] to include the allowed chars. Then use while loop instead of for. This is how it would be : private static readonly char[] _allowedChars = new char[] { ' ', '-' }; public string Name { get; set; } internal void ReadConsole() { Console.Write("Enter Name (only letter, spaces or dash): "); while (!TryParseName(Console.ReadLine())) { Console.Write("Wrong input, please re-enter Name (only letter, spaces or dash): "); } } private bool TryParseName(string input) { try { if(input?.All(c => char.IsLetter(c) || _allowedChars.Contains(c)) == true) { Name = input; return true; } } catch (ArgumentException e) { Console.WriteLine(e.Message); } return false; }
{ "domain": "codereview.stackexchange", "id": 43126, "lm_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#, error-handling", "url": null }
python, pandas Title: Optimise a function with numerous conditions that depends on the previous row in a Python dataframe Question: I have the following dataframe: country_ID ID direction date ESP_1 0 IN 2021-02-28 ENG 0 IN 2021-03-03 ENG 0 OUT 2021-03-04 ESP_2 0 IN 2021-03-05 FRA 1 OUT 2021-03-07 ENG 1 OUT 2021-03-09 ENG 1 OUT 2021-03-10 ENG 2 IN 2021-03-13 I have implemented the following functionality: ef create_columns_analysis(df): df['visit_ESP'] = 0 df['visit_ENG'] = 0 df['visit_FRA'] = 0 list_ids = [] for i in range(len(df)): if df.loc[i,'country_ID'] == 'ENG': country_ID_ENG(df, i, list_ids) else: # case country_ID = {FRA, ESP_1, ESP_2} # other methods not specified return df
{ "domain": "codereview.stackexchange", "id": 43127, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, pandas", "url": null }
python, pandas For each row with a specific country_ID, a similarly structured function is applied. I would like to optimise or simplify the code of the country_ID_ENG function. The country_ID_ENG function is defined as follows: def country_ID_ENG(df, i, list_ids): # If it is the first time the ID is detected if df.loc[i,'ID'] not in list_ids: # It adds up to one visit regardless of the direction of the ID df.loc[i,'visit_ENG'] = 1 # Add the ID to the read list list_ids.append(df.loc[i, 'ID']) # Assigns the error column a start message df.loc[i,'error'] = 'ERROR:1' # If it is not the first time it detects that ID else: # Saves the information of the previous row prev_row = df.loc[i-1] # If the current row direction is 'IN' if df.loc[i,'direction'] == 'IN': # Add a visit df.loc[i,'visit_ENG'] = 1 # Behaviour dependent on the previous row # If the current row direction is 'IN' and previous row is 'IN' if prev_row['direction'] == 'IN': if prev_row['country_ID'] == 'FRA': df.loc[i,'error'] = 'ERROR:0' elif prev_row['country_ID'] in ['ESP_1','ESP_2']: df.loc[i,'error'] = 'ERROR:2' df.loc[i,'visit_FRA'] = 1 else: df.loc[i,'error'] = 'ERROR:3' # If the current row direction is 'IN' and previous row is 'OUT' else: if prev_row['country_ID'] == 'ENG': df.loc[i,'error'] = 'ERROR:0' elif prev_row['country_ID'] in ['FRA','ESP_2']: df.loc[i,'error'] = 'ERROR:4' df.loc[i,'visit_FRA'] = 1 else: df.loc[i,'error'] = 'ERROR:5' df.loc[i,'visit_ESP'] = 1 df.loc[i,'visit_FRA'] = 1
{ "domain": "codereview.stackexchange", "id": 43127, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, pandas", "url": null }
python, pandas df.loc[i,'visit_ESP'] = 1 df.loc[i,'visit_FRA'] = 1 # If the current row direction is 'OUT' else: # If the current row direction is 'OUT' and previous row is 'IN' if prev_row['direction'] == 'IN': # If it detects an output before an input of the same 'country_ID', # it calculates the visit time if prev_row['country_ID'] == 'ENG': df.loc[i,'mean_time'] = df.loc[i,'date']-prev_row['date'] df.loc[i,'error'] = 'ERROR:0' elif prev_row['country_ID'] in ['ESP_1','ESP_2']: df.loc[i,'error'] = 'ERROR:6' df.loc[i,'visit_FRA'] = 1 df.loc[i,'visit_ENG'] = 1 else: df.loc[i,'error'] = 'ERROR:7' df.loc[i,'visit_ENG'] = 1 # If the current row direction is 'OUT' and previous row is 'OUT' else: df.loc[i,'visit_ENG'] = 1 if prev_row['country_ID'] == 'ENG': df.loc[i,'error'] = 'ERROR:8' elif prev_row['country_ID'] in ['FRA','ESP_2']: df.loc[i,'error'] = 'ERROR:9' df.loc[i,'visit_FRA'] = 1 else: df.loc[i,'error'] = 'ERROR:10' df.loc[i,'visit_ESP'] = 1 df.loc[i,'visit_FRA'] = 1
{ "domain": "codereview.stackexchange", "id": 43127, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, pandas", "url": null }
python, pandas The above function uses the information from the current row and the previous row (if any) to create new columns for visit_ENG, visit_ESP, visit_FRA, mean_time and error. For the example dataframe the function, applying the function country_ID_ENG to rows whose country_ID is equal to ENG, should return the following result: country_ID ID direction date visit_ENG visit_FRA visit_ESP mean_time error ESP_1 0 IN 2021-02-28 0 0 0 NaN NaN ENG 0 IN 2021-03-03 0 1 0 NaN ERROR:2 ENG 0 OUT 2021-03-04 0 0 0 1 days ERROR:0 ESP_2 0 IN 2021-03-05 0 0 0 NaN NaN FRA 1 OUT 2021-03-07 0 0 0 NaN NaN ENG 1 OUT 2021-03-09 1 1 0 NaN ERROR:9 ENG 1 OUT 2021-03-10 1 0 0 NaN ERROR:8 ENG 2 IN 2021-03-13 1 0 0 NaN ERROR:1 The function is very long, and the other functions for rows with country_ID equal to ESP or FRA will have the same complexity. I would like you to help me to simplify or optimise the code of this function to also take it into account when defining the country_ID_ESP and country_ID_FRA functions. I appreciate your help. Answer: per pandas iteration guidance You should never modify something you are iterating over. This is not guaranteed to work in all cases. Depending on the data types, the iterator returns a copy and not a view, and writing to it will have no effect! suggested from typing import Iterable, Tuple import pandas as pd COLS = ['country_ID', 'ID', 'direction', 'date'] DATA = [['ESP_1', 0, 'IN', '2021-02-28'], ['ENG', 0, 'IN', '2021-03-03'], ['ENG', 0, 'OUT', '2021-03-04'], ['ESP_2', 0, 'IN', '2021-03-05'], ['FRA', 1, 'OUT', '2021-03-07'], ['ENG', 1, 'OUT', '2021-03-09'], ['ENG', 1, 'OUT', '2021-03-10'], ['ENG', 2, 'IN', '2021-03-13']]
{ "domain": "codereview.stackexchange", "id": 43127, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, pandas", "url": null }
python, pandas def both_in(country_id: str): """where both condtions were `IN`""" esp, eng, fra = (0, 0, 0) if country_id == 'FRA': error_code = 0 elif country_id in ('ESP_1', 'ESP_2'): error_code = 2 fra = 1 else: error_code = 3 return (esp, eng, fra, f'ERROR:{error_code}') def both_out(country_id: str): """where both contionds were `OUT`""" esp, eng, fra = (0, 1, 0) if country_id == 'ENG': error_code = 8 elif country_id in ('FRA', 'ESP_2'): error_code = 9 fra = 1 else: error_code = 10 esp, fra = 1, 1 return (esp, eng, fra, f'ERROR:{error_code}') def in_out(country_id: str): """where current was IN and previous was OUT""" esp, eng, fra = (0, 0, 0) if country_id == 'ENG': error_code = 0 elif country_id in ('FRA', 'ESP_2'): error_code = 4 fra = 1 else: error_code = 5 esp = 1 fra = 1 return (esp, eng, fra, f'ERROR:{error_code}') def out_in(country_id: str): """where current was `OUT` and previous was `IN`""" esp, eng, fra = (0, 0, 0) if country_id == 'ENG': error_code = 0 elif country_id in ('ESP_1', 'ESP_2'): error_code = 6 eng, fra = 1, 1 else: error_code = 7 eng = 1 return (esp, eng, fra, f'ERROR:{error_code}') def create_columns_analysis(df: pd.DataFrame)->Iterable[Tuple[int,int,int,str,pd.Timestamp]]: """create_columns_analysis"""
{ "domain": "codereview.stackexchange", "id": 43127, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, pandas", "url": null }
python, pandas # in your logic there are 4 potential driving conditions based on the direction # of the current row and the previous row. so we'll make a dictionary that we can # index and call the associated functions. direction = { ('IN', 'IN'): both_in, ('OUT', 'OUT'): both_out, ('IN', 'OUT'): in_out, ('OUT', 'IN'): out_in, } # to align the direction slice # - the last row # - the first row # - and zip them together def iter_countires(): """yields a (ESP,ENG,FRA,ERROR,MEAN_TIME)""" list_ids = [] # because we sliced the first row from the loop yield that value first def first_row(country_id): if country_id == 'ENG': return (0, 1, 0, 'ERROR:1', pd.NA) return (0, 0, 0, 'ERROR:1', pd.NA) yield first_row(df['country_ID'][0]) for previous, current in zip(df[:-1].itertuples(), df[1:].itertuples()): time_delta = current.date-previous.date # If it is the first time the ID is detected if current.country_ID == 'ENG' and current.ID not in list_ids: list_ids.append(current.ID) yield (0, 1, 0, 'ERROR:1', time_delta) elif current.country_ID == 'ENG': # indexing our dict with the ('IN','OUT') to get the function conditional_func = ( direction[(previous.direction, current.direction)]) # call the function and pass the previous.country_ID as thats the only var it relies on # unpack thoes values and tack on the timedelta yield (*conditional_func(previous.country_ID), time_delta) else: # you could create a different conditional func dict if you wanted to # handle country_ID logic differently yield (0, 0, 0, pd.NA, pd.NA) return iter_countires()
{ "domain": "codereview.stackexchange", "id": 43127, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, pandas", "url": null }
python, pandas return iter_countires() def start(): """start""" df = pd.DataFrame(DATA, columns=COLS) df['date'] = pd.to_datetime(df['date']) df[['visit_ESP', 'visit_ENG', 'visit_FRA', 'error', 'mean_time']]=( tuple(create_columns_analysis(df))) print(df) if __name__ == '__main__': start() result country_ID ID direction date visit_ESP visit_ENG visit_FRA error mean_time 0 ESP_1 0 IN 2021-02-28 0 0 0 ERROR:1 <NA> 1 ENG 0 IN 2021-03-03 0 1 0 ERROR:1 3 days 00:00:00 2 ENG 0 OUT 2021-03-04 0 0 0 ERROR:0 1 days 00:00:00 3 ESP_2 0 IN 2021-03-05 0 0 0 <NA> <NA> 4 FRA 1 OUT 2021-03-07 0 0 0 <NA> <NA> 5 ENG 1 OUT 2021-03-09 0 1 0 ERROR:1 2 days 00:00:00 6 ENG 1 OUT 2021-03-10 0 1 0 ERROR:8 1 days 00:00:00 7 ENG 2 IN 2021-03-13 0 1 0 ERROR:1 3 days 00:00:00
{ "domain": "codereview.stackexchange", "id": 43127, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, pandas", "url": null }
kotlin, fibonacci-sequence Title: Iterative Fibonacci number generator in Kotlin Question: I have very limited experience in Java and slightly more in C# (just doing Advent of Code problems last month), so I'm not familiar with how to write idiomatic Kotlin. This class implements an infinite generator for the Fibonacci sequence. import java.math.BigInteger class FibonacciGenerator { private var fibs = arrayListOf<BigInteger>(BigInteger.ZERO, BigInteger.ONE) fun get(idx: Int): BigInteger { while (fibs.size <= idx) { val nextNum: BigInteger = fibs[fibs.size - 1] + fibs[fibs.size - 2] fibs.add(nextNum) } return fibs[idx] } } Answer: A few points: It is common practice to create mutable list without specifying implementation details using mutableListOf. Also I'd expect LinkedList to perform better than ArrayList, but that is very JVM-specific - there is no linkedListOf, but you can create it using Java API and use it. ArrayList would have to constantly reallocate more memory as the list grows bigger and you are not really using advantages of it (fast access), since you are always accessing only last 2 items in the array. Get method name is pretty generic. It doesn't say if you always cache it, calculate, etc. Not sure what would be better - maybe calculateUntil, with parameter index or generateUntil, since you are using Generator suffix. In some cases you don't need to specify type, it is already assumed from the code: arrayListOf(BigInteger.ZERO, BigInteger.ONE) ... val nextNum = fibs[fibs.size - 1] + fibs[fibs.size - 2] Use .last() method for accessing last element in the list. Consider creating extension function for accessing second last to improve readability and for consistency reasons (that may be an overkill :) ): return fibs.last() If using last is not appropriate, you can use lastIndex property rather than fibs.size - 1. I'd rename fibs to something more obvious like calculatedList (or generated.
{ "domain": "codereview.stackexchange", "id": 43128, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "kotlin, fibonacci-sequence", "url": null }
kotlin, fibonacci-sequence I'd rename fibs to something more obvious like calculatedList (or generated. I assume you never wanna reassign fibs, in that case var is not necessary and you can use val. Think is is good idea to extract the functionality, that adds new item to the sequence into a separate method. Overall, I imagine final code to something close to this (not sure about naming): import java.math.BigInteger fun <T> List<T>.secondLast(): T { if (size < 2) throw NoSuchElementException("List is not big enough to return second last") return this[lastIndex - 1] } class FibonacciGenerator { private val generatedList = mutableListOf(BigInteger.ZERO, BigInteger.ONE) private fun addAnotherItem() { generatedList.add(generatedList.last() + generatedList.secondLast()) } fun generateUntilIndex(index: Int): BigInteger { while (generatedList.size <= index) { addAnotherItem() } return generatedList[index] } }
{ "domain": "codereview.stackexchange", "id": 43128, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "kotlin, fibonacci-sequence", "url": null }
c++, multithreading, thread-safety Title: C++ thread pool and thread safe queue Question: This is my first time writing a custom thread pool in C++. I would love some feedback on how my code looks and if I am missing best practices or have glaring/subtle issues. Thanks! ThreadPool.hpp: #pragma once #include <atomic> #include <vector> #include <iostream> #include <thread> #include <future> #include <mutex> #include <queue> #include <functional> #include <ThreadSafeQueue.hpp> class ThreadPool{ public: ThreadPool(std::atomic_bool& result); void waitForCompletion(); void addJob(std::function<bool()> newJob); void setComplete(); private: void workLoop(std::atomic_bool& result); int m_numThreads; std::vector<std::thread> m_threads; std::atomic_bool m_workComplete; std::mutex m_mutex; std::condition_variable m_jobWaitCondition; ThreadSafeQueue<std::function<bool()>> m_JobQueue; }; ThreadPool.cpp: #include <ThreadPool.hpp> ThreadPool::ThreadPool(std::atomic_bool& result){ m_numThreads = std::thread::hardware_concurrency(); m_workComplete = false; for (int i = 0; i < m_numThreads; i++) { m_threads.push_back(std::thread(&ThreadPool::workLoop, this, std::ref(result))); } } // each thread executes this loop void ThreadPool::workLoop(std::atomic_bool& result){ while(!m_workComplete){ std::function<bool()> currentJob; bool popped; { std::unique_lock<std::mutex> lock(m_mutex); m_jobWaitCondition.wait(lock, [this](){ return !m_JobQueue.empty() || m_workComplete.load(); }); popped = m_JobQueue.pop(currentJob); } if(popped){ result = currentJob() && result; } } } void ThreadPool::addJob(std::function<bool()> newJob){ m_JobQueue.push(newJob); m_jobWaitCondition.notify_one(); }
{ "domain": "codereview.stackexchange", "id": 43129, "lm_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++, multithreading, thread-safety", "url": null }
c++, multithreading, thread-safety void ThreadPool::setComplete(){ m_workComplete = true; } void ThreadPool::waitForCompletion(){ { std::unique_lock<std::mutex> lock(m_mutex); m_workComplete.store(true); } m_jobWaitCondition.notify_all(); for(auto& thread : m_threads){ thread.join(); } m_threads.clear(); } ThreadSafeQueue.hpp: #pragma once #include <mutex> #include <queue> template <class T> class ThreadSafeQueue { public: ThreadSafeQueue(){}; void push(T element) { std::unique_lock<std::mutex> lock(m_mutex); m_queue.push(element); } bool pop(T& retElement) { std::unique_lock<std::mutex> lock(m_mutex); if (m_queue.empty()) { return false; } retElement = m_queue.front(); m_queue.pop(); return true; } bool empty(){ std::unique_lock<std::mutex> lock(m_mutex); return m_queue.empty(); } private: std::queue<T> m_queue; std::mutex m_mutex; }; ``` Answer: #include <filename> vs #include "filename" #include <ThreadPool.hpp> is typically how you would include third-party headers. You would do #include "ThreadPool.hpp" for your own headers. hardware_concurrency error-checking hardware_concurrency could return zero. Better handle that error. You might create a constant number of threads if that happens, or you might want to throw an exception: m_numThreads = std::max(std::thread::hardware_concurrency(), 2u); Consider emplace_back over push_back: m_threads.push_back(std::thread(&ThreadPool::workLoop, this, std::ref(result))); // replace with m_threads.emplace_back(&ThreadPool::workLoop, this, std::ref(result)); addJob takes an unnecessary copy: m_JobQueue.push(newJob); // replace with m_JobQueue.push(std::move(newJob)); Destructor It's better to check and call waitForCompletion in your destructor. Empty constructor ThreadSafeQueue(){}; // replace with ThreadSafeQueue() = default;
{ "domain": "codereview.stackexchange", "id": 43129, "lm_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++, multithreading, thread-safety", "url": null }
c++, multithreading, thread-safety // replace with ThreadSafeQueue() = default; Questionable API bool pop(T &retElement) is a really bad way of going about doing that. You force the object to have a default constructor and a copy constructor, basically. A much better way would be: std::optional<T> pop();. You would also move the element, instead of copying it. void push(T element) is not a bad idea, but you should move element into the queue, instead of copying it. Finally Not exactly the same, but do check-out my similar post from some time ago: Asynchronous dispatch queue
{ "domain": "codereview.stackexchange", "id": 43129, "lm_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++, multithreading, thread-safety", "url": null }
python, python-3.x, numpy, pandas Title: dataframe mean outliers to NaN to derive a higher quality mean for area,speed,azimuth
{ "domain": "codereview.stackexchange", "id": 43130, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x, numpy, pandas", "url": null }
python, python-3.x, numpy, pandas Question: I have some data that represents the area, speed(meters per second), and azimuth(rads) of a polygon. The objective is to determine the mean for each set of parameters. With that mean value, apply a threshold to remove data points that fell outside of the mean deviation threshold. Then recalculate the means for the parameters set. I am using match statements so you will need python 3.10 data DATA = [ [0.045750000000000984, 0.04939999999999974, 0.05244999999999857, 0.054399999999998436, 0.056099999999999456, 0.05375000000000011, 0.047700000000000985, 0.053700000000000594, 0.053249999999999686, 16.81209831859011, 27.983008063348617, 20.301826794339316, 13.421484359287598, 17.10557180223468, 14.686987606192902, 41.18082589372154, 13.065486605460656, 4.608155337880411, 0.7571951341718915, 0.3457777398771206, 0.46056961460740087, 0.2819901554949584, 0.7205708724903156, -0.00040991561554303056, 0.3860776453927442, 0.09629955035400072, 0.2468722764784534], [0.03290000000000123, 0.033550000000000045, 0.03949999999999949, 0.035550000000001615, 0.03725000000000067, 0.03515000000000022, 0.03714999999999999, 0.041350000000001316, 0.03869999999999882, 14.902912040542054, 15.452401255651447, 12.5484544315597, 10.83783196920491, 13.246734412134916, 12.636336066844674, 19.61093585673077, 8.898327945757917, 26.237157593452878, 0.36589566404637536, 0.5140598344685876, 0.06092353057665044, 0.5433592643289422, 0.3300217799943245, 0.1295695630661193, 0.5813772760582753, 0.97888742111902, 0.2144469684077374], [0.15945000000000153, 0.1419000000000014, 0.1346, 0.14314999999999908, 0.14485000000000084, 0.1293000000000014, 0.14264999999999992, 0.1434499999999994, 0.08944999999999861, 39.54982055905117, 67.05598966736439, 14.170464300161013, 25.57103344352307, 22.224605807376317,
{ "domain": "codereview.stackexchange", "id": 43130, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x, numpy, pandas", "url": null }
python, python-3.x, numpy, pandas 28.901343579758898, 19.05130673155152, 25.61289901736464, 122.31441473369556, 0.5250514668415044, 0.3119136953061388, 0.3818093125132205, 0.2669557624118119, -0.4876722558321518, 0.03814067199937899, -0.07502082862542193, 0.15371372713178985, -1.1026290280269917], [0.00340000000000014, 0.0066000000000002515, 0.008499999999999603, 0.007999999999999518, 0.0065500000000002015, 0.008100000000000543, 0.0032500000000004834, 0.018350000000000196, 0.020150000000000542, 22.364276562983136, 20.506557739907425, 6.243036570120132, 19.3458717607394, 10.456833536986126, 19.65879720239808, 14.307243539019602, 9.091403905263792, 18.47420699835527, 0.8485690702159555, 0.40094252533477115, 0.1157765828210181, 0.6944022345849206, 0.46766736064272035, 1.153657712332056, 0.7600461290670872, 0.4170470750740715, 0.49920935232659946], [None, None, 0.003549999999999955, 0.005799999999999788, 0.005799999999999788, 0.006900000000000275, 0.007049999999999682, 0.006800000000000173, 0.005200000000000045, None, None, 8.06110268044255, 13.695219329907925, 0.0, 12.81872890572318, 6.190861120089245, 3.9861242549543703, 4.403761437912741, None, None, -0.8342338501323102, -0.35990880371032785, 0.0, -2.9708131816772876, -0.12378167714772335, -1.4646911328887278, -2.475146432921943] ]
{ "domain": "codereview.stackexchange", "id": 43130, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x, numpy, pandas", "url": null }
python, python-3.x, numpy, pandas main.py import functools from typing import Iterable, Dict import pandas as pd import numpy as np DATA = ... INDEX = ['89234', '89467', '89519', '89680', '90104'] #COLUMN = np.repeat(['area', 'MPS', 'azimuth'], 9) # added MULTI_COLUMN per request DATE_RANGE = pd.to_datetime(range(9), unit='m', origin=pd.Timestamp('1960-01-01')) MULTI_COLUMN = pd.MultiIndex.from_tuples(( (date, param) for param in ('area', 'MPS', 'azimuth') for date in DATE_RANGE), names=['validTime', 'parameters']) def normalize( frame_cache: pd.DataFrame, thresh) -> pd.DataFrame: """normalize values in the dataframe""" frame_cache[['area', 'MPS', 'azimuth']] = np.block( list(outliers2nan(frame_cache, thresh=thresh))) return frame_cache def outliers2nan( frame_cache: pd.DataFrame, thresh: Dict[str, float]) -> Iterable[np.ndarray]: """ where a parameter is greater than the minimum mean threshold set the value to NaN """ for param, frame in frame_cache.groupby('parameters', axis=1, sort=False): mean = mean_stack(frame, kind=param) match param: case 'azimuth': deg_diff = ( np.rad2deg(frame_cache['azimuth']) - np.rad2deg(mean)) yield frame.where(abs((deg_diff + 180) % 360 - 180) < thresh[param]) case _: yield frame.where(abs(frame-mean) < mean*thresh[param]) def mean_stack( frame: pd.DataFrame, axis=1, kind=None) -> np.ndarray: """DataFrame.mean(1) stacked as a np.ndarray""" match kind: case 'azimuth': return ( functools.reduce(_mean_azimuth_reduction, frame.to_numpy().T)[:, np.newaxis]) case _: return ( frame.mean(axis=axis).to_numpy()[:, np.newaxis]) def _mean_azimuth_reduction(col1: np.ndarray, col2: np.ndarray) -> np.ndarray: np.nan_to_num(x=col1, nan=col2, copy=False)
{ "domain": "codereview.stackexchange", "id": 43130, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x, numpy, pandas", "url": null }
python, python-3.x, numpy, pandas np.nan_to_num(x=col1, nan=col2, copy=False) mean_rads = ( np.arctan2(np.sin(col1)+np.sin(col2), np.cos(col1)+np.cos(col2))) return mean_rads def get_means(df: pd.DataFrame) -> pd.DataFrame: """start subroutine""" return pd.DataFrame({ param: mean_stack(frame, kind=param).squeeze() for param, frame in df.groupby('parameters', axis=1, sort=False) }, index=INDEX) def start(): """construct df and display means""" bad_df = pd.DataFrame( DATA, index=INDEX, columns=MULTI_COLUMN) bad_means = get_means(bad_df) good_df = normalize( bad_df.droplevel('validTime', axis=1).copy(), thresh={'area': .65, 'MPS': .65, 'azimuth': 60.0}) good_means = get_means(good_df) good_df.columns = MULTI_COLUMN print(f""" BAD {bad_df.stack()} GOOD {good_df.stack()} BAD {bad_means} GOOD {good_means} DIF {abs(bad_means-good_means)} """) if __name__ == '__main__': start()
{ "domain": "codereview.stackexchange", "id": 43130, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x, numpy, pandas", "url": null }
python, python-3.x, numpy, pandas result A good example of the use case is on the last MPS column of index 89519 which reported a speed of 122 meters per second. That value gets omitted from the final return value. BAD validTime 1960-01-01 00:00:00 1960-01-01 00:01:00 1960-01-01 00:02:00 1960-01-01 00:03:00 1960-01-01 00:04:00 1960-01-01 00:05:00 1960-01-01 00:06:00 1960-01-01 00:07:00 1960-01-01 00:08:00 parameters 89234 MPS 16.812098 27.983008 20.301827 13.421484 17.105572 14.686988 41.180826 13.065487 4.608155 area 0.045750 0.049400 0.052450 0.054400 0.056100 0.053750 0.047700 0.053700 0.053250 azimuth 0.757195 0.345778 0.460570 0.281990 0.720571 -0.000410 0.386078 0.096300 0.246872 89467 MPS 14.902912 15.452401 12.548454 10.837832 13.246734 12.636336 19.610936 8.898328 26.237158 area 0.032900 0.033550 0.039500 0.035550 0.037250 0.035150 0.037150 0.041350 0.038700 azimuth 0.365896 0.514060 0.060924 0.543359 0.330022 0.129570 0.581377 0.978887 0.214447
{ "domain": "codereview.stackexchange", "id": 43130, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x, numpy, pandas", "url": null }
python, python-3.x, numpy, pandas 89519 MPS 39.549821 67.055990 14.170464 25.571033 22.224606 28.901344 19.051307 25.612899 122.314415 area 0.159450 0.141900 0.134600 0.143150 0.144850 0.129300 0.142650 0.143450 0.089450 azimuth 0.525051 0.311914 0.381809 0.266956 -0.487672 0.038141 -0.075021 0.153714 -1.102629 89680 MPS 22.364277 20.506558 6.243037 19.345872 10.456834 19.658797 14.307244 9.091404 18.474207 area 0.003400 0.006600 0.008500 0.008000 0.006550 0.008100 0.003250 0.018350 0.020150 azimuth 0.848569 0.400943 0.115777 0.694402 0.467667 1.153658 0.760046 0.417047 0.499209 90104 MPS NaN NaN 8.061103 13.695219 0.000000 12.818729 6.190861 3.986124 4.403761 area NaN NaN 0.003550 0.005800 0.005800 0.006900 0.007050 0.006800 0.005200 azimuth NaN NaN -0.834234 -0.359909 0.000000 -2.970813 -0.123782 -1.464691 -2.475146
{ "domain": "codereview.stackexchange", "id": 43130, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x, numpy, pandas", "url": null }
python, python-3.x, numpy, pandas GOOD 1960-01-01 00:00:00 1960-01-01 00:01:00 1960-01-01 00:02:00 1960-01-01 00:03:00 1960-01-01 00:04:00 1960-01-01 00:05:00 1960-01-01 00:06:00 1960-01-01 00:07:00 1960-01-01 00:08:00 89234 MPS 16.812098 27.983008 20.301827 13.421484 17.105572 14.686988 NaN 13.065487 NaN area 0.045750 0.049400 0.052450 0.054400 0.056100 0.053750 0.047700 0.053700 0.053250 azimuth 0.757195 0.345778 0.460570 0.281990 0.720571 -0.000410 0.386078 0.096300 0.246872 89467 MPS 14.902912 15.452401 12.548454 10.837832 13.246734 12.636336 19.610936 8.898328 NaN area 0.032900 0.033550 0.039500 0.035550 0.037250 0.035150 0.037150 0.041350 0.038700 azimuth 0.365896 0.514060 0.060924 0.543359 0.330022 0.129570 0.581377 0.978887 0.214447 89519 MPS 39.549821 NaN NaN 25.571033 22.224606 28.901344 19.051307 25.612899 NaN area 0.159450 0.141900 0.134600 0.143150 0.144850 0.129300 0.142650 0.143450 0.089450
{ "domain": "codereview.stackexchange", "id": 43130, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x, numpy, pandas", "url": null }
python, python-3.x, numpy, pandas azimuth NaN 0.311914 0.381809 0.266956 -0.487672 0.038141 -0.075021 0.153714 -1.102629 89680 MPS 22.364277 20.506558 6.243037 19.345872 10.456834 19.658797 14.307244 9.091404 18.474207 area 0.003400 0.006600 0.008500 0.008000 0.006550 0.008100 0.003250 NaN NaN azimuth 0.848569 0.400943 0.115777 0.694402 0.467667 1.153658 0.760046 0.417047 0.499209 90104 MPS NaN NaN 8.061103 NaN NaN NaN 6.190861 3.986124 4.403761 area NaN NaN 0.003550 0.005800 0.005800 0.006900 0.007050 0.006800 0.005200 azimuth NaN NaN -0.834234 NaN NaN NaN NaN -1.464691 -2.475146
{ "domain": "codereview.stackexchange", "id": 43130, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x, numpy, pandas", "url": null }
python, python-3.x, numpy, pandas BAD area MPS azimuth 89234 0.051833 18.796161 0.230576 89467 0.036789 14.930121 0.455432 89519 0.136533 40.494653 -0.524696 89680 0.009211 15.605359 0.552226 90104 0.005871 7.022257 -1.823553 GOOD area MPS azimuth 89234 0.051833 17.625209 0.230576 89467 0.036789 13.516742 0.455432 89519 0.136533 26.818502 -0.525529 89680 0.006343 15.605359 0.552226 90104 0.005871 5.660462 -1.969919 DIF area MPS azimuth 89234 0.000000 1.170951 0.000000 89467 0.000000 1.413380 0.000000 89519 0.000000 13.676152 0.000833 89680 0.002868 0.000000 0.000000 90104 0.000000 1.361794 0.146366 Answer: I'm going to assume that you have real timestamps instead of the synthetic 1960 values. I think that all of the following should go away: np.block() normalize() for param, frame in yield and any kind of generation match and any kind of column-conditional branch mean_stack() squeeze() droplevel() I don't think that the current approach is as vectorised as it could be. Also, the data shape coming in is insane. The index is not a "parameter" but is in fact (by your description) a "polygon_id". The second index level should be validTime. That leaves three columns - area, MPS and azimuth - all dependent variables. Suggested Not strictly identical because it has a different output shape, but numerically equivalent: import functools import pandas as pd import numpy as np
{ "domain": "codereview.stackexchange", "id": 43130, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x, numpy, pandas", "url": null }