text
stringlengths
1
2.12k
source
dict
c++, callback And in invoke() you can write: for (auto& callback: callbacks) callback(args...); Unsafe callback comparison The way you try to make callbacks comparable is wrong. First of all, you try to create a hash of the callback, and compare hashes. However, there is no guarantee that two distinct callbacks will have two distinct hash values. Even if you think it is very unlikely to happen, don't rely on probability. The other issue is that it is not defined by the standard what the layout of class std::function is. You assume that it stores just a pointer to some function, and maybe that assumption works on your platform, but it is not portable. The best you can do in the constructor of callback is to take the address of func (the parameter, not this->func), and store that unhashed. However, there is a reason why you cannot equality-compare two std::function objects, and I think any attempt to make them properly comparable is doomed. Another option would be to not bother comparing functions, but to generate a unique ID for each callback, and return that ID to the caller. They can then pass it to the unhook() function, and look up the right entry in the vector callbacks using that ID.
{ "domain": "codereview.stackexchange", "id": 43396, "lm_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++, callback", "url": null }
python, python-3.x, programming-challenge, palindrome Title: The largest palindrome made from the product of two 3-digit numbers Question: Problem description: A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99. Find the largest palindrome made from the product of two 3-digit numbers. Palindrome: In math, a palindrome is a number that reads the same forward and backward. Example: 353, 787, and 2332 are examples of palindromes. By definition, all numbers that have the same digits such as 4, 11, 55, 222, and 6666 are examples of palindromes. Step-by-Step my code: 1- largest number of n-1 digit. For example, for n = 2, upper_limit is 99 2- One plus this number is lower limit which is product of two numbers. For example, for n = 2, lower_limit is 10. 3- calculating product of two n-digit numbers 4- calculating reverse of product to check whether it is palindrome or not 5- update new product if exist and if greater than previous one My Solution This is my solution for problem 4 of Project Euler using Python: def largest_palindrome_product(n): '''Find Largest Palindrome Product ''' upper_limit = (10**(n))-1 lower_limit = 1 + upper_limit//10 max_product = 0 for i in range(upper_limit,lower_limit-1, -1): for j in range(i,lower_limit-1,-1): product = i * j if (product < max_product): break number = product reverse = 0 while (number != 0): reverse = reverse * 10 + number % 10 number =number // 10 if (product == reverse and product > max_product): max_product = product return max_product
{ "domain": "codereview.stackexchange", "id": 43397, "lm_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, palindrome", "url": null }
python, python-3.x, programming-challenge, palindrome return max_product Answer: Outsource secondary calculations to helper functions. Your current code is reasonable. Its primary drawback is that the Euler-solving code is cluttered up with the details of checking for palindrome status. And that check can be done more easily in the realm of strings than integers: just check whether the number's string representation equals the reversed string. def is_palindrome(n): s = str(n) return s == s[::-1] An alternative to compute the bounds: some more string-based thinking. As illustrated by one comment, your approach to computing upper/lower bounds is not immediately intuitive. A different approach is to think in terms of range start and stop parameters. For example, for n = 3 we want the range to start on 999 and stop on 99. You can create those values quite easily – again, with string-based logic rather than math. def largest_palindrome_product(n): start = int('9' * n) stop = int('9' * (n - 1)) max_product = 0 for i in range(start, stop, -1): for j in range(i, stop, -1): p = i * j if p <= max_product: break elif is_palindrome(p): max_product = p return max_product
{ "domain": "codereview.stackexchange", "id": 43397, "lm_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, palindrome", "url": null }
python, python-3.x, programming-challenge, palindrome When asking for help, express expectations in the form of automated tests. The code you are posting on CodeReview is getting better – well done. However, you are still ignoring a key piece of advice given for Project Euler #1: write automated tests. Among their other benefits, such tests help your helpers, telling them precisely how to call your code (again, see the comment where there was some ambiguity on this matter), allowing them to edit your code in confidence knowing that they haven't broken anything, and providing a convenient vehicle for them to add other tests as they experiment. def main(): TESTS = ( (2, 9009), (3, 906609), (4, 99000099), (5, 9966006699), (6, 999000000999), # You'll need a more clever algorithm to go higher. ) for n, exp in TESTS: got = largest_palindrome_product(n) if got == exp: print('ok') else: print('GOT', got, 'EXP', exp) if __name__ == '__main__': main()
{ "domain": "codereview.stackexchange", "id": 43397, "lm_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, palindrome", "url": null }
python, python-3.x, algorithm, programming-challenge, factors Title: The smallest positive number that is evenly divisible by all of the numbers from 1 to 20 Question: Problem description: 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder. What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20? Least Common Multiple(LCM): In arithmetic and number theory, the least common multiple, lowest common multiple, or smallest common multiple of two integers a and b, usually denoted by lcm, is the smallest positive integer that is divisible by both a and b. Example: LCM(6,7,21) Multiples of 6: 6, 12, 18, 24, 30, 36, 42, 48, 54, 60 Multiples of 7: 7, 14, 21, 28, 35, 42, 56, 63 Multiples of 21: 21, 42, 63 Find the smallest number that is on all of the lists. We have it in bold above. So LCM(6, 7, 21) is 42 The best solution with Euclid GCD algorithm Euclid’s GCD algorithm: 1- The smallest positive number that is evenly divided (divided without remainder) by a > set of numbers is called the Least Common Multiple (LCM). 2- All we have to do to solve this problem is find the LCM for the integers {1, 2, 3, 4, > …, 20} using Euclid’s GCD algorithm. 3- After some reflection you might correctly realize that every integer is divisible by > > 1, so 1 can be removed from the list and use 2 through 20 instead. 4- we can eliminate other factors as well. 5- We leave 20 in the calculation but then remove its factors {2, 4, 5, 10}. Any number > > evenly divisible by 20 is also evenly divisible by these factors. 6- 19 is prime and has no factors— it stays. 7- 18 has factors {2, 3, 6, 9} and we already removed 2 but we can remove 3, 6, and 9. 17 > is prime — it stays. 8- We continue this numeric carnage until our original list of {1…20} becomes the much > > smaller {11…20}. 9- In general, all smaller factors of a bigger number in the list can be safely removed > > without changing the LCM.
{ "domain": "codereview.stackexchange", "id": 43398, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x, algorithm, programming-challenge, factors", "url": null }
python, python-3.x, algorithm, programming-challenge, factors My Solution This is my solution for problem 5 of Project Euler using Python: def LCM(a, b): '''Return the least common multiple of the specified integer arguments ''' return a // gcd(a, b) * b N = int(input("The LCM for numbers 1 through ")) N_reduce = reduce(LCM, range(N//2+1, N+1)) print ("The LCM for numbers 1 through" ,N, "is:", N_reduce) Answer: Straight. If you - defined "the range-LCM" in a function with a docsting - presented imports  and test cases or usage examples, - added boundary checks (try N = 0), I'd call it great. You might get a reviewer's extra eye-roll throwing in def largest_power_of_two_not_exceeding(n): """ Return the largest power of 2 not exceeding n taken as an integer. """ n = int(n) if n <= 0: raise ValueError while 0 != n & n-1: n &= n-1 return n def LCMup2(n): """ return the LCM for numbers 1 through n. """ n = int(n) if n <= 1: return 1 return reduce(LCM, range((n//6)*2+1, n+1, 2) ) * largest_power_of_two_not_exceeding(n)
{ "domain": "codereview.stackexchange", "id": 43398, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x, algorithm, programming-challenge, factors", "url": null }
python, matplotlib, pdf Title: A Python script to plot data and save to PDF Question: I have a very simple Python script. All it does is open two data files from a given directory, read the data, make a series of plots and save as PDF. It works, but it is very slow. It takes almost 20 seconds for data files that have 50-100 lines and <30 variables. import numpy as np import matplotlib.pyplot as plt from matplotlib.backends.backend_pdf import PdfPages with open('file1.out') as f: var1 = f.readline().split() with open('file2.out') as f: var2 = f.readline().split() df1 = np.loadtxt('file1.out', skiprows=1, unpack=True) df2 = np.loadtxt('file2.out', skiprows=1, unpack=True) nc1 = df1.shape[0] nc2 = df2.shape[0] with PdfPages('file_output.pdf') as pdf: ## file1.out fig = plt.figure(figsize=(11,7)) j = 1 for i in range(1,nc1): ax = fig.add_subplot(3,2,j) ax.plot(df1[0], df1[i], linestyle='-', color='black') ax.set(title=var1[i], xlabel='seconds', ylabel='') if j == 6: pdf.savefig(fig) fig = plt.figure(figsize=(11,7)) j = 1 else: j = j + 1 pdf.savefig(fig) ## file2.out fig = plt.figure(figsize=(11,7)) j = 1 for i in range(1,nc2): ... # and it continues like the block of code above My questions are: Do I need all those imports and are they slowing down the execution? Is there a better way to read the data files then opening them twice (once to get the file header and once to get data)? Am I using the matplotlib commands correctly/efficiently (I am not very familiar with matplotlib, and this is basically my first attempt to use it)?
{ "domain": "codereview.stackexchange", "id": 43399, "lm_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, matplotlib, pdf", "url": null }
python, matplotlib, pdf Please keep in mind that ideally this script should have as few dependencies as possible, because it is meant to be used on different systems by different users. The data files have the following format: t X1 X2 X3 X4 X5 X6 X7 X8 X11 X12 X13 X14 X15 X16 6.000000E+001 4.309764E-007 2.059219E-004 9.055840E-007 2.257223E-003 1.148868E-002 7.605114E-002 4.517820E-004 3.228596E-008 2.678874E-006 7.095441E-006 1.581115E-007 1.010346E-006 1.617892E-006 9.706194E-007 1.200000E+002 4.309764E-007 2.059219E-004 9.055840E-007 2.257223E-003 1.148868E-002 7.605114E-002 4.517820E-004 3.228596E-008 2.678874E-006 7.095441E-006 1.581115E-007 1.010346E-006 1.617892E-006 9.706194E-007 1.800000E+002 3.936234E-007 2.027775E-004 8.644279E-007 2.180931E-003 1.131226E-002 7.476778E-002 4.353550E-004 3.037527E-008 2.534515E-006 6.778434E-006 1.470889E-007 9.488175E-007 1.531702E-006 9.189112E-007 Answer: coding style Your code is almost pep-8 compliant. There are a few spaces missing after comma's, but all in all this is not too bad. I myself use black to take care of this formatting for me. some of the variables names can be clearer. What does nc1 mean for example magic numbers The number 3, 2 and 6 are the number of rows and columns on the grid. Better would be to make them real variables, and replace 6 with rows * columns. If you ever decide you want 4 columns, you don't have to chase down all those magic numbers looping You are looping over the indexes of var and df. Better here would be to use zip to iterate over both tables together. If you want to group them per 6, you can use the grouper itertools recipe. and enumerate to get the index of the different subplots. rows, columns = 3, 2
{ "domain": "codereview.stackexchange", "id": 43399, "lm_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, matplotlib, pdf", "url": null }
python, matplotlib, pdf for group in grouper(zip(var1[1:], df1[1:]), rows * columns): fig = plt.figure(figsize=(11, 7)) for i, (label, row) in enumerate(filter(None, group)): ax = fig.add_subplot(rows, columns, i + 1) ax.plot(df1[0], row, linestyle="-", color="black") ax.set(title=label, xlabel="seconds", ylabel="") The filter(None,...) is to eliminate the items that get the fillvalue in the grouper Is a lot clearer than the juggling with nc1 and j functions This would be a lot easier to test an handle if you would separate the different parts of the script into functions reading the file making 1 page plot appending the different pages This will also allow each of those parts to be tested separately reading the file Instead of loading the file twice and using numpy, using pandas, which supports data with names and indices will simplify this part a lot df = pd.read_csv(<filename>, sep="\s+", index_col=0) this is a labelled DataFrame, so no more need to use var1 for the column names making the individual plot: group the columns per 6 def column_grouper(df, n): for i in range(0, df.shape[1], n): yield df.iloc[:, i:i+n] this simple helper generator can group the data per 6 columns make the plot def generate_plots(df, rows=3, columns=2): for group in column_grouper(df, rows * columns): fig = plt.figure(figsize=(11, 7)) for i, (label, column) in enumerate(group.items()): ax = fig.add_subplot(rows, columns,i + 1) ax.plot(column, linestyle='-', color='black') ax.set(title=label, xlabel='seconds', ylabel='') yield fig saving the pdf Here a simple method that accepts an iterable of figures and a filename will do the trick def save_plots(figures, output_file): with PdfPages(output_file) as pdf: for fig in figures: pdf.savefig(fig)
{ "domain": "codereview.stackexchange", "id": 43399, "lm_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, matplotlib, pdf", "url": null }
python, matplotlib, pdf pulling it together def parse_file(input_file, output_file, rows=3, columns=2): df = pd.read_csv(input_file, sep="\s+", index_col=0) figures = generate_plots(df, rows, columns) save_plots(figures, output_file) and then calling this behind a main guard if __name__ == "__main__": input_files = ['file1.out', 'file2.out'] output_file = 'file_output.pdf' for input_file in input_files: parse_file(input_file, output_file) If this still is too slow, at least now the different parts of the program are split, and you can start looking what part of the program is slowing everything down
{ "domain": "codereview.stackexchange", "id": 43399, "lm_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, matplotlib, pdf", "url": null }
rust Title: Rust vector iteration and integer conversions Question: Started learning Rust by solving LeetCode problems as they involve all the standard data structures of the language. I have the following standard hash table solution to the two-sum problem: use std::collections::HashMap; impl Solution { pub fn two_sum(nums: Vec<i32>, target: i32) -> Vec<i32> { let mut positions = HashMap::<i32,usize>::new(); for (pos, n) in nums.iter().enumerate() { positions.insert(*n, pos); } for (pos, n) in nums.iter().enumerate() { if let Some(p) = positions.get(&(target - *n)) { if *p != pos { return vec![pos as i32, *p as i32]; } } } return vec![]; } } In other words, the code returns two distinct indices into the vector such that the corresponding entries sum up to target. The signature of the function is given by the platform. Since we are returning indices into the array, the return type should obviously be Vec<usize>, so this is a dumb choice. Having to live with that, I'm trying to figure out two things: Since integers are trivial to copy, is there a way to write the code without having to deal with references? HashMap::get() seems to want a reference as its parameter. Is there a way to avoid the ugly &(target - *n) when looking up positions in the hash table? Any other Rust tips for making the code cleaner or more idiomatic? Answer: welcome. You can use .into_iter() to consume the vector and return the numbers by value instead of by reference, this will only work in the last place you use the vector. You can also use .copied() on an iterator where the inner type implements Copy, this way you remove the referencing. When matching you can match to a pattern with build in dereferencing if let Some(&p) = ... here p is usize instead of &usize. Yes it does. You can also see this in action in the documentation.
{ "domain": "codereview.stackexchange", "id": 43400, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "rust", "url": null }
rust Yes it does. You can also see this in action in the documentation. The last line can be just Vec::new() (or vec![]) instead of return vec![];. The first loop can be rewritten as follows: positions.extend(nums.iter().enumerate().map(|(pos, n)| (*n, pos)));. You do not have to write out the HashMap type, but it can help in reasoning about the code. Here is the function again with the above mentioned changes. pub fn two_sum(nums: Vec<i32>, target: i32) -> Vec<i32> { let mut positions = HashMap::<i32, usize>::new(); positions.extend(nums.iter().copied().enumerate().map(|(pos, n)| (n, pos))); for (pos, n) in nums.iter().copied().enumerate() { if let Some(&p) = positions.get(&(target - n)) { if p != pos { return vec![pos as i32, p as i32]; } } } Vec::new() }
{ "domain": "codereview.stackexchange", "id": 43400, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "rust", "url": null }
javascript, node.js, image, network-file-transfer Title: Server code to upload and save images to cloud storage Question: Is there a way to beautify my code? It works but there repeated blocks and I am not sure that I'm using some functions in the right way. I'm not new to JavaScript but I want to improve it and get rid of Bad Coding Habits. Below is my code snippet that I'm using on the server to upload product images to cloud storage using multer and sharp. const EasyYandexS3 = require('easy-yandex-s3') const multer = require('multer') const sharp = require('sharp') const slug = require('slug') const s3 = new EasyYandexS3({ auth: { accessKeyId: process.env.KEY_ID, secretAccessKey: process.env.SECRET_KEY, }, Bucket: process.env.BACKET, // Название бакета debug: false, // Дебаг в консоли }) const storage = multer.memoryStorage() const fileFilter = (req, file, cb) => { if ( file.mimetype === 'image/jpeg' || file.mimetype === 'image/jpg' || file.mimetype === 'image/png' ) { cb(null, true) } else { cb(null, false) } } const upload = multer({ storage, fileFilter, limits: { fileSize: 1024 * 1024 * 5, // ограничение до 5 мб }, }) const uploadFields = upload.fields([ { name: 'cover', maxCount: 1 }, { name: 'media', maxCount: 4 }, ])
{ "domain": "codereview.stackexchange", "id": 43401, "lm_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, node.js, image, network-file-transfer", "url": null }
javascript, node.js, image, network-file-transfer const uploadImages = (req, res, next) => { uploadFields(req, res, (err) => { if (err instanceof multer.MulterError) { if (err.code === 'LIMIT_UNEXPECTED_FILE') { return res.send('Превышено количество файлов.') } } else if (err) { return res.send(err) } next() }) } const resizeImages = async (req, res, next) => { // Функция загрузки фотографий в бакет async function transform(size, file, filename, type) { const folder = slug(req.body.title) const resizedImgFilename = `${filename}-${size}` const resizedImgBuffer = await sharp(file.buffer) .resize(size) .toFormat('jpeg') .jpeg({ quality: 90 }) .toBuffer() const upload = await s3.Upload( { buffer: resizedImgBuffer, name: resizedImgFilename, }, `/products/${folder}/` ) if (size === 800) { type.push(upload.Location.slice(0, -4)) } }
{ "domain": "codereview.stackexchange", "id": 43401, "lm_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, node.js, image, network-file-transfer", "url": null }
javascript, node.js, image, network-file-transfer // Проверяем какие файл загружены if (req.files.media === undefined && req.files.cover === undefined) { return next() } else if (req.files.media === undefined) { await Promise.all( req.files.cover.map(async (file) => { const filename = Date.now() + Math.round(Math.random() * 1e2) + 'c' const type = req.body.cover await transform(800, file, filename, type) await transform(400, file, filename, type) await transform(250, file, filename, type) }) ) } else if (req.files.cover === undefined) { await Promise.all( req.files.media.map(async (file) => { const filename = Date.now() + Math.round(Math.random() * 1e2) + 'm' const type = req.body.media await transform(800, file, filename, type) await transform(400, file, filename, type) await transform(250, file, filename, type) }) ) } else { await Promise.all( req.files.media.map(async (file) => { const filename = Date.now() + Math.round(Math.random() * 1e2) + 'm' const type = req.body.media await transform(800, file, filename, type) await transform(400, file, filename, type) await transform(250, file, filename, type) }) ) await Promise.all( req.files.cover.map(async (file) => { const filename = Date.now() + Math.round(Math.random() * 1e2) + 'c' const type = req.body.cover await transform(800, file, filename, type) await transform(400, file, filename, type) await transform(250, file, filename, type) }) ) } next() } module.exports = { uploadImages, resizeImages, }
{ "domain": "codereview.stackexchange", "id": 43401, "lm_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, node.js, image, network-file-transfer", "url": null }
javascript, node.js, image, network-file-transfer module.exports = { uploadImages, resizeImages, } Answer: Within resizeImages, the if (req.files.media)... seems to be highly redundant. You seem to be unnecessarily checking for existence of media and cover instead of just processing them if they are defined. const async transformItems(items, fileType, type) { return Promise.all((items ?? []).map((file) => { const filename = Date.now() + Math.round(Math.random() * 1e2) + fileType await transform(800, file, filename, type) await transform(400, file, filename, type) await transform(250, file, filename, type) }) } await transformItems(req.files.media, 'm', req.body.media); await transformItems(req.files.cover, 'c', req.body.cover); next() There isn't really any need to guard whether media or cover exist or are populated, that can easily be handled within the helper and the promise will just return. The rest of it doesn't appear to show much if any repetition. As a matter of style, if prefer to use the classic form function ... declaration rather than assigning an arrow function to a const symbol, because it's clearer that it's a local function. Arrow function definition and calls can be somewhat easily misread I find. You also have a function scope symbol called upload that will mask the file (outer) scope symbol of the same name, which adds to confusion.
{ "domain": "codereview.stackexchange", "id": 43401, "lm_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, node.js, image, network-file-transfer", "url": null }
python, python-3.x, hangman Title: Python smart Hangman game Question: I made a smart Hangman game in Python and now want your opinion about the readability and code quality of this script. I want to improve my overall coding style. So I am happy to hear improvements for naming conventions, proper docstrings and logical/runtime enhancements. So lets start with a quick explanation how my program works. The user chooses a word from a dictionary The program gets the possible words from the list based on the length The program calculates the character frequency before asking If the asked character is not in the secret word the possible word list gets updated again If the asked character is in the list the program asks for indices and based on that input the word list gets updated again This concept works very good. The only problem is if several characters occurs with the same count the program asks in alphabetically order, but this can't be optimized I guess and is acceptable. Let´s get through the functions. Here I load the vocabulary file: def read_vocabuary_file(path): """ Function to read the vocabulary file :param path: Path to file :return: List with words """ words = [] with open(path) as file: for line in file: words.append(line.rstrip().lower()) return words This function checks if the word is in the list def check_word(word, words): """ Helper function to check if choosen word is in list :param word: Word choosed by user :param words: Word list :return: True if word is in list - False if not """ if word in words: return True else: return False Get the character frequency def get_char_frequency(words): """ Function to get the frequency of each character in the word list :param words: Word list :return: Frequency dict """ char_counts = Counter(letter for word in words for letter in word) return char_counts
{ "domain": "codereview.stackexchange", "id": 43402, "lm_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, hangman", "url": null }
python, python-3.x, hangman Function to get words with equal length as the hidden word def get_equal_words(word_length, words): """ Function to get possible words with same length :param word_length: The length of the user word :param words: List of words :return: Possible words with equal length """ possible_words = [word for word in words if len(word) == word_length] return possible_words Update function to remove words with wrong character def filter_wrong_characters(character, words): """ Function to update the word list and remove words where asked character is not in :param character: The character for that the program asked :param words: Current word list :return: Updated word list """ possible_words = [word for word in words if character not in word] return possible_words Function to get words where correct character is at a given index def filter_correct_characters(character, indices, words): """ Function to update the word list with potential words :param character: The character for that the program asked :param indices: The indicies where the characters are :param words: Current word list :return: Updated word list """ possible_words = [] for idx in indices: possible_words += [word for word in words if word[int(idx)] == character] return list(set(possible_words)) Helper function to print the current game state def print_screen(your_word, wrong_guess): """ Helper function to print the current game state :param your_word: The masked user word :return: None """ print(HANGMAN[wrong_guess]) print(' '.join(str(i) for i in your_word)) for i in range(len(your_word)): print(i, end=" ") print() Helper function to clear the screen for better readability def clear_screen(): """ Helper function to clear terminal :return: None """ os.system('cls' if os.name == 'nt' else 'clear')
{ "domain": "codereview.stackexchange", "id": 43402, "lm_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, hangman", "url": null }
python, python-3.x, hangman Finally here is the full source code from collections import Counter import os HANGMAN = [''' +---+ | | | | | | =========''', ''' +---+ | | O | | | | =========''', ''' +---+ | | O | | | | | =========''', ''' +---+ | | O | /| | | | =========''', ''' +---+ | | O | /|\ | | | =========''', ''' +---+ | | O | /|\ | / | | =========''', ''' +---+ | | O | /|\ | / \ | | ========='''] def read_vocabuary_file(path): """ Function to read the vocabulary file :param path: Path to file :return: List with words """ words = [] with open(path) as file: for line in file: words.append(line.rstrip().lower()) return words def check_word(word, words): """ Helper function to check if choosen word is in list :param word: Word choosed by user :param words: Word list :return: True if word is in list - False if not """ if word in words: return True else: return False def get_char_frequency(words): """ Function to get the frequency of each character in the word list :param words: Word list :return: Frequency dict """ char_counts = Counter(letter for word in words for letter in word) return char_counts def get_equal_words(word_length, words): """ Function to get possible words with same length :param word_length: The length of the user word :param words: List of words :return: Possible words with equal length """ possible_words = [word for word in words if len(word) == word_length] return possible_words
{ "domain": "codereview.stackexchange", "id": 43402, "lm_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, hangman", "url": null }
python, python-3.x, hangman def filter_wrong_characters(character, words): """ Function to update the word list and remove words where asked character is not in :param character: The character for that the program asked :param words: Current word list :return: Updated word list """ possible_words = [word for word in words if character not in word] return possible_words def filter_correct_characters(character, indices, words): """ Function to update the word list with potential words :param character: The character for that the program asked :param indices: The indicies where the characters are :param words: Current word list :return: Updated word list """ possible_words = [] for idx in indices: possible_words += [word for word in words if word[int(idx)] == character] return list(set(possible_words)) def print_screen(your_word, wrong_guess): """ Helper function to print the current game state :param your_word: The masked user word :return: None """ print(HANGMAN[wrong_guess]) print(' '.join(str(i) for i in your_word)) for i in range(len(your_word)): print(i, end=" ") print() def clear_screen(): """ Helper function to clear terminal :return: None """ os.system('cls' if os.name == 'nt' else 'clear') if __name__ == '__main__': words = read_vocabuary_file('vocabulary.txt') word = str(input('Please enter a word which is in the vocabulary: \t')) word_in_list = False while word_in_list == False: if check_word(word, words): word_in_list = True else: word = str(input('Word not in list, please choose another one: \t')) words = get_equal_words(len(word), words) playing = True your_word = ["_"] * len(word) wrong_guess = 0 clear_screen() print_screen(your_word, wrong_guess)
{ "domain": "codereview.stackexchange", "id": 43402, "lm_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, hangman", "url": null }
python, python-3.x, hangman while playing: word_counts = get_char_frequency(words) for char in ''.join(str(i) for i in your_word): if char in word_counts: del word_counts[char] # try/except block if user messed up the input # for example if he said no but the word contains the asked character # breaks list of possible words try: most_common = word_counts.most_common()[0] except IndexError: print('Ops, something went wrong') break character_contained = str(input(f'Is there a [{most_common[0][0]}] ? - [Y]ES or [N]O :\t')) while character_contained.lower() not in ['yes', 'y', 'no', 'n']: print("Only yes/no is allowd") character_contained = str(input(f'Is there a [{most_common[0][0]}] ? - [Y]ES or [N]O :\t')) if character_contained.lower() in ['yes', 'y']: valid_indices = False while not valid_indices: indices = list(input('At which indices? Please start with 0 and separate them with a space:').split()) for idx in indices: try: your_word[int(idx)] = most_common[0][0] valid_indices = True except: print("Something went wrong. Please check your input again") words = filter_correct_characters(most_common[0][0], indices, words) else: words = filter_wrong_characters(most_common[0][0], words) wrong_guess += 1 clear_screen() print_screen(your_word, wrong_guess) if wrong_guess == 6: clear_screen() print('GAME OVER') print_screen(your_word, wrong_guess) playing = False
{ "domain": "codereview.stackexchange", "id": 43402, "lm_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, hangman", "url": null }
python, python-3.x, hangman if len(words) == 1: clear_screen() print('I found your word:') your_word = words[0] print_screen(your_word, wrong_guess) playing = False I can't upload the vocabulary file, you can download it here This can't ge a bit complicated to understand but I didn't found a better solution. word_counts = get_char_frequency(words) for char in ''.join(str(i) for i in your_word): if char in word_counts: del word_counts[char] Since I always assign the first element of the frequency dict to the variable most_common I first have to delete the characters which the program already guesses correctly. If not the program asks for a character it already founds over and over again.
{ "domain": "codereview.stackexchange", "id": 43402, "lm_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, hangman", "url": null }
python, python-3.x, hangman Answer: Organize programs around functions. The best parts of your current code are the small, well-focused functions and the worst part is the stuff after the main-guard where you deal with user inputs in an ineffective manner. Why is it ineffective? Because you abandoned functions. More details below. Put all code in functions. Everything after the main-guard should be in a function such as main() or play_hangman(). When feasible, select names that agree with grammar. For example, a count of the number wrong guesses should be named in a plural fashion or in a way that conveys the idea of counting: for example, wrong_guesses or n_wrong are better than the singular wrong_guess. Similarly, a list of hangman ascii-images should be HANGMEN, not HANGMAN. Avoid names based on ambiguous pronouns. Names like your_word or my_foo are often a bad idea. When writing/reading a computer program, who is the "you" and who is the "me" or "we" or "they"? In the current code, the implication is that "you" refers to the human player. But "we" (you and me) are the ones writing the code and thinking about it: our perspective is that of a coder, not a player. Rather than getting bogged down in referential mysteries like that, aim for either simpler names where appropriate (eg, just word) or for clarifying names (eg, secret_word or masked_word). If you can return directly from a simple function, do so. In a few functions your code becomes unnecessarily bureaucratic, either by creating an intervening variable that doesn't help with code clarity or by adding unnecessary if-else clauses. Two examples: # Fine, but needlessly heavy. def get_char_frequency(words): char_counts = Counter(letter for word in words for letter in word) return char_counts # Better: return the Counter directly. def get_char_frequency(words): return Counter(letter for w in words for letter in w)
{ "domain": "codereview.stackexchange", "id": 43402, "lm_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, hangman", "url": null }
python, python-3.x, hangman # The if-else structure isn't helping. def check_word(word, words): if word in words: return True else: return False # Better: return the bool directly. # It turns out that we don't need this function, but that's a separate issue. def check_word(word, words): return word in words Alternative names for the filtering functions. Your word-filtering functions have reasonable implementations, but their names are not particularly clear. None of these names convey an accurate sense of what they do: filter_wrong_characters() and filter_correct_characters() sort of imply that we are filtering characters, but we are actually filtering words; and get_equal_words(), in addition to being named differently than the other two functions, sidesteps the main issue, which is not word-equality but word-size. Here are some alternatives to consider. Some points worth noting: (1) the functions establish a naming convention (filter by X); (2) they establish an argument convention (words first because that's what we are filtering, then letter if any, and then other stuff); and (3) the filter_by_known_letter() implementation seems a bit more direct that your current approach because we drive the logic via an iteration over words, eliminating the need to filter out duplicates. def filter_by_word_size(words, size): return [w for w in words if len(w) == size] def filter_by_excluded_letter(words, letter): return [w for w in words if letter not in w] def filter_by_known_letter(words, letter, indices): return [ w for w in words if all(w[i] == letter for i in indices) ]
{ "domain": "codereview.stackexchange", "id": 43402, "lm_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, hangman", "url": null }
python, python-3.x, hangman Handle user input with reusable functions. You need to ask the user for input several times, and each operation involves similar annoying details. The way to avoid repetitive code like that is to think about collecting user input in a general way: start a while-true loop; give the user a prompt; get the user's reply; convert the reply to a value; validate the value; return if OK, otherwise ask for input again. That sounds simple enough, but the slightly tricky part is realizing that a general-purpose function for user input needs to receive conversion and validation behavior as arguments -- in other words, its arguments will be functions. Here's one way to do that kind of thing. [As it turns out, your program can rely entirely on the choices approach to validation, but I've left the validate parameter in place here to illustrate the general approach.] def get_input(prompt, convert = None, validate = None, choices = None): # Prepare the conversion and validation functions. convert = convert or (lambda x: x) if choices: validate = lambda x: x in choices elif validate is None: validate = lambda x: True # Get user reply: convert and return if valid. while True: reply = input(prompt + ': ') try: value = convert(reply) if validate(value): return value except Exception: pass prompt = 'Invalid input. Try again'
{ "domain": "codereview.stackexchange", "id": 43402, "lm_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, hangman", "url": null }
python, python-3.x, hangman The user-interaction is too heavy and error-prone. Your program reverses the typical hangman approach where the human guesses and the computer reveals. That's perfectly fine both as a game and as a learning exercise, but it does set up an odd dynamic where the computer is asking the human for answers that the computer already knows -- specifically, whether the letter is in the word and where the letter is located. And since humans can make mistakes, this dynamic forces you to handle exceptions caused by data-entry errors related to the indices. Two simplifications are possible. (1) Don't ask the user whether and where (two questions); instead just ask where (interpret empty reply as nowhere). (2) Compute the expected indices and pass them to get_input() as the only allowed choice, eliminating the possibility of data-entry errors. Some adjustments to the printing function. It's good that you've centralized your screen printing logic in one place. A few adjustments can simplify the function and its usage. (1) You always clear before printing, so just move the clear_screen() call into print_screen(). (2) Strings are iterable, so you can print both the masked word and its indices via simple print-join operations. (3) When the game is over, you have some awkward code that ends up printing the screen twice, first in the ordinary way and then with a game-over message. You can eliminate that repetition by adding an optional message parameter to the print_screen() function. def print_screen(masked_word, wrong_guesses, message = None): clear_screen() print(HANGMEN[wrong_guesses]) print(' '.join(masked_word)) print(' '.join(map(str, range(len(masked_word))))) if message: print(message)
{ "domain": "codereview.stackexchange", "id": 43402, "lm_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, hangman", "url": null }
python, python-3.x, hangman Playing hangman. With those changes in place, the game-playing function can be simplified a fair bit. A few other points worth noting: (1) where it makes sense, outsource logical details to utility functions, such as most_common_letter(); (2) readability in a moderately large function like this can be enhanced with fairly simple comments that organize the code into smaller logical units; (3) to get indices from the user, we need a small data-conversion function; and (4) rather than hardcoding six wrong guesses as a game-over condition, compare the number of wrong guesses to the length of HANGMEN. def play_hangman(): # Select word from vocabulary. words = read_vocabuary_file('vocabulary.txt') word = get_input( 'Please enter a word which is in the vocabulary', choices = words, ) # Filter down to words of that size. size = len(word) words = filter_by_word_size(words, size) masked_word = ['_'] * size # Play until solved or failed. game_over = None wrong_guesses = 0 print_screen(masked_word, wrong_guesses) while not game_over: # Guess the most common letter. letter = most_common_letter(words, masked_word) # Force the poor human to enter the letter locations, if any. expected_indices = [i for i, c in enumerate(word) if c == letter] indices = get_input( f'If the word contains [{letter}], enter its indices', convert = parse_ints, choices = [expected_indices], ) # Filter words based on reply. if indices: words = filter_by_known_letter(words, letter, indices) for i in indices: masked_word[i] = letter else: words = filter_by_excluded_letter(words, letter) wrong_guesses += 1
{ "domain": "codereview.stackexchange", "id": 43402, "lm_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, hangman", "url": null }
python, python-3.x, hangman # Check for game over. if wrong_guesses >= len(HANGMEN): game_over = 'GAME OVER!' elif len(words) == 1: game_over = 'I found your word!' masked_word = words[0] # Display. print_screen(masked_word, wrong_guesses, message = game_over) def most_common_letter(words, masked_word): counts = get_char_frequency(words) for c in masked_word: counts.pop(c, None) return counts.most_common()[0][0] def parse_ints(reply): return sorted(map(int, reply.split()))
{ "domain": "codereview.stackexchange", "id": 43402, "lm_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, hangman", "url": null }
c++, object-oriented, static Title: Accept an array, erase some elements and print the array Question: I'm trying to learn about OOP, specifically encapsulation, and use of static. My goal is to improve my coding skills, I am just looking for feedback specific to encapsulation, the use of static, and any other tips to make this "production quality". I don't feel confident the Solve method has been implemented correctly. By instantiating the object its contained within. Similarly the call to solve in main. The question was very simple (accept an array, erase some elements and print the array) and very specific about the format of data. Given the size of a vector, its elements, an element to delete, and a range of elements to delete, after the first delete operation. Perform the deletes, and return the size of the array and its contents. Input: 6 1 4 6 2 8 9 2 2 4 Output: 3 1 8 9 #include <iostream> #include <vector> class File { int size = 0; int eraseStart = 0; int eraseEnd = 0; int eraseEle = 0; std::vector<int> v; public: const std::vector<int> getVect() { return v; } const int getStart() { return eraseStart; } const int getEnd() { return eraseEnd; } const int getEraseEle() { return eraseEle; } void processData() { int temp = 0; std::cin >> size; for (int i = 0; i < size; i++) { std::cin >> temp; v.push_back(temp); } std::cin >> eraseEle; std::cin >> eraseStart >> eraseEnd; return; } void print() { std::cout << size << '\n'; for (auto x : v) { std::cout << x << ' '; } std::cout << '\n'; return; } void erase1(int i) { v.erase(v.begin() + i - 1); size--; return; } void eraseRange(int start, int end) { v.erase(v.begin() + start - 1, v.begin() + end - 1); size -= end - start; return; }
{ "domain": "codereview.stackexchange", "id": 43403, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, object-oriented, static", "url": null }
c++, object-oriented, static static void solve() { File file; file.processData(); file.erase1(file.getEraseEle()); file.eraseRange(file.getStart(), file.getEnd()); file.print(); return; } }; int main() { File::solve(); return 0; } Answer: The issues you are interested in are deep, deep issues of software design and idiomatic C++. There’s no “right” answer, and different C++ experts will have different opinions about what the “best” solution would look like. So, there’s just no possible way I can give an answer that isn’t at least partially coloured by my own biases. Please keep that in mind. I’d start a design review by suggesting a top-down approach: start with what you think a really good solution should look like, and then figure out the details. So, okay, what would a really good solution look like. Would it look like File::solve();? I’d say no. What’s wrong with File::solve();? Well: It’s utterly meaningless. If you saw File::solve(); in someone else’s program, what would you think? What is that line doing? What does it mean? It’s completely inflexible. Whatever File::solve(); does, it clearly doesn’t give the user any say in how, when, or where it’s doing it. As a user, I chafe at the idea that the person who wrote that function thinks they know more than I do about what I want or need. It’s literal nonsense: How do you “solve” a file?
{ "domain": "codereview.stackexchange", "id": 43403, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, object-oriented, static", "url": null }
c++, object-oriented, static The name solve() isn’t really the problem; the issue is that there is no good explanation of what is being solved, or how. The real problem here is File. This class does not describe a file, and even if it did, that is not what any of this is really about. So File is a terrible name. What would be a good name? Well, what is the class actually about? It’s about some kind of challenge, it seems. So, maybe a name like array_modification_problem (or ArrayModificationProblem, if you prefer; I just find snake case easier to read). That would give you array_modification_problem::solve()… which, to me, is a lot clearer, and even reads better. If I saw that in code, I would immediately understand that there is some problem involving modifying arrays, and this line is solving it. Which, while vague, is correct. There’s still a problem, though… well, half of a problem. The solver is completely inflexible. You can’t control anything about it. What if you don’t want to read the data from std::cin? What if you want to read it from a file instead? And what if you don’t want to write the results to std::cout? There’s another important reason to give this flexibility: testing. You should ALWAYS test your code. In fact, you should write tests for your code, before you write the code. Code without tests is garbage code; I won’t accept code without tests in any projects I’m in charge of. The best thing you can learn as a coder, is how to PROPERLY test your code. If you hard-code std::cin and std::cout into your solver, you make it extremely difficult to test. If you take the input and output streams as arguments, then you make it easy to test. For example: class array_modification_problem { public: static auto solve(std::istream& in, std::ostream& out) { // actual solution here } static auto solve() { return solve(std::cin, std::cout); } // ... };
{ "domain": "codereview.stackexchange", "id": 43403, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, object-oriented, static", "url": null }
c++, object-oriented, static static auto solve() { return solve(std::cin, std::cout); } // ... }; // Example of how to test, using Catch2: TEST_CASE("example case") { constexpr auto example_input = R"(6 1 4 6 2 8 9 2 2 4 )"; constexpr auto example_output = R"(3 1 8 9 )"; auto in = std::istringstream{example_input}; auto out = std::ostringstream{}; array_modification_problem::solve(in, out); REQUIRE(out.str() == example_output); } Note that I’ve included an overload that defaults the input and output streams to std::cin and std::cout, so you can still do array_modification_problem::solve(); as a shorthand for array_modification_problem::solve(std::cin, std::cout);. See how being able to provide your own streams as input and output makes testing easy? We simply create a string stream, fill it with the example input, run the solver, and then check that the expected results were written to the output string stream. Easy peasy. If you had no way to specify the streams, this would become incredibly hard. But let’s go a step further. Because maybe we don’t want to just print the results. Maybe we might want the final vector. We might want to do a more complex problem of which this problem is only a sub-step. So in addition to the two solve() functions above, I’d also suggest one that takes an input stream, and just returns the final vector: class array_modification_problem { public: static auto solve(std::istream& in) { // read the data from in // solve the problem // return the final vector } static auto solve(std::istream& in, std::ostream& out) { auto result = solve(in); // write result to out } static auto solve() { return solve(std::cin, std::cout); } // ... };
{ "domain": "codereview.stackexchange", "id": 43403, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, object-oriented, static", "url": null }
c++, object-oriented, static static auto solve() { return solve(std::cin, std::cout); } // ... }; This makes the solver much more flexible, and as a bonus, it makes testing even easier. But we can go even further! Consider the problem. The input data to the problem is a vector, a single number, then a pair of numbers. So… why not actually code a function that just takes that directly? static auto solve(std::vector<int> data, int position, std::pair<int, int> range) { data.erase(data.begin() + (position - 1)); data.erase(data.begin() + (std::get<0>(range) - 1), data.begin() + (std::get<1>(range) - 1)); return data; } All other functions can now be written in terms of this function. You just need two helpers: static auto read(std::istream& in) { // this is basically your processData() function // read the data vector, the position, and then the two range numbers return std::tuple{data, position, std::tuple{start, end}}; } static auto write(std::vector<int> const& data, std::ostream& out) { // this is basically your print() function } And now everything else is easy: static auto solve(std::istream& in) { auto [data, position, range] = read(in); return solve(std::move(data), position, range); } static auto solve(std::istream& in, std::ostream& out) { write(solve(in), out); } static auto solve() { return solve(std::cin, std::cout); } So, so far, the interface of the class looks like this: class array_modification_problem { public: // Input/output functions ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Read problem data from stream. static auto read(std::istream& in) -> std::tuple<std::vector<int>, int, std::tuple<int, int>>; // Write solution to stream. static auto write(std::vector<int> const& data, std::ostream& out) -> void;
{ "domain": "codereview.stackexchange", "id": 43403, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, object-oriented, static", "url": null }
c++, object-oriented, static // Actual solution function ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ static auto solve(std::tuple<std::vector<int>, int, std::tuple<int, int>> problem_data) -> std::vector<int>; // Nicer interface functions to simplify the above ~~~~~~~~~~~~~~~~~ static auto solve(std::istream& in) -> std::vector<int>; static auto solve(std::istream& in, std::ostream& out) -> void; static auto solve() -> void; }; I’d say that’s a pretty decent interface. It’s easy to use. And so long as you pass legal values, it’s pretty darn hard to misuse. But now we get to the part that you’re really interested in. Note that in the interface about, I use this large tuple type twice: std::tuple<std::vector<int>, int, std::tuple<int, int>> That tuple type is the problem data: the vector, the position for the single removal, and then the range for the range removal. While using a tuple for this works, it’s kind of ugly. So what if we instead use the actual problem class to store the problem data (as you did): class array_modification_problem { public: // Input/output functions ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Read problem data from stream. static auto read(std::istream& in) -> array_modification_problem; // Write solution to stream. static auto write(std::vector<int> const& data, std::ostream& out) -> void; // Actual solution function ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ static auto solve(array_modification_problem const& problem_data) -> std::vector<int>; // Nicer interface functions to simplify the above ~~~~~~~~~~~~~~~~~ static auto solve(std::istream& in) -> std::vector<int>; static auto solve(std::istream& in, std::ostream& out) -> void; static auto solve() -> void; };
{ "domain": "codereview.stackexchange", "id": 43403, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, object-oriented, static", "url": null }
c++, object-oriented, static We can still use a bare vector for the result… because that’s all the result is: just a vector. Now we can implement the problem data like so: class array_modification_problem { std::vector<int> _data; int _pos; std::tuple<int, int> _rng; public: // Input/output functions ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Read problem data from stream. static auto read(std::istream& in) -> array_modification_problem; // Write solution to stream. static auto write(std::vector<int> const& data, std::ostream& out) -> void; // Actual solution function ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ static auto solve(array_modification_problem const& problem_data) -> std::vector<int>; // Nicer interface functions to simplify the above ~~~~~~~~~~~~~~~~~ static auto solve(std::istream& in) -> std::vector<int>; static auto solve(std::istream& in, std::ostream& out) -> void; static auto solve() -> void; // Constructor for problem data ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // this doesn't *need* to be public; you *could* make it private, but // since it is safe (assuming you do the checks mentioned below), it's // okay to make it public; it will make testing easier (because you can // create problem test data directly, without needing to put it in a // stream and parse it) array_modification_problem(std::vector<int> data, int position, std::tuple<int, int> range) : _data{std::move(data)} , _pos{position} , _rng{range} { // here we could check that the position and range values are okay // (like, that all the values are in range for the data vector), // and if not, throw an exception } };
{ "domain": "codereview.stackexchange", "id": 43403, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, object-oriented, static", "url": null }
c++, object-oriented, static Now, what you’re concerned about—instantiating an object of the class within one of the static functions—is not a problem at all. That’s basically what all of the “nicer interface” functions above are doing. It is possible to instantiate an object of the class outside of those static functions either using read() or the constructor… but it doesn’t have to be; we could make those functions private, and everything would still be just fine (the class would just become a little less flexible). (Performance-wise, there’s one small problem: The vector of numbers doesn’t get reused, so a whole new vector has to be created for the result. This is an easy fix, though; just add an overload of solve() that takes the problem data by rvalue reference, and then you can steal the vector out of it. But really getting into the performance weeds here will just add complications unrelated to the questions you’re interested in.) So the above is basically what I would do if I were writing this. As you can see, it’s pretty darn close to what you did! But there are some very important differences, that I really think need to be pointed out. So let’s look at your version. The first problem I have with your version—other than that I think the name File is bad—is that the class is default-constructible… and the default constructed data is illegal. That’s… pretty bad. In a well-written class, it should never be possible to create an illegal state (at least not without doing something incredibly stupid). Your class creates an illegal state by default. And why is it illegal? Well, in the default constructed class, eraseEle, the position for the single element erasure, is 0. But… the numbers in the problem are 1-based. 0 is just plain illegal. It turns out, though, that this isn’t actually a problem, because, for example, the erase1() function doesn’t even use eraseEle; it takes the position to erase as an argument.
{ "domain": "codereview.stackexchange", "id": 43403, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, object-oriented, static", "url": null }
c++, object-oriented, static Except… that creates an entirely new problem. Because a user of the class can pass literally any integer to erase1(). They can pass 0. Or −1. Literally anything. So the second problem I have with your version is: all of your intermediate operation functions should be private. There is no reason to give J Rando User the power to call erase1() directly. That’s just inviting them to screw something up. Note that the problem isn’t that you’ve made all the intermediate steps into functions. That’s fine; I know I didn’t do that above, but maybe I should have. I could have done something more like this: private: auto erase_1() { _data.erase(_data.begin() + (_pos - 1)); }
{ "domain": "codereview.stackexchange", "id": 43403, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, object-oriented, static", "url": null }
c++, object-oriented, static auto erase_range() { _data.erase(_data.begin() + (std::get<0>(_rng) - 1), _data.begin() + (std::get<1>(_rng) - 1)); } public: static auto solve(array_modification_problem problem_data) { problem_data.erase_1(); problem_data.erase_range(); return problem_data._data; } That’s fine because erase_1() and erase_range() are private, so I don’t need to check that the arguments are valid. I do need to check that they’re valid in the public function, though… except that’s already handled in the constructor. So everything is safe. It’s impossible to screw up. array_modification_problem is always created with valid data (or the constructor will throw), and so you can never call solve() with bad data, and thus it should always return valid results. This probably isn’t the best way to do this, though, because after the first step, the problem data is now messed up. It’s okay here, because the messed up data is isolated within the solve() function. But you need to be careful if you ever refactor the class. It’s a bad idea to write functions that leave your class in an illegal state, even if they’re only used internally. That’s why I’d prefer to just do the two steps inline in solve(), with no help from other functions. Your mileage may vary. There are plenty of other issues that arise from making these intermediate step functions public, too. For example, consider what would happen if someone called processData() twice. (This isn’t such a crazy idea. Someone might be solving these problems in a loop, and they might want to reuse the object.) There are only a few other small things to mention:
{ "domain": "codereview.stackexchange", "id": 43403, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, object-oriented, static", "url": null }
c++, object-oriented, static size is pointless. v knows what size it is. All the effort you go through to keep size in sync with v.size() is error-prone and wasteful. All four of the accessor functions are pointless. There is no reason to give users access to the internals of the class. Also regarding the accessors: Returning const values is (almost) always wrong. It doesn’t really help anything—the user can strip away the const effortlessly. In all the other functions except the accessors: The final return; statement is pointless. In processData(): temp should not be declared at the top of the function. It should be declared right where you need it. (Which is right before std::cin >> temp;.) Also in processData(): After reading size, you know how big the vector is supposed to be. At that point, you should call v.reserve(size);. This will prevent repeated re-allocations as you push back the elements, which could be a massive speedup. So in summary, I think your concern is unwarranted: your solve() function is implemented just fine. It’s everything else that I think is problematic: Never allow objects to be constructible in an illegal state. If there is a sane default state, use that. If there is no sensible default state—as is the case here—then don’t allow default construction. Never allow objects to be left in an illegal state. Every function that can change the object should leave it in a legal state. Don’t make functions public if the user should never be allowed to call them. In your case, most of the functions in your class are dangerous, because they either should only be called in certain situations (like you can only call erase1() directly after processData()), and/or they can only be called exactly once. Your public interface should be idiot-proof, as much as possible… so giving random users access to functions that are so finicky and dangerous is a recipe for disaster. Test your code. Learn how to test properly, and write your classes so they can be easily tested.
{ "domain": "codereview.stackexchange", "id": 43403, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, object-oriented, static", "url": null }
c++, mergesort, heap Title: Adjusting heaps efficiently Question: Introduction and context I am working on a small application which involves sorting 20GB files as one of the operations. This is being done, due to memory constraints, by breaking them into ~1GB chunks, sorting in memory and then writing back to disk. Then, as stage 2, reading the head of each file and picking the smallest/largest and streaming to the final output file. This falls into the domain of External sorting. This CR will focus on just one small part of that which involves "picking which chunk to take the next element from" when streaming to the final file. It turns out that this part, and specifically the element comparison, is CPU bound and the bottleneck. The elements being sorted are std::array<std::byte, 20>, so a non-trivial comparison, which compiles down to memcmp. EDIT It turns out that we can be significantly faster than memcmp with some very simple "big 64-bits load, byte-swap and compares". See my self answer below END-EDIT So we need a data structure which makes it easy to pick the next element. Typically there are around 20 chunks, so my first attempt was just using std::min_element because linear search can be really fast for a small number of elements. When I discovered the comparisons were the CPU bottleneck I moved to using a std::priority_queue. This reduced the comparisons by > 2x, so that was a big gain. For clarification, that reduction in the number of comparisons, also brought a 2x speed up in the full application, from 6mins for the merge stage of the 20 x 1GB files, down to 3mins. But at 3mins, the CPU is still @ 100% and almost all inside the operator< of the 20 byte array. This CR is about whether we can do better still, by reducing the number of comparisons further. You cannot change/update elements in a std::priority_queue, and that is exactly what we we need to do. This is the algorithm of the critical loop std::priority_queue<head, std::vector<head>, decltype(cmp)> heads(cmp);
{ "domain": "codereview.stackexchange", "id": 43404, "lm_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++, mergesort, heap", "url": null }
c++, mergesort, heap while (!heads.empty()) { const head& t = heads.top(); sorted.write(t.value); std::size_t chunk_idx = t.idx; heads.pop(); if (auto& chunk = chunks[chunk_idx]; chunk.current != chunk.end) { heads.push({*(chunk.current), chunk_idx}); ++(chunk.current); } } So, it seems very inefficient to call queue.pop() and then queue.push() both of which need to move elements through the heap. It would seem more efficient to just "change" the .top() (having read it and written it to output), to the new value (essentially calling std::next or ++ on the iterator of that chunk) and then "re-heapifying". Let get under the hood of std::priority_queue. The canonical way to do this using the c++ STL heap algorithms is: // Note I am using a max-heap, but the comparator is customisable below std::pop_heap(heap.begin(), heap.end(), comp); heap.pop_back(); heap.push_back(newval); std::push_heap(heap.begin(), heap.end(), comp); Most heap implementations use primitives underneath called something like "bubble/sift up/down". All we actually need is the bubble_down implementation and call that on the changed, top() element. The c++ standard does not offer primitives, but implementations are not hard and there are 2 (one iterative and one recursive) in the code below. Investigation Focus Relatively small heaps (3 => 100 elements, but easily adjustable in code below) Operation: Update the heap.top() element ONLY Optimisation criteria = number of comparisons to re-heapify This is a very simple case. No question of "knowing where the element to be changed is in the heap" - a typical concern with this approach. So surely we can do better, right...? The code below studies 4 implementations: STL way as above (using libstdc++-11). This is the base case. (Note that I believe libc++ is less sophisticated in this area). A recursive "bubble down" algo An iterative "bubble down" algo A libstd++ __adjust_heap followed by __push_heap algo
{ "domain": "codereview.stackexchange", "id": 43404, "lm_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++, mergesort, heap", "url": null }
c++, mergesort, heap I generate random heap sizes, contents and replacement value and iterate 1M times. Findings The STL is Good The recursive and iterative bubble down alogs are nearly identical (expected, because the compiler, on -O3, "tailcall optimises" the recursion away) and, surprisingly, consistently have more comparisons than the STL even for this very specialised case. So just using a heap-primitive doesn't give you any gains. We can beat the STL using... the STL , by copying out the code of the unpublished functions, "cleaning them up" (of underscores etc) and using them in a specialised way to solve this limited, specialised problem. Gains are in the order of 10-20%. A modest, but significant gain? Typical results: method avg_cmp_cnt std::heap / std::priority_queue 7.568285 bubble up recursively 8.031054 bubble up iteratively 8.047352 libstc++ __adjust_heap 6.327297 The code: #include "fmt/core.h" #include <algorithm> #include <cassert> #include <concepts> #include <cstddef> #include <cstdlib> #include <execution> #include <iostream> #include <random> #include <stdexcept> template <std::unsigned_integral T> T log2(T x) { T log = 0; while (x >>= 1U) ++log; return log; }
{ "domain": "codereview.stackexchange", "id": 43404, "lm_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++, mergesort, heap", "url": null }
c++, mergesort, heap template <typename T, typename Comp = std::less<>> void print_heap(const std::vector<T>& heap, Comp comp = {}) { std::size_t levels = log2(heap.size()) + 1; unsigned width = 6 * (1U << (levels - 1U)); std::cout << "\n\n"; for (const auto& e: heap) std::cout << e << " "; std::cout << "\n"; std::cout << fmt::format("is_heap = {:}\n\n", std::is_heap(heap.begin(), heap.end(), comp)); if (heap.empty()) { std::cout << "<empty heap>\n"; return; } unsigned idx = 0; bool done = false; for (unsigned l = 0; l != levels; ++l) { for (unsigned e = 0; e != 1U << l; ++e) { std::cout << fmt::format("{:^{}}", heap[idx], width); ++idx; if (idx == heap.size()) { done = true; break; } } width /= 2; std::cout << "\n\n"; if (done) break; } } template <typename T, typename Comp = std::less<>> void replace_top_using_stl(std::vector<T>& heap, T newval, Comp comp = {}) { if (heap.empty()) throw std::domain_error("can't replace_top on an empty heap"); assert(std::is_heap(heap.begin(), heap.end(), comp)); std::pop_heap(heap.begin(), heap.end(), comp); heap.pop_back(); heap.push_back(newval); std::push_heap(heap.begin(), heap.end(), comp); } template <typename T, typename Comp = std::less<>> // NOLINTNEXTLINE recursion is tailcall eliminated by compiler void bubble_down_recursively(std::vector<T>& heap, std::size_t i, Comp comp = {}) { const auto left = 2 * i + 1; const auto right = 2 * i + 2; const auto n = heap.size(); using std::swap; // enable ADL
{ "domain": "codereview.stackexchange", "id": 43404, "lm_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++, mergesort, heap", "url": null }
c++, mergesort, heap using std::swap; // enable ADL if (left >= n) { // no children return; } else if (right >= n) { // left exists right does not. NOLINT else after return if (comp(heap[i], heap[left])) { swap(heap[i], heap[left]); bubble_down_recursively(heap, left, comp); } } else { // both children exist // 'larger' is only well named if comp = std::less<>{} auto larger = comp(heap[right], heap[left]) ? left : right; if (comp(heap[i], heap[larger])) { swap(heap[i], heap[larger]); bubble_down_recursively(heap, larger, comp); } } } template <typename T, typename Comp = std::less<>> void replace_top_using_bubble_down_recursively(std::vector<T>& heap, T newval, Comp comp = {}) { if (heap.empty()) throw std::domain_error("can't replace_top on an empty heap"); assert(std::is_heap(heap.begin(), heap.end(), comp)); heap[0] = newval; bubble_down_recursively(heap, 0, comp); } template <typename T, typename Comp = std::less<>> void bubble_down_iteratively(std::vector<T>& heap, std::size_t i, Comp comp = {}) { const auto n = heap.size(); while (true) { const std::size_t left = 2 * i + 1; const std::size_t right = 2 * i + 2; std::size_t largest = i; if ((left < n) && comp(heap[largest], heap[left])) { largest = left; } if ((right < n) && comp(heap[largest], heap[right])) { largest = right; } if (largest == i) { break; } using std::swap; // enable ADL swap(heap[i], heap[largest]); i = largest; } } template <typename T, typename Comp = std::less<>> void replace_top_using_bubble_down_iteratively(std::vector<T>& heap, T newval, Comp comp = {}) { if (heap.empty()) throw std::domain_error("can't replace_top on an empty heap"); assert(std::is_heap(heap.begin(), heap.end(), comp)); heap[0] = newval; // stick it in anyway bubble_down_iteratively(heap, 0, comp); // and fix the heap }
{ "domain": "codereview.stackexchange", "id": 43404, "lm_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++, mergesort, heap", "url": null }
c++, mergesort, heap // borrowed from libstdc++ __push_heap template <typename RandomAccessIterator, typename Distance, typename Tp, typename Compare> constexpr void push_heap(RandomAccessIterator first, Distance holeIndex, Distance topIndex, Tp value, Compare& comp) { Distance parent = (holeIndex - 1) / 2; while (holeIndex > topIndex && comp(*(first + parent), value)) { *(first + holeIndex) = *(first + parent); holeIndex = parent; parent = (holeIndex - 1) / 2; } *(first + holeIndex) = std::move(value); } // borrowed from libstdc++ __adjust_heap template <typename RandomAccessIterator, typename Distance, typename Tp, typename Compare> constexpr void adjust_heap(RandomAccessIterator first, Distance holeIndex, Distance len, Tp value, Compare comp) { const Distance topIndex = holeIndex; Distance secondChild = holeIndex; while (secondChild < (len - 1) / 2) { secondChild = 2 * (secondChild + 1); if (comp(*(first + secondChild), *(first + (secondChild - 1)))) secondChild--; *(first + holeIndex) = *(first + secondChild); holeIndex = secondChild; } if ((len & 1) == 0 && secondChild == (len - 2) / 2) { secondChild = 2 * (secondChild + 1); *(first + holeIndex) = *(first + (secondChild - 1)); holeIndex = secondChild - 1; } push_heap(first, holeIndex, topIndex, value, comp); } template <typename T, typename Comp = std::less<>> void replace_top_using_adjust_heap(std::vector<T>& heap, T newval, Comp comp = {}) { if (heap.empty()) throw std::domain_error("can't replace_top on an empty heap"); assert(std::is_heap(heap.begin(), heap.end(), comp)); heap[0] = newval; adjust_heap(heap.begin(), 0L, heap.end() - heap.begin(), newval, comp); }
{ "domain": "codereview.stackexchange", "id": 43404, "lm_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++, mergesort, heap", "url": null }
c++, mergesort, heap heap[0] = newval; adjust_heap(heap.begin(), 0L, heap.end() - heap.begin(), newval, comp); } template <typename T> struct cmp_counter { static std::size_t cmpcount; // NOLINT must be static because STL takes Comp by value bool operator()(T a, T b) { ++cmpcount; return a < b; // effectively std::less<>{}; } static void reset() { cmpcount = 0; } }; template <typename T> std::size_t cmp_counter<T>::cmpcount = 0; // NOLINT global static int main() { using ValueType = int; struct method { using cb_t = void (*)(std::vector<ValueType>&, ValueType, cmp_counter<ValueType>); std::string label; cb_t cb; }; auto methods = std::vector<method>{ {"std::heap / std::priority_queue", &replace_top_using_stl}, {"bubble up recursively", &replace_top_using_bubble_down_recursively}, {"bubble up iteratively", &replace_top_using_bubble_down_iteratively}, {"libstc++ __adjust_heap", &replace_top_using_adjust_heap}, }; std::cout << fmt::format("{:35s} {:s}\n", "method", "avg_cmp_cnt"); for (auto& method: methods) { auto prng = std::mt19937_64(1); // NOLINT fixed seed for repeatability auto heap_element_dist = std::uniform_int_distribution<>(1, 100); auto heap_size_dist = std::uniform_int_distribution<std::size_t>(3, 100); const std::size_t number_of_trials = 1'000'000; std::size_t total_cmpcount = 0; cmp_counter<ValueType> comp; for (unsigned i = 0; i != number_of_trials; ++i) { std::vector<int> h(heap_size_dist(prng)); std::generate(h.begin(), h.end(), [&] { return ValueType(heap_element_dist(prng)); }); std::make_heap(h.begin(), h.end(), comp); auto newval = ValueType(heap_element_dist(prng)); cmp_counter<ValueType>::reset(); method.cb(h, newval, comp); total_cmpcount += cmp_counter<ValueType>::cmpcount;
{ "domain": "codereview.stackexchange", "id": 43404, "lm_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++, mergesort, heap", "url": null }
c++, mergesort, heap if (!std::is_heap(h.begin(), h.end(), comp)) { std::cerr << method.label << "NOT A HEAP ANYMORE!!\n"; return EXIT_FAILURE; } } std::cout << fmt::format("{:35s} {:f}\n", method.label, double(total_cmpcount) / number_of_trials); } }
{ "domain": "codereview.stackexchange", "id": 43404, "lm_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++, mergesort, heap", "url": null }
c++, mergesort, heap Answer: Minimizing comparisons All the algorithms you have tested need \$O(\log N)\$ comparisons. The __adjust_heap() method seems to save about one comparison on average. I am not sure if you can do much better than that using heaps or trees to sort the priority queue. It might be possible to do a space vs. time tradeoff. If you could find a way to compress the keys such that the index into an array of buckets that is several times larger than the number of chunks, then inserting or removing a key from that array would on average not need any comparisons, as a bucket would most likely be empty on insertion or have 1 element on removal. Then the remaining problem is finding the first bucket with an item in it, which would have its own cost that scales with the number of buckets, but which can probably be done very cheaply. The trick is then finding a balance so maintaining this array is cheaper than maintaining a heap. As for the code itself: Use std::ranges You are using C++20 features, but I'm missing the use of std::ranges, which would simplify some of the code. Use std::bit_width() to implement log2() I am a bit surprised that both GCC and Clang did not manage to optimize your naive implementation of the integer base-2 logarithm. But if you use std::bit_width() - 1, they manage to replace the loop with a lzcnt instruction on x86 architectures. Make your code even more generic You did make a significant effort to make your code generic by templating it on the value type of the container and on the comparison functions, however you should be able to make it work on containers other than std::vector. I would just copy the interface of std::ranges::pop_heap() and related functions. For extra fun, you could make cmp_counter() a function adapter, that by default adapts std::less but that would allow you to have it add a counter to any comparison operator. Make use of front() and back()
{ "domain": "codereview.stackexchange", "id": 43404, "lm_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++, mergesort, heap", "url": null }
c++, mergesort, heap Make use of front() and back() Especially if you make your code more generic, you shouldn't assume that the containers are random accessible, and avoid code like heap[0] = .... Instead you can write things like: heap.front() = newval;
{ "domain": "codereview.stackexchange", "id": 43404, "lm_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++, mergesort, heap", "url": null }
c++, mergesort, heap And you can replace the pop() and push() operations with a single heap.back() = newval inside replace_top_using_stl(). Add more static and const I already see good use of const, but no static outside of cmp_counter. Consider making most functions static. Furthermore, you can use const in more cases. And in particular, methods can be made a static const array. Inconsistent use of fmt::format() I see fmt::format() in a few places, but in other cases you just concatenate output using <<. I recommend using fmt::format() consistently. Even better, avoid having to write std::cout << by using fmt::print().
{ "domain": "codereview.stackexchange", "id": 43404, "lm_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++, mergesort, heap", "url": null }
validation, sh Title: Chaining perf with FlameGraph Question: This is my first serious shell script, so it is probably horrible. Problem statement I decided to improve my profiling skills as so far they were mostly about hand-rolling counters and timers. After trying out better profiling tools and techniques I noticed that previously I was just rolling my face over keyboard until the metrics got better. Yet to do profiling in a consistent and hassle-free way is a bit tedious. perf is a profiling utility used to collect software and hardware metrics about program's execution or entirety of the machine. It outputs binary files that can be fed into variety of tools, but I decided on FlameGraph. The problem with it is that it takes several commands and the overall process is rather boring. I decided to automate it with a shell script that invokes needed commands with the flags I usually use. Code #!/bin/sh usage="$(basename "$0") [-g fgdir] [-h] -t target where: -h show this help text -t executable to run under perf -g root directory of FlameGraph repository https://github.com/brendangregg/FlameGraph " fgroot="." while getopts 'g:ht:' option; do case "$option" in h) echo "$usage" exit ;; t) if ! [ -x "$(command -v "$OPTARG")" ]; then echo "$OPTARG is not executable" exit 1 fi echo "$OPTARG" target="$OPTARG" ;; g) fgroot="$OPTARG" echo "$OPTARG" ;; :) printf "missing argument for -%s\n" "$OPTARG" >&2 echo "$usage" >&2 exit 1 ;; \?) printf "illegal option: -%s\n" "$OPTARG" >&2 echo "$usage" >&2 exit 1 ;; esac done shift $((OPTIND - 1)) scpath="$fgroot/stackcollapse-perf.pl" fgpath="$fgroot/flamegraph.pl" echo "$scpath" "$fgpath" if ! [ "$(command -v "$scpath")" ]; then printf "could not find stackcollapse-perf.pl\n" exit 1 fi
{ "domain": "codereview.stackexchange", "id": 43405, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "validation, sh", "url": null }
validation, sh if ! [ "$(command -v "$fgpath")" ]; then printf "could not find flamegraph.pl\n" exit 1 fi #filename=$(date +"%Y-%m-%d-%Hh-%Mm-%Ss").perf filename=$(date -u +"%Y-%m-%dT%H:%M:%S%Z") perf record -g --call-graph=dwarf -F 99 "$target" perf script > "$filename".perf $scpath "$filename".perf > "$filename".collapsed $fgpath "$filename".collapsed > "$filename".svg Is the interface idiomatic (command line argument letters, usage string, etc)? Is it possible to write the shell script in an easier to understand way? Is there any more useful checking I should do inside my code? Sample output: Answer: Some of your diagnostic messages are being sent to stdout; you want to send all of them to stderr (>&2). A good practice is to include the script's name in these messages, so you can see who is emitting a message when you have scripts calling scripts calling scripts etc. (Many of these echos were apparently just for debugging anyway; I commented out those instead.) As a minor refactoring, I turned usage into a function. I made usage return exit code 1, which is a fairly common convention, and thus changed the other error cases to return exit codes 2, 3, etc to allow a caller to distinguish between these cases. Perhaps make up your mind regarding whether to use echo or printf. The former is less versatile but often more compact for simple messages. The check for whether the argument to -t is executable or not is slightly problematic; command -v will not output anything if it isn't. But I don't see an easy way to rephrase that. Perhaps the error message should be rearticulated, though? The conventional way to use command -v is to simply run it directly, without a command substitution; perhaps see also Why is testing "$?" to see if a command succeeded or not, an anti-pattern? for a discussion, though that's not exactly the problem here. #!/bin/sh me="$(basename "$0")"
{ "domain": "codereview.stackexchange", "id": 43405, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "validation, sh", "url": null }
validation, sh me="$(basename "$0")" usage () { printf '%s\n' >&2 \ "$me [-g fgdir] [-h] -t target" "" \ " where:" \ " -h show this help text" \ " -t executable to run under perf" \ " -g root directory of FlameGraph repository https://github.com/brendangregg/FlameGraph" "" exit 1 } fgroot="." while getopts 'g:ht:' option; do case "$option" in h) usage;; t) if ! [ -x "$(command -v "$OPTARG")" ]; then echo "$me: $OPTARG is not executable" >&2 exit 2 fi # echo "$OPTARG" target="$OPTARG" ;; g) fgroot="$OPTARG" # echo "$OPTARG" ;; :) printf "%s: missing argument for -%s\n" "$me" "$OPTARG" >&2 usage ;; \?) printf "%s: illegal option: -%s\n" "$me" "$OPTARG" >&2 usage ;; esac done shift $((OPTIND - 1)) scpath="$fgroot/stackcollapse-perf.pl" fgpath="$fgroot/flamegraph.pl" # echo "$scpath" "$fgpath" if ! command -v "$scpath" >/dev/null; then printf "%s: could not find stackcollapse-perf.pl\n" "$me" >&2 exit 3 fi if ! command -v "$fgpath" >/dev/null; then printf "%s: could not find flamegraph.pl\n" "$me" >&2 exit 4 fi filename=$(date -u +"%Y-%m-%dT%H:%M:%S%Z") perf record -g --call-graph=dwarf -F 99 "$target" perf script > "$filename".perf $scpath "$filename".perf > "$filename".collapsed $fgpath "$filename".collapsed > "$filename".svg Options should arguably be optional; but I refrained from removing the -t option in case you need it to stay for reasons of backwards compatibility. If stackcollapse-perf.pl accepts input from stdin, you could avoid creating the .collapsed file. These temporary files in the current directory which can get overwritten at any time are still a bit of a wart.
{ "domain": "codereview.stackexchange", "id": 43405, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "validation, sh", "url": null }
python, python-3.x, programming-challenge Title: Sum square difference Question: Problem description: The sum of the squares of the first ten natural numbers is, 1² + 2² + … + 10² = 385 The square of the sum of the first ten natural numbers is, (1 + 2 + … + 10)² = 55² = 3025 Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is: 3025 – 385 = 2640. Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum. Square difference: l = sum of the squares of the first n natural numbers k = sum of n naturals numbers m = differences between l and k My Solution This is my solution for problem 6 of Project Euler using Python: def square_difference(n): l = (n * (n + 1) * (2 * n + 1)) / 6 k = (n * (n + 1)) / 2 k = k ** 2 m = abs(l - k) return m How could my code be improved?
{ "domain": "codereview.stackexchange", "id": 43406, "lm_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", "url": null }
python, python-3.x, programming-challenge How could my code be improved? Answer: The other answer observes that some one character variable names can be confused. This can partly be avoided by choosing a better font in your editor (although O will always be problematic). Even then, you want to use more descriptive variable names. You went to the trouble to tell us about l, k, and m. Why not just make those names a bit more descriptive? This might also help you notice that k changes between your comments about k and m. I don't see much point in assigning something to m in order to return m in the next line. Let's skip that step and just return. As noted in comments, the square of the sum is always greater than the sum of the squares. So we can write the difference that way and leave out the abs. Empty lines can be useful for creating blocks of thought, but there's not that much going on in your function, so I'd say we don't really need those lines. To be really pedantic, this is not your solution to problem #6. This is your function used to find the solution to problem #6, but the actual solution would be evaluating this function at 100. I added a docstring to the function, so that you can call help(square_difference) in other code. I've removed some unnecessary parentheses. This gives us: def square_difference(n): ''' Return the difference between the square of the sum of the first n natural numbers and the sum of the squares of the first n natural numbers. ''' sum_of_squares = n * (n + 1) * (2 * n + 1) / 6 sum_of_terms = n * (n + 1) / 2 return sum_of_terms**2 - sum_of_squares print(square_difference(100)) If your function was really causing a bottleneck (it isn't), you could get a bit more performance out of this by using some algebra to find that the result is n*(n+1)*(3*n+2)*(n-1)/12. But if you did that, you'd need a good comment explaining what is happening. As things are, we don't really need any comments.
{ "domain": "codereview.stackexchange", "id": 43406, "lm_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", "url": null }
python Title: How can I make my code, that defines variables based on a list that is returned by a function, look nicer? Question: Is there a way to do in a nicer way the following thing in Python ? def proving(): a = 4*5 b = 1*9 results = [a,b] return results results = proving() a = results[0] b = results[1] I would like to make a function that makes some calculations and then obtain the values of the variables of interest from this function. Yes, I could simply write a = 4*5 and b = 1*9 but I like the idea to wrap everything into a function. On the other hand, I think that defining the variables a and b as a = results[0] and b = results[1] is a little bit ugly (expecially if the number of variables defined in this way increases...). Answer: You could return everything as a tuple. Using a concept called unpacking, you can then just extract the values you need. def proving(): a = 4*5 b = 1*9 return a, b a, b = proving() You could go one step further and eliminate the variables inside the function: def proving(): return 4*5, 1*9 a, b = proving() BTW, this works outside functions, and with lists too: a, b = 4*5, 1*9 c, d = [3*6, 2*7]
{ "domain": "codereview.stackexchange", "id": 43407, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python", "url": null }
bash, web-scraping, sh, curl, pdf Title: Shell script to download Project Euler problems and combine to PDF Question: This is a script I created that downloads Project Euler webpages and combines them to PDF. The script also downloads animated files. #!/bin/sh for i in $(seq -f "%03g" $1 $2); do URL="https://projecteuler.net/problem=$i" # chromium print to PDF, wait for rendering https://stackoverflow.com/a/49789027 chromium-browser --headless --disable-gpu --run-all-compositor-stages-before-draw --virtual-time-budget=10000 --print-to-pdf-no-header --print-to-pdf=$i.pdf $URL # Distill PDFs to workaround Ghostscript skipped character problem https://stackoverflow.com/questions/12806911 gs -dBATCH -dNOPAUSE -sDEVICE=pdfwrite -o ${i}_gs.pdf $i.pdf # download extra txt and GIF files if available, printing links to shell curl -s $URL | pup 'a attr{href}' | grep '\.txt$' | tee /dev/tty | sed 's/^/https:\/\/projecteuler.net\//' | xargs -r -n1 curl -O curl -s $URL | pup 'img attr{src}' | grep '\.gif$' | tee /dev/tty | sed 's/^/https:\/\/projecteuler.net\//' | xargs -r -n1 curl -O done # remove non-animated GIFs for i in *.gif; do [ $(identify "$i" | wc -l) -le 1 ] && rm -v "$i" done # combine all PDFs using gs gs -dBATCH -dNOPAUSE -sDEVICE=pdfwrite -dPDFSETTINGS=/ebook -sOutputFile=problems.pdf *_gs.pdf # create final zip zip problems.zip problems.pdf *.txt *.gif Is there a way to get rid of the two nearly duplicate lines which only differ in pup and grep? Is it possible to write the curl lines so that an image is saved only if ImageMagick identify indentifies as gif, instead of cleaning up afterwards? Is this cleaner? I'm not very experienced writing shell scripts so let me know if there are any style issues or better ways to use sed, grep, xargs, etc. Answer: Here's a refactoring with various fixes.
{ "domain": "codereview.stackexchange", "id": 43408, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "bash, web-scraping, sh, curl, pdf", "url": null }
bash, web-scraping, sh, curl, pdf Answer: Here's a refactoring with various fixes. Generally quote shell variables. Don't read lines with for. I switched the URL variable to lower case, in accordance with recommended convention. This uses a temporary file for the curl output, and a trap to clean it up. The logic to process this file was refactored to a function pupcurl. I switched the regex separator in the sed script to % to reduce the need for backslashes. Use ./ prefix for glob expressions so as to avoid having file names which start with dashes be interpreted as (presumably invalid) options. $i in the URL is not defined outside the loop. Move the assignment inside the loop. For the record, there is no way to run identify on an image without downloading it first. #!/bin/sh tmp=$(mktemp -t pdfstitcher.XXXXXXXX) || exit trap 'rm -f "$tmp"' EXIT pupcurl () { pup "$1" | grep "$2" | tee /dev/tty | sed 's%^%https://projecteuler.net/%' | xargs -r -n1 curl -O } seq -f "%03g" "$1" "$2" | while read -r i; do url="https://projecteuler.net/problem=$i" chromium-browser --headless --disable-gpu \ --run-all-compositor-stages-before-draw \ --virtual-time-budget=10000 \ --print-to-pdf-no-header \ --print-to-pdf="$i.pdf" "$url" gs -dBATCH -dNOPAUSE -sDEVICE=pdfwrite \ -o "${i}_gs.pdf" "$i.pdf" curl -s "$url" >"$tmp" pupcurl 'a attr{href}' '\.txt$' <"$tmp" pupcurl 'img attr{src}' '\.gif$' <"$tmp" done for i in ./*.gif; do [ $(identify "$i" | wc -l) -le 1 ] && rm -v "$i" done gs -dBATCH -dNOPAUSE -sDEVICE=pdfwrite \ -dPDFSETTINGS=/ebook \ -sOutputFile=problems.pdf ./*_gs.pdf zip problems.zip problems.pdf ./*.txt ./*.gif
{ "domain": "codereview.stackexchange", "id": 43408, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "bash, web-scraping, sh, curl, pdf", "url": null }
bash, web-scraping, sh, curl, pdf Depending on what you want to accomplish, perhaps all of this should run in a temporary directory which you remove when you're done (mktemp -d). I'm not entirely happy with the identify call. I assume the code looks for GIF files where identify outputs more than one line, and removes the rest. This looks suspiciously like a useless use of wc but I'm drawing a blank when it comes to actually improving it. Perhaps it could be broken out into a separate function with some comments to explain it, or maybe use Awk to postprocess the result: keep_only_animated_gifs () { for i in ./*.gif; do identify "$i" | awk 'NR == 2 { exit 1 }' || rm -v "$i" done } If you are willing to change from a sh script to a Bash script, the temporary file (and thus also the trap) could be avoided with something like curl -s "$url" | tee >(pupcurl 'a attr{href}' '\.txt$') | pupcurl 'img attr{src}' '\.gif$'
{ "domain": "codereview.stackexchange", "id": 43408, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "bash, web-scraping, sh, curl, pdf", "url": null }
bash, web-scraping, sh, curl, pdf The >(...) is a process substitution which is a Bash extension. Perhaps see also Difference between sh and bash The tee /dev/tty is slightly dubious but I left it in. If the intent is to display the output to the user as a progress message, perhaps tee /dev/stderr instead, though then ideally the output should have a bit of an explanation, too. (A common convention is to include the generating script's name in all diagnostic messages, so you can see which script is emitting it when you have scripts calling scripts calling scripts etc.) Based on feedback in the comments, I removed the Bashism to trap ... ERR too (good catch! And insidious to run Shellckeck when clearly I didn't :-) which means this could leave temporary files behind if curl fails to connect, for example. Maybe add set -e at the top to cover that case, too; but I haven't combed over the script to check whether it's otherwise set -e -safe. (In particular, could gs fail spuriously?) Finally, probably try http://shellcheck.net/ before asking for human assistance. It can suggest several of the changes here automatically.
{ "domain": "codereview.stackexchange", "id": 43408, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "bash, web-scraping, sh, curl, pdf", "url": null }
python, console, validation Title: UPDATE on Newspaper Bill Calculator CLI with Python (2 of 3, CLI) Question: Code is posted after explanation. Due to the size of the project, this is being posted in three separate posts. This also ensures each post is more focused. Post 1 of 3, Core: UPDATE 1 on Newspaper Bill Calculator CLI with Python (1 of 3, Core) Post 3 of 3, Database: UPDATE 1 on Newspaper Bill Calculator CLI with Python (3 of 3, Database) This is a follow-up to an earlier version of the same project. The feedback from the last round is tracked in an issue. What is this? This application helps you calculate monthly newspaper bills. The goal is to generate a message that I can paste into WhatsApp and send to my newspaper vendor. The end result here is a CLI tool that will be later used as a back-end to build GUIs (hence learn about: C#, HTML/CSS/JS, Flutter). In its current form, everything will be "compiled" by PyInstaller into one-file stand-alone executables for the end-user using GitHub Actions. The other important goal was to be a testbed for learning a bunch of new tools: more Python libraries, SQL connectors, GitHub Actions (CI/CD, if I understand correctly), unit tests, CLI libraries, type-hinting, regex. I had earlier built this on a different platform, so I now have a solid idea of how this application is used. Key concepts Each newspaper has a certain cost per day of the week Each newspaper may or may not be delivered on a given day Each newspaper has a name, and a number called a key You may register any dates when you didn't receive a paper in advance using the addudl command Once you calculate, the results are displayed and logged. What files exist? (ignoring conventional ones like README and requirements.txt) File Purpose/Description Review
{ "domain": "codereview.stackexchange", "id": 43409, "lm_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, console, validation", "url": null }
python, console, validation File Purpose/Description Review npbc_core.py Provide the core functionality: the calculation, parsing and validation of user input, interaction with the DB etc. Later on, some functionality from this will be extracted to create server-side code that can service more users, but I have to learn a lot more before getting there. Please review this. npbc_regex.py Contains all the regex statements used to validate and parse user input. Please review this. npbc_exceptions.py Defines classes for all the custom exceptions used by the core and the CLI. Please review this. npbc_cli.py Import functionality from npbc_core.py and wrap a CLI layer on it using argparse. Also provide some additional validation. Please review this. npbc_updater.py Provide a utility to update the application on the user's end. Don't bother reviewing this (code not included). test_core.py Test the functionality of the core file (pytest), except anything to do with the database. Please review this. test_db.py Test the functionality of the core file (pytest), for anything to do with the database. Please review this. test_regex.py Test the functionality of the regex statements. Please review this. data/schema.sql Database schema. In my local environment, the data folder also has a test database file (but I don't want to upload this online). Please review this if you can (not high priority). data/test.sql SQL statements to generate test data for test_db.py. Please review this if you can (not high priority). npbc_cli.py """ wraps a CLI around the core functionality (using argparse) - inherits functionality from `npbc_core.py` - inherits regex from `npbc_regex.py`, used for validation - inherits exceptions from `npbc_exceptions.py`, used for error handling - performs some additional validation - formats data retrieved from the core for the user """
{ "domain": "codereview.stackexchange", "id": 43409, "lm_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, console, validation", "url": null }
python, console, validation import sqlite3 from argparse import ArgumentParser from argparse import Namespace as ArgNamespace from datetime import datetime from sys import argv from typing import Generator from colorama import Fore, Style import npbc_core import npbc_exceptions from npbc_regex import DELIVERY_MATCH_REGEX def define_and_read_args(arguments: list[str]) -> ArgNamespace: """configure parsers - define the main parser for the application executable - define subparsers (one for each functionality) - parse the arguments""" # main parser for all commands main_parser = ArgumentParser( prog="npbc", description="Calculates your monthly newspaper bill." ) functions = main_parser.add_subparsers(required=True) # calculate subparser calculate_parser = functions.add_parser( 'calculate', help="Calculate the bill for one month. Previous month will be used if month or year flags are not set." ) calculate_parser.set_defaults(func=calculate) calculate_parser.add_argument('-m', '--month', type=int, help="Month to calculate bill for. Must be between 1 and 12.") calculate_parser.add_argument('-y', '--year', type=int, help="Year to calculate bill for. Must be greater than 0.") calculate_parser.add_argument('-l', '--nolog', help="Don't log the result of the calculation.", action='store_true') # add undelivered string subparser addudl_parser = functions.add_parser( 'addudl', help="Store a date when paper(s) were not delivered. Current month will be used if month or year flags are not set. Either paper ID must be provided, or the all flag must be set." )
{ "domain": "codereview.stackexchange", "id": 43409, "lm_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, console, validation", "url": null }
python, console, validation addudl_parser.set_defaults(func=addudl) addudl_parser.add_argument('-m', '--month', type=int, help="Month to register undelivered incident(s) for. Must be between 1 and 12.") addudl_parser.add_argument('-y', '--year', type=int, help="Year to register undelivered incident(s) for. Must be greater than 0.") addudl_parser.add_argument('-p', '--paperid', type=str, help="ID of paper to register undelivered incident(s) for.") addudl_parser.add_argument('-a', '--all', help="Register undelivered incidents for all papers.", action='store_true') addudl_parser.add_argument('-s', '--strings', type=str, help="Dates when you did not receive any papers.", required=True, nargs='+') # delete undelivered string subparser deludl_parser = functions.add_parser( 'deludl', help="Delete a stored date when paper(s) were not delivered. If no parameters are provided, the function will not default; it will throw an error instead." ) deludl_parser.set_defaults(func=deludl) deludl_parser.add_argument('-p', '--paperid', type=str, help="ID of paper to unregister undelivered incident(s) for.") deludl_parser.add_argument('-i', '--stringid', type=str, help="String ID of paper to unregister undelivered incident(s) for.") deludl_parser.add_argument('-m', '--month', type=int, help="Month to unregister undelivered incident(s) for. Must be between 1 and 12.") deludl_parser.add_argument('-y', '--year', type=int, help="Year to unregister undelivered incident(s) for. Must be greater than 0.") deludl_parser.add_argument('-s', '--string', type=str, help="Dates when you did not receive any papers.") # get undelivered string subparser getudl_parser = functions.add_parser( 'getudl', help="Get a list of all stored date strings when paper(s) were not delivered. All parameters are optional and act as filters." )
{ "domain": "codereview.stackexchange", "id": 43409, "lm_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, console, validation", "url": null }
python, console, validation getudl_parser.set_defaults(func=getudl) getudl_parser.add_argument('-p', '--paperid', type=str, help="ID for paper.") getudl_parser.add_argument('-i', '--stringid', type=str, help="String ID of paper to unregister undelivered incident(s) for.") getudl_parser.add_argument('-m', '--month', type=int, help="Month. Must be between 1 and 12.") getudl_parser.add_argument('-y', '--year', type=int, help="Year. Must be greater than 0.") getudl_parser.add_argument('-s', '--string', type=str, help="Dates when you did not receive any papers.") # edit paper subparser editpaper_parser = functions.add_parser( 'editpaper', help="Edit a newspaper's name, days delivered, and/or price." ) editpaper_parser.set_defaults(func=editpaper) editpaper_parser.add_argument('-n', '--name', type=str, help="Name for paper to be edited.") editpaper_parser.add_argument('-d', '--delivered', type=str, help="Number of days the paper to be edited is delivered. All seven weekdays are required. A 'Y' means it is delivered, and an 'N' means it isn't. No separator required.") editpaper_parser.add_argument('-c', '--costs', type=str, help="Daywise prices of paper to be edited. 0s are ignored.", nargs='*') editpaper_parser.add_argument('-p', '--paperid', type=str, help="ID for paper to be edited.", required=True) # add paper subparser addpaper_parser = functions.add_parser( 'addpaper', help="Add a new newspaper to the list of newspapers." )
{ "domain": "codereview.stackexchange", "id": 43409, "lm_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, console, validation", "url": null }
python, console, validation addpaper_parser.set_defaults(func=addpaper) addpaper_parser.add_argument('-n', '--name', type=str, help="Name for paper to be added.", required=True) addpaper_parser.add_argument('-d', '--delivered', type=str, help="Number of days the paper to be added is delivered. All seven weekdays are required. A 'Y' means it is delivered, and an 'N' means it isn't. No separator required.", required=True) addpaper_parser.add_argument('-c', '--costs', type=str, help="Daywise prices of paper to be added. 0s are ignored.", required=True, nargs='+') # delete paper subparser delpaper_parser = functions.add_parser( 'delpaper', help="Delete a newspaper from the list of newspapers." ) delpaper_parser.set_defaults(func=delpaper) delpaper_parser.add_argument('-p', '--paperid', type=str, help="ID for paper to be deleted.", required=True) # get paper subparser getpapers_parser = functions.add_parser( 'getpapers', help="Get all newspapers." ) getpapers_parser.set_defaults(func=getpapers) getpapers_parser.add_argument('-n', '--names', help="Get the names of the newspapers.", action='store_true') getpapers_parser.add_argument('-d', '--delivered', help="Get the days the newspapers are delivered. All seven weekdays are required. A 'Y' means it is delivered, and an 'N' means it isn't.", action='store_true') getpapers_parser.add_argument('-c', '--cost', help="Get the daywise prices of the newspapers. Values must be separated by semicolons.", action='store_true') # get undelivered logs subparser getlogs_parser = functions.add_parser( 'getlogs', help="Get the log of all undelivered dates." )
{ "domain": "codereview.stackexchange", "id": 43409, "lm_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, console, validation", "url": null }
python, console, validation getlogs_parser.set_defaults(func=getlogs) getlogs_parser.add_argument('-i', '--logid', type=int, help="ID for log to be retrieved.") getlogs_parser.add_argument('-p', '--paperid', type=str, help="ID for paper.") getlogs_parser.add_argument('-m', '--month', type=int, help="Month. Must be between 1 and 12.") getlogs_parser.add_argument('-y', '--year', type=int, help="Year. Must be greater than 0.") getlogs_parser.add_argument('-t' , '--timestamp', type=str, help="Timestamp. Must be in the format dd/mm/yyyy hh:mm:ss AM/PM.") # update application subparser update_parser = functions.add_parser( 'update', help="Update the application." ) update_parser.set_defaults(func=update) return main_parser.parse_args(arguments) def status_print(status: bool, message: str) -> None: """ print out a coloured status message using Colorama - if the status is True, print in green (success) - if the status is False, print in red (failure) """ if status: print(f"{Fore.GREEN}", end="") else: print(f"{Fore.RED}", end="") print(f"{Style.BRIGHT}{message}{Style.RESET_ALL}\n") def calculate(parsed_arguments: ArgNamespace) -> None: """calculate the cost for a given month and year - default to the previous month if no month and no year is given - default to the current month if no month is given and year is given - default to the current year if no year is given and month is given""" ## deal with month and year # if either of them are given if parsed_arguments.month or parsed_arguments.year: # validate them try: npbc_core.validate_month_and_year(parsed_arguments.month, parsed_arguments.year) except npbc_exceptions.InvalidMonthYear: status_print(False, "Invalid month and/or year.") return
{ "domain": "codereview.stackexchange", "id": 43409, "lm_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, console, validation", "url": null }
python, console, validation # for each, if it is not given, set it to the current month and/or year month = parsed_arguments.month or datetime.now().month year = parsed_arguments.year or datetime.now().year # if neither are given else: # set them to the previous month and year previous_month = npbc_core.get_previous_month() month = previous_month.month year = previous_month.year # prepare a dictionary for undelivered strings undelivered_strings = { int(paper_id): [] for paper_id, _, _, _, _ in npbc_core.get_papers() } # get the undelivered strings from the database try: raw_undelivered_strings = npbc_core.get_undelivered_strings(month=month, year=year) # add them to the dictionary for _, paper_id, _, _, string in raw_undelivered_strings: undelivered_strings[paper_id].append(string) # ignore if none exist except npbc_exceptions.StringNotExists: pass # if there is a database error, print an error message except sqlite3.DatabaseError as e: status_print(False, f"Database error: {e}\nPlease report this to the developer.") return try: # calculate the cost for each paper costs, total, undelivered_dates = npbc_core.calculate_cost_of_all_papers( undelivered_strings, month, year ) # if there is a database error, print an error message except sqlite3.DatabaseError as e: status_print(False, f"Database error: {e}\nPlease report this to the developer.") return # format the results formatted = '\n'.join(npbc_core.format_output(costs, total, month, year)) # unless the user specifies so, log the results to the database if not parsed_arguments.nolog: try: npbc_core.save_results(costs, undelivered_dates, month, year)
{ "domain": "codereview.stackexchange", "id": 43409, "lm_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, console, validation", "url": null }
python, console, validation # if there is a database error, print an error message except sqlite3.DatabaseError as e: status_print(False, f"Database error: {e}\nPlease report this to the developer.") return formatted += '\n\nLog saved to file.' # print the results status_print(True, "Success!") print(f"SUMMARY:\n\n{formatted}") def addudl(parsed_arguments: ArgNamespace) -> None: """add undelivered strings to the database - default to the current month if no month and/or no year is given""" # validate the month and year try: npbc_core.validate_month_and_year(parsed_arguments.month, parsed_arguments.year) # if they are invalid, print an error message except npbc_exceptions.InvalidMonthYear: status_print(False, "Invalid month and/or year.") return ## deal with month and year # for any that are not given, set them to the current month and year month = parsed_arguments.month or datetime.now().month year = parsed_arguments.year or datetime.now().year # if the user either specifies a specific paper or specifies all papers if parsed_arguments.paperid or parsed_arguments.all: # attempt to add the strings to the database try: npbc_core.add_undelivered_string(month, year, parsed_arguments.paperid, *parsed_arguments.strings) # if the paper doesn't exist, print an error message except npbc_exceptions.PaperNotExists: status_print(False, f"Paper with ID {parsed_arguments.paperid} does not exist.") return
{ "domain": "codereview.stackexchange", "id": 43409, "lm_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, console, validation", "url": null }
python, console, validation # if the string was invalid, print an error message except npbc_exceptions.InvalidUndeliveredString: status_print(False, "Invalid undelivered string(s).") return # if there is a database error, print an error message except sqlite3.DatabaseError as e: status_print(False, f"Database error: {e}\nPlease report this to the developer.") return # if no paper is specified, print an error message else: status_print(False, "No paper(s) specified.") return status_print(True, "Success!") def deludl(parsed_arguments: ArgNamespace) -> None: """delete undelivered strings from the database""" # validate the month and year try: npbc_core.validate_month_and_year(parsed_arguments.month, parsed_arguments.year) # if they are invalid, print an error message except npbc_exceptions.InvalidMonthYear: status_print(False, "Invalid month and/or year.") return # attempt to delete the strings from the database try: npbc_core.delete_undelivered_string( month=parsed_arguments.month, year=parsed_arguments.year, paper_id=parsed_arguments.paperid, string=parsed_arguments.string, string_id=parsed_arguments.stringid ) # if no parameters are given, print an error message except npbc_exceptions.NoParameters: status_print(False, "No parameters specified.") return # if the string doesn't exist, print an error message except npbc_exceptions.StringNotExists: status_print(False, "String does not exist.") return # if there is a database error, print an error message except sqlite3.DatabaseError as e: status_print(False, f"Database error: {e}\nPlease report this to the developer.") return status_print(True, "Success!")
{ "domain": "codereview.stackexchange", "id": 43409, "lm_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, console, validation", "url": null }
python, console, validation def getudl(parsed_arguments: ArgNamespace) -> None: """get undelivered strings from the database filter by whichever parameter the user provides. they as many as they want. available parameters: month, year, paper_id, string_id, string""" # validate the month and year try: npbc_core.validate_month_and_year(parsed_arguments.month, parsed_arguments.year) # if they are invalid, print an error message except npbc_exceptions.InvalidMonthYear: status_print(False, "Invalid month and/or year.") return # attempt to get the strings from the database try: undelivered_strings = npbc_core.get_undelivered_strings( month=parsed_arguments.month, year=parsed_arguments.year, paper_id=parsed_arguments.paperid, string_id=parsed_arguments.stringid, string=parsed_arguments.string ) # if the string doesn't exist, print an error message except npbc_exceptions.StringNotExists: status_print(False, "No strings found for the given parameters.") return status_print(True, "Success!") ## format the results # print the column headers print(f"{Fore.YELLOW}string_id{Style.RESET_ALL} | {Fore.YELLOW}paper_id{Style.RESET_ALL} | {Fore.YELLOW}year{Style.RESET_ALL} | {Fore.YELLOW}month{Style.RESET_ALL} | {Fore.YELLOW}string{Style.RESET_ALL}") # print the strings for items in undelivered_strings: print(', '.join([str(item) for item in items])) def extract_delivery_from_user_input(input_delivery: str) -> list[bool]: """convert the /[YN]{7}/ user input to a Boolean list""" if not DELIVERY_MATCH_REGEX.match(input_delivery): raise npbc_exceptions.InvalidInput("Invalid delivery days.") return list(map(lambda x: x == 'Y', input_delivery))
{ "domain": "codereview.stackexchange", "id": 43409, "lm_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, console, validation", "url": null }
python, console, validation return list(map(lambda x: x == 'Y', input_delivery)) def extract_costs_from_user_input(paper_id: int | None, delivery_data: list[bool] | None, *input_costs: float) -> Generator[float, None, None]: """convert the user input to a float list""" # filter the data to remove zeros suspected_data = [ cost for cost in input_costs if cost != 0 ] # reverse it so that we can pop to get the first element first (FILO to FIFO) suspected_data.reverse() # if the delivery data is given, use it if delivery_data: # if the number of days the paper is delivered is not equal to the number of costs, raise an error if (len(suspected_data) != delivery_data.count(True)): raise npbc_exceptions.InvalidInput("Number of costs don't match number of days delivered.") # for each day, yield the cost if it is delivered or 0 if it is not for day in delivery_data: yield suspected_data.pop() if day else 0 # if the delivery data is not given, but the paper ID is given, get the delivery data from the database elif paper_id: # get the delivery data from the database, and filter for the paper ID try: raw_data = [paper for paper in npbc_core.get_papers() if paper[0] == int(paper_id)] # if there is a database error, print an error message except sqlite3.DatabaseError as e: status_print(False, f"Database error: {e}\nPlease report this to the developer.") return raw_data.sort(key=lambda paper: paper[2]) # extract the data from the database delivered = [ bool(delivered) for _, _, _, delivered, _ in raw_data ]
{ "domain": "codereview.stackexchange", "id": 43409, "lm_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, console, validation", "url": null }
python, console, validation # if the number of days the paper is delivered is not equal to the number of costs, raise an error if len(suspected_data) != delivered.count(True): raise npbc_exceptions.InvalidInput("Number of costs don't match number of days delivered.") # for each day, yield the cost if it is delivered or 0 if it is not for day in delivered: yield suspected_data.pop() if day else 0 else: raise npbc_exceptions.InvalidInput("Neither delivery data nor paper ID given.") def editpaper(parsed_arguments: ArgNamespace) -> None: """edit a paper's information""" try: # attempt to get the delivery data. if it's not given, set it to None delivery_data = extract_delivery_from_user_input(parsed_arguments.delivered) if parsed_arguments.delivered else None # attempt to edit the paper. if costs are given, use them, else use None npbc_core.edit_existing_paper( paper_id=parsed_arguments.paperid, name=parsed_arguments.name, days_delivered=delivery_data, days_cost=list(extract_costs_from_user_input(parsed_arguments.paperid, delivery_data, *parsed_arguments.costs)) if parsed_arguments.costs else None ) # if the paper doesn't exist, print an error message except npbc_exceptions.PaperNotExists: status_print(False, "Paper does not exist.") return # if some input is invalid, print an error message except npbc_exceptions.InvalidInput as e: status_print(False, f"Invalid input: {e}") return # if there is a database error, print an error message except sqlite3.DatabaseError as e: status_print(False, f"Database error: {e}\nPlease report this to the developer.") return status_print(True, "Success!") def addpaper(parsed_arguments: ArgNamespace) -> None: """add a new paper to the database"""
{ "domain": "codereview.stackexchange", "id": 43409, "lm_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, console, validation", "url": null }
python, console, validation def addpaper(parsed_arguments: ArgNamespace) -> None: """add a new paper to the database""" try: # attempt to get the delivery data delivery_data = extract_delivery_from_user_input(parsed_arguments.delivered) # attempt to add the paper. npbc_core.add_new_paper( name=parsed_arguments.name, days_delivered=delivery_data, days_cost=list(extract_costs_from_user_input(None, delivery_data, *parsed_arguments.costs)) ) # if the paper already exists, print an error message except npbc_exceptions.PaperAlreadyExists: status_print(False, "Paper already exists.") return # if some input is invalid, print an error message except npbc_exceptions.InvalidInput as e: status_print(False, f"Invalid input: {e}") return # if there is a database error, print an error message except sqlite3.DatabaseError as e: status_print(False, f"Database error: {e}\nPlease report this to the developer.") return status_print(True, "Success!") def delpaper(parsed_arguments: ArgNamespace) -> None: """delete a paper from the database""" # attempt to delete the paper try: npbc_core.delete_existing_paper(parsed_arguments.paperid) # if the paper doesn't exist, print an error message except npbc_exceptions.PaperNotExists: status_print(False, "Paper does not exist.") return # if there is a database error, print an error message except sqlite3.DatabaseError as e: status_print(False, f"Database error: {e}\nPlease report this to the developer.") return status_print(True, "Success!")
{ "domain": "codereview.stackexchange", "id": 43409, "lm_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, console, validation", "url": null }
python, console, validation status_print(True, "Success!") def getpapers(parsed_arguments: ArgNamespace) -> None: """get a list of all papers in the database - filter by whichever parameter the user provides. they may use as many as they want (but keys are always printed) - available parameters: name, days, costs - the output is provided as a formatted table, printed to the standard output""" # get the papers from the database try: raw_data = npbc_core.get_papers() # if there is a database error, print an error message except sqlite3.DatabaseError as e: status_print(False, f"Database error: {e}\nPlease report this to the developer.") return # initialize lists for column headers and paper IDs headers = ['paper_id'] ids = [] # extract paperr IDs ids = list(set(paper[0] for paper in raw_data)) ids.sort() # initialize lists for the data, based on the number of paper IDs delivery = [None for _ in ids] costs = [None for _ in ids] names = [None for _ in ids] # if the user wants the name, add it to the headers and the data to the list if parsed_arguments.names: headers.append('name') names = list(set( (paper_id, name) for paper_id, name, _, _, _ in raw_data )) # sort the names by paper ID and extract the names only names.sort(key=lambda item: item[0]) names = [name for _, name in names] # if the user wants the delivery data or the costs, get the data about days if parsed_arguments.delivered or parsed_arguments.cost: # initialize a dictionary for the days of each paper days = { paper_id: {} for paper_id in ids }
{ "domain": "codereview.stackexchange", "id": 43409, "lm_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, console, validation", "url": null }
python, console, validation # for each paper, add the days to the dictionary for paper_id, _, day_id, _, _ in raw_data: days[paper_id][day_id] = {} # for each paper, add the costs and delivery data to the dictionary for paper_id, _, day_id, day_delivery, day_cost in raw_data: days[paper_id][day_id]['delivery'] = day_delivery days[paper_id][day_id]['cost'] = day_cost # if the user wants the delivery data, add it to the headers and the data to the list if parsed_arguments.delivered: headers.append('days') # convert the data to the /[YN]{7}/ format the user is used to delivery = [ ''.join([ 'Y' if days[paper_id][day_id]['delivery'] else 'N' for day_id, _ in enumerate(npbc_core.WEEKDAY_NAMES) ]) for paper_id in ids ] # if the user wants the costs, add it to the headers and the data to the list if parsed_arguments.cost: headers.append('costs') # convert the data to the /x(;x){0,6}/ where x is a floating point number format the user is used to costs = [ ';'.join([ str(days[paper_id][day_id]['cost']) for day_id, _ in enumerate(npbc_core.WEEKDAY_NAMES) if days[paper_id][day_id]['cost'] != 0 ]) for paper_id in ids ] # print the headers print(' | '.join([ f"{Fore.YELLOW}{header}{Style.RESET_ALL}" for header in headers ])) # print the data for paper_id, name, delivered, cost in zip(ids, names, delivery, costs): print(paper_id, end='') if parsed_arguments.names: print(f", {name}", end='') if parsed_arguments.delivered: print(f", {delivered}", end='')
{ "domain": "codereview.stackexchange", "id": 43409, "lm_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, console, validation", "url": null }
python, console, validation if parsed_arguments.delivered: print(f", {delivered}", end='') if parsed_arguments.cost: print(f", {cost}", end='') print() def getlogs(parsed_arguments: ArgNamespace) -> None: """get a list of all logs in the database - filter by whichever parameter the user provides. they may use as many as they want (but log IDs are always printed) - available parameters: log_id, paper_id, month, year, timestamp - will return both date logs and cost logs""" # attempt to get the logs from the database try: data = npbc_core.get_logged_data( query_log_id = parsed_arguments.logid, query_paper_id=parsed_arguments.paperid, query_month=parsed_arguments.month, query_year=parsed_arguments.year, query_timestamp= datetime.strptime(parsed_arguments.timestamp, r'%d/%m/%Y %I:%M:%S %p') if parsed_arguments.timestamp else None ) # if there is a database error, print an error message except sqlite3.DatabaseError as e: status_print(False, f"Database error. Please report this to the developer.\n{e}") return # if there is a date format error, print an error message except ValueError: status_print(False, "Invalid date format. Please use the following format: dd/mm/yyyy hh:mm:ss AM/PM") return # print column headers print(' | '.join( f"{Fore.YELLOW}{header}{Style.RESET_ALL}" for header in ['log_id', 'paper_id', 'month', 'year', 'timestamp', 'date/cost'] )) # print the data for row in data: print(', '.join(str(item) for item in row)) def update(parsed_arguments: ArgNamespace) -> None: """update the application - under normal operation, this function should never run - if the update CLI argument is provided, this script will never run and the updater will be run instead""" status_print(False, "Update failed.")
{ "domain": "codereview.stackexchange", "id": 43409, "lm_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, console, validation", "url": null }
python, console, validation status_print(False, "Update failed.") def main(arguments: list[str]) -> None: """main function - initialize the database - parses the command line arguments - calls the appropriate function based on the arguments""" # attempt to initialize the database try: npbc_core.setup_and_connect_DB() # if there is a database error, print an error message except sqlite3.DatabaseError as e: status_print(False, f"Database error: {e}\nPlease report this to the developer.") return # parse the command line arguments parsed_namespace = define_and_read_args(arguments) # execute the appropriate function parsed_namespace.func(parsed_namespace) if __name__ == "__main__": main(argv[1:]) Relevant section of test_db.py from pathlib import Path import npbc_cli ACTIVE_DIRECTORY = Path("data") DATABASE_PATH = ACTIVE_DIRECTORY / "npbc.db" def test_db_creation(): DATABASE_PATH.unlink(missing_ok=True) assert not DATABASE_PATH.exists() try: npbc_cli.main([]) except SystemExit: pass assert DATABASE_PATH.exists() If you need it, here is a link to the GitHub repo for this project. It's at the same commit as the code above, and I won't edit this so that any discussion is consistent. https://github.com/eccentricOrange/npbc/tree/041a949bbba018531ec590a2193523f1530659aa Answer: This print: print(f"{Fore.GREEN}", end="") doesn't need the f-string; you can just print Fore.GREEN directly. However, that if can be refactored so that it uses a colour variable: if status: colour = Fore.GREEN else: colour = Fore.RED print(f"{colour}{Style.BRIGHT}{message}{Style.RESET_ALL}\n") These two return tuples: for paper_id, _, _, _, _ in npbc_core.get_papers() for _, paper_id, _, _, string in raw_undelivered_strings:
{ "domain": "codereview.stackexchange", "id": 43409, "lm_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, console, validation", "url": null }
python, console, validation for _, paper_id, _, _, string in raw_undelivered_strings: are a little cumbersome. Instead consider simple named tuples so that you can access members instead of positions. When you call status_print, it's probably best if you pass status by named argument. status is a little ambiguous and would be clearer as success. Swallowing SystemExit seems like a really, really bad idea. Why is that there? If you just want to enforce that last assert regardless of what happens, then: try: npbc_cli.main([]) finally: assert DATABASE_PATH.exists()
{ "domain": "codereview.stackexchange", "id": 43409, "lm_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, console, validation", "url": null }
python, python-3.x, programming-challenge, sieve-of-eratosthenes Title: the 10001st prime number Question: Problem description: By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. What is the 10001st prime number? Prime number: A prime number is a whole number greater than 1 whose only factors are 1 and itself. A factor is a whole number that can be divided evenly into another number. Example: The first 25 prime numbers (all the prime numbers less than 100) are: 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97 The best solution is with Sieve Of Eratosthenes Sieve Of Eratosthenes: In mathematics, the sieve of Eratosthenes is an ancient algorithm for finding all prime numbers up to any given limit. It does so by iteratively marking as composite (i.e., not prime) the multiples of each prime, starting with the first prime number, 2. The multiples of a given prime are generated as a sequence of numbers starting from that prime, with constant difference between them that is equal to that prime. This is the sieve's key distinction from using trial division to sequentially test each candidate number for divisibility by each prime. Once all the multiples of each discovered prime have been marked as composites, the remaining unmarked numbers are primes. The sieve of Eratosthenes is one of the most efficient ways to find all primes smaller than n when n is smaller than 10 million or so.
{ "domain": "codereview.stackexchange", "id": 43410, "lm_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, sieve-of-eratosthenes", "url": null }
python, python-3.x, programming-challenge, sieve-of-eratosthenes Sieve Of Eratosthenes(Step by Step): 1- Create a list of consecutive integers from 2 through n: (2, 3, 4, ..., n). 2- Initially, let p equal 2, the smallest prime number. 3- Enumerate the multiples of p by counting in increments of p from 2p to n, and mark them in the list (these will be 2p, 3p, 4p, ...; the p itself should not be marked). 4- Find the smallest number in the list greater than p that is not marked. If there was no such number, stop. Otherwise, let p now equal this new number (which is the next prime), and repeat from step 3. 5- When the algorithm terminates, the numbers remaining not marked in the list are all the primes below n. My Solution This is my solution for problem 7 of Project Euler using Python: def sieve_of_eratosthenes(n): '''method for finding all primes up to a given natural n. ''' is_prime = [True]*n is_prime[0] = False is_prime[1] = False for i in range(2,int(math.sqrt(n)+1)): index = i*2 while index < n: is_prime[index] = False index = index+i prime = [] for i in range(n): if is_prime[i] == True: prime.append(i) return prime How could my code be improved? Answer: Initial improvements Don't use int(math.sqrt(n)). Python's integers can be very large, and math.sqrt(n) needs to first convert the integer to a floating point value before the square-root is calculated, which can lead to inaccurate results when n exceeds \$2^{53}\$. While you are likely nowhere near that limit, the function math.isqrt(n) (introduced in Python 3.8) avoids the conversion to floating point, and is actually shorter to type. Your while loop ... index = i*2 while index < n: is_prime[index] = False index = index+i ... can be replaced with a for loop using Python's range object: for index in range(i * 2, n, i): is_prime[index] = False
{ "domain": "codereview.stackexchange", "id": 43410, "lm_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, sieve-of-eratosthenes", "url": null }
python, python-3.x, programming-challenge, sieve-of-eratosthenes This should be faster than your while loop, due to the looping condition and increment all handled internally in the range() object. The final for loop used to collect primes could be replaced with list comprehension using the enumerate function: primes = [i for i, flag in enumerate(is_prime) if flag] Functional improvements 2 is the only even prime number. It is worth while handling it separately, and only testing odd numbers in the sieve. Since only odd primes are being considered in the sieve, you can double your "crossing out" increment to 2p. Also, crossing out multiples 2p, 3p, 4p, ... is inefficient, since all odd multiples below \$p^2\$ will have been crossed out during prior steps. As pointed out by vnp, you're missing "step 4". You don't need to cross out multiples of composite numbers, since they've already been crossed out. is_prime = [False, True] * (n // 2) is_prime[1] = False is_prime[2] = True for i in range(3, math.isqrt(n) + 1, 2): if is_prime[i]: for index in range(i * i, n, 2 * i): is_prime[index] = False Tool changes https://pypi.org/project/bitarray/ There is a module called bitarray which can be installed. Instead of using a list to store the is_prime flags, the bitarray can store the flags packed into individual bits of one long buffer. This is a phenomenal memory optimization. Moreover, using bitarray further simplifies the crossing-out of multiples to a slice assignment operation: import bitarray ... is_prime = bitarray.bitarray(n) is_prime.setall(False) is_prime[2] = True is_prime[3::2] = True ... for i in range(3, math.isqrt(n) + 1, 2): if is_prime[i]: is_prime[i*i::2*i] = False ...
{ "domain": "codereview.stackexchange", "id": 43410, "lm_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, sieve-of-eratosthenes", "url": null }
c++, simulation, bitwise Title: Electronic circuit logic gates simulator Question: I've seen a lot of C++ simulators implementing logic gates, but absolutely all of them use the wrapped bitwise operations of the programming language itself. I have tried to omit the use of a bitwise operator and mimic what a transistor really does at its basic level until it reaches a really functional logical gate (just using branching states). I would appreciate any kind of feedback on how this can be improved because I have an OR gate for which I need to use the C++ OR bitwise (|) operator, for which also I have an approach using 3 NAND logic gates, but I think maybe the starting idea is wrong as how I modeled the transistor and the overall composition of the electronic schema. Maybe I'll need to implement electric flow output probes to be able to virtualize the transistor itself correctly. The overall scope of this is to create a full working 8bit CPU from scratch in C++. Electronic schema profile: class ElectricSchema { public: NotGate* m_NotGate; AndGate* m_AndGate; NandGate* m_NandGate; OrGate* m_OrGate; XorGate* m_XorGate; HalfAdder* m_HalfAdder; FullAdder* m_FullAdder; // 512 bit adder FullAdder* m_BusAdder512[512]; private: bool m_voltageRail; public: ElectricSchema() : m_voltageRail(false) {} ElectricSchema(bool voltage) : m_voltageRail(voltage) {}; ~ElectricSchema() {} const bool& getVoltageRail() const { return m_voltageRail; } }; Transistor profile: class Transistor { private: bool m_collecterPinIn; bool m_basePinIn; bool m_emitterPinOut; public: Transistor() : m_collecterPinIn(schema.getVoltageRail()), m_basePinIn(false), m_emitterPinOut(false){}
{ "domain": "codereview.stackexchange", "id": 43411, "lm_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++, simulation, bitwise", "url": null }
c++, simulation, bitwise Transistor(bool collecter, bool base, bool emitter) : m_collecterPinIn(schema.getVoltageRail()), m_basePinIn(base), m_emitterPinOut(emitter) { if(collecter == false) { m_emitterPinOut = false; } else if(base == true) { m_emitterPinOut = true; } else { m_emitterPinOut = false; } } ~Transistor(){} const bool& getCollecterPinIn() const { return m_collecterPinIn; } const bool& getBasePinIn() const { return m_basePinIn; } const bool& getEmitterPinOut() { updateInternalStates(); return m_emitterPinOut; } bool& setCollecterPinIn() { return m_collecterPinIn; } bool& setBasePinIn() { return m_basePinIn; } private: void updateInternalStates() { if(m_collecterPinIn == false) { m_emitterPinOut = false; } else if(m_basePinIn == true) { m_emitterPinOut = true; } else { m_emitterPinOut = false; } } }; Full code is around 1600 lines of code: https://godbolt.org/z/McnjY5T1d
{ "domain": "codereview.stackexchange", "id": 43411, "lm_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++, simulation, bitwise", "url": null }
c++, simulation, bitwise Full code is around 1600 lines of code: https://godbolt.org/z/McnjY5T1d Answer: Why simulate transistors? I do not think simulating "what a transistor really does at its basic level" is productive. Apart from just slowing down your code and not adding any value to the end user, your simulation of a transistor is quite arbitrary. A real transistor does not have boolean inputs and a boolean output, and the output doesn't instanteneously change when the inputs change. Furthermore, virtually all logic gates nowadays are implemented using a CMOS design, meaning that it is not using transistors, but rather pairs of complementary p- and n-type MOSFETs. Finally, your NandGate is based on an AndGate and NotGate, but in real life the basic gates are often NAND and NOT, and an AND-gate is implemented by combining a NAND-gate and a NOT-gate. Class design The class ElectricSchema has a fixed set of pointers to logic gates. What if you want to make a more complex schema? Ideally, an ElectricSchema would be able to hold an arbitrary amount of logic gates. You could create a base class LogicGate, and derive the concrete gate classes from that: class LogicGate { public: virtual void update() = 0; ... }; class NotGate: public LogicGate { public: void update() override { pinOut = !pinIn; } ... }; Then in ElectricSchema, you could do: class ElectricSchema { std::vector<LogicGate *> gates; ... public: void update() { for (auto& gate: gates) { gate->update(); } } ... }; And then add gates like so: schema.gates.push_back(new NotGate());
{ "domain": "codereview.stackexchange", "id": 43411, "lm_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++, simulation, bitwise", "url": null }
c++, simulation, bitwise And then add gates like so: schema.gates.push_back(new NotGate()); Ideally each concrete LogicGate knows how to update itself based on its inputs and outputs, and you have to find some way to connect outputs from one gate to the inputs of other gates. But once you have that, you should just be able to call schema.update() in a loop to simulate the whole schema. Avoid manual new and delete It's easy to make mistakes when doing manual memory management, and in modern C++ it is almost never necessary to do this anymore. First, don't allocate memory if it is not necessary to begin with. In your class ElectricSchema, why not just write: class ElectricSchema { public: NotGate m_NotGate; AndGate m_AndGate; ... FullAddres m_BusAdder512[512]; ... }; This avoids having to write any new and delete statements. However, to make that work, your gate classes must be defined before ElectricSchema. If you do need to allocate memory, then the C++ standard library comes with several types to manage memory for you, like std::unique_ptr and the STL containers.
{ "domain": "codereview.stackexchange", "id": 43411, "lm_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++, simulation, bitwise", "url": null }
python, performance, algorithm, recursion, iteration Title: Locate Primitive Value in Nested Sequence Type - Iterative version is slower than equivalent recursive function Question: I'm looking for advice on how to improve the performance and/or style of these two search functions. This is just for fun and for practice: they are already fast enough for any application I would be using them in, and they don't have to meet any specific performance criteria, but I'm interested to see how they could be made better. The two code examples both work in all cases I've tested, but I believe there may be unnecessary overhead (especially in the second version) slowing them down. The first function is faster than the second: in my most recent benchmarking test (I included the timing procedure I used for this test in the code examples), the first took ~0.147 seconds while the second took ~0.185 seconds to perform the same 1000 searches. Description of code: These are two functions which I have written and intend to be equivalent solutions to the same problem using two different approaches. The first is a typical recursive depth-first search algorithm, and the second is the same function refactored to eliminate recursion (it is 100% iterative). Both functions take a sequence type (either list or tuple) and a primitive value (int, string etc.) as arguments, and look for the primitive value inside the sequence. If the value is found, the function returns the path taken to get to it (as a list of indices) and the depth of the item (i.e. the number of inner nested sequences it is inside). If the value does not occur anywhere in the sequence, the function returns an empty list and a depth of -1.
{ "domain": "codereview.stackexchange", "id": 43412, "lm_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, algorithm, recursion, iteration", "url": null }
python, performance, algorithm, recursion, iteration Background on this question: Recently on Stack Overflow I asked a question about a recursive depth-first search function which was failing to return the correct path after locating the item. After receiving a great answer on that site, I now have working code for the original version of the function. Someone also asked if I'd considered using a non-recursive approach, and another user suggested taking the fixed version here for improvements, so I'm doing both and posing the question as an explicit comparison of the two different implementations. When I rewrote the function to be entirely iterative, I was expecting it to run faster than the recursive version, as I'd heard that recursive calls are slow (in general) compared to loops. After running a benchmarking test on both functions side by side, I was surprised to see that the iterative implementation was actually significantly slower. Although I'm familiar with the concept, I'm not very experienced with actually implementing breadth-first algorithms compared to depth-first ones, so the decreased performance is probably because I'm doing something inefficiently or performing unnecessary work somewhere in the function. My best guess is that it's the part that 'retraces its steps' from the outermost sequence at depth 0 back to depth (n - 1) after exiting a nested sequence at depth n. (This is the nested for loop inside the while loop: I've made a note of it inside the code comments as well.) While I'm aware that the 'retracing' procedure could be avoided by storing references to each nested sequence as they're encountered, this doesn't seem like a worthwhile tradeoff due to the added space complexity (although this should be negligible since they would just be references, not deep copies) and decrease in readability from having yet another temporary variable at the top of the function. If I'm wrong about this I'd be glad to be corrected though.
{ "domain": "codereview.stackexchange", "id": 43412, "lm_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, algorithm, recursion, iteration", "url": null }
python, performance, algorithm, recursion, iteration Here is the recursive function: # ITERATIVE/RECURSIVE SEQUENCE TRAVERSER # Searches for 'item' in sequence (list or tuple) S, and returns a tuple # containing the indices (in order of increasing depth) at which the item # can be found, plus the depth in S at which 'item' was found. # If the item is *not* found, returns a tuple containing an empty list and -1 # For benchmarking import time def traverse(S, item, indices=[]): # If the sequence is empty, return the 'item not found' result if not S: return ([], -1) else: # For each element in the sequence (breadth-first) for i in range(len(S)): # Success condition base case: found the item! if S[i] == item: # Credit to Freddy Mcloughlan from Stack Overflow for # pointing out that since the depth is always 1 less than # the length of the final list of indices, it doesn't have # to be passed as another parameter to 'traverse' return (indices + [i], len(indices)) # Recursive step (depth-first): enter nested sequence # and repeat procedure from beginning elif type(S[i]) in (list, tuple): testCall = traverse(S[i], item, indices + [i]) # Nick's solution from Stack Overflow: only return the # recursive call if it is a success result, to avoid # 'covering up' successes with false negatives if testCall != ([], -1): return testCall # Fail condition base case: searched the entire length # and depth of the sequence and didn't find the item, so # return the 'item not found' result else: return ([], -1) L = [0, 1, 2, [3, (4, 5, [6, 6.25, 6.5, 6.75, 7]), 7.5], [[8, ()]], (([9], ), 10)] startTime = time.time() for i in range(1000): for j in range(21): traverse(L, j/2)
{ "domain": "codereview.stackexchange", "id": 43412, "lm_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, algorithm, recursion, iteration", "url": null }
python, performance, algorithm, recursion, iteration startTime = time.time() for i in range(1000): for j in range(21): traverse(L, j/2) finishedAt = time.time() print("Original recursive version took " + str(finishedAt - startTime) + " seconds") And here is the iterative equivalent: # Iterative-only version of the same function from the question # For benchmarking import time def traverse(S, item): indices = [] sequence = S depth = 0 # By definition, if the sequence is empty, you won't find any items in it. # Return the 'item not found' result. if not S: return ([], -1) else: # You have to start somewhere :D indices.append(0) while depth > -1: # Go back up one level once the end of a nested sequence is reached. while indices[depth] == len(sequence): depth -= 1 # If the depth ever gets below 0, that means that we've scanned # the entire length of the outermost sequence and not found the # item. Return the 'failed to find item' result. if depth == -1: return ([], -1) # Remove the entry corresponding to index in the innermost # nested sequence we just exited indices.pop() # INEFFICIENT ??? # Reset 'sequence' using the outermost sequence S and the indices # computed so far, to get back to the sequence which contained # the previous one sequence = S for i in range(len(indices) - 1): sequence = sequence[indices[i]]
{ "domain": "codereview.stackexchange", "id": 43412, "lm_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, algorithm, recursion, iteration", "url": null }
python, performance, algorithm, recursion, iteration indices[depth] += 1 # And return to the top of the outer 'while' loop to re-check # whether to go down another level continue # Success: found the item at depth 'depth', in sequence 'sequence', # at index 'indices[depth]` inside that sequence. Return 'indices' # and 'depth'. if sequence[indices[depth]] == item: return (indices, depth) # Recursion replacement: enter the nested subsequence and increase the depth # as long as the nested subsequence is not empty. If it is empty, treat it # as if it were a non-sequence type. elif (type(sequence[indices[depth]]) in (list, tuple)) and (sequence[indices[depth]]): sequence = sequence[indices[depth]] depth += 1 indices.append(0) # The item being compared is not a sequence type and isn't equal to 'item', so increment # the index without increasing the depth else: indices[depth] += 1 # If all of S has been searched and item was not found, # return the 'failed to find item' result return ([], -1) L = [0, 1, 2, [3, (4, 5, [6, 6.25, 6.5, 6.75, 7]), 7.5], [[8, ()]], (([9], ), 10)] startTime = time.time() for i in range(1000): for j in range(21): traverse(L, j/2) finishedAt = time.time() print("Iterative version took " + str(finishedAt - startTime) + " seconds") I would greatly appreciate any suggestions for improvements to either or both implementations (regarding performance, readability, or any other 'best practices' metric), but especially would be interested in a comparison of where the second version is getting slowed down and falling behind the first.
{ "domain": "codereview.stackexchange", "id": 43412, "lm_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, algorithm, recursion, iteration", "url": null }
python, performance, algorithm, recursion, iteration Answer: The benchmark is flawed because the iterative version is doing too much work. Iterative BFS/DFS has an elegant simplicity once your get your mind wrapped around its core idea. Your implementation, by contrast, is fairly complex and, at least for me, unintuitive. The complexity comes from managing, mutating, and resetting the state variables, especially sequence and indices, as you go from level to level. Those repeated mutations slow things down. Classic BFS/DFS. A typical implementation, by contrast, avoids the need to worry about resetting the status variables. Instead, it uses a queue/stack to hold independent copies of the state. The queue/stack functions as a TODO list. What goes into the TODO? The arguments that you would have passed recursively (there's a reason they call it a "call stack"). You must take care not to mutate those variables. Only the queue/stack is mutated. def traverse_iterative(S, item): if S: # Initialize the TODO list. stack = [(S, [])] while stack: # Get the next data to check. xs, indices = stack.pop() for i, x in enumerate(xs): if x == item: # Success. return (indices + [i], len(indices)) elif isinstance(x, (list, tuple)): # Add it to the TODO list. stack.append((x, indices + [i])) return ([], -1)
{ "domain": "codereview.stackexchange", "id": 43412, "lm_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, algorithm, recursion, iteration", "url": null }
python, performance, algorithm, recursion, iteration Benchmark. That function runs generally the same speed as your recursive function on my computer (0.152 vs 0.151, using your scenario). One could fuss around with details on both functions to squeeze out some more performance (for example, the edits shown below speed up the recursive function a small bit), but I'm mostly bored by that sort of thing. Code review stuff. Your recursive implementation is reasonable and easy to understand. Just a few suggestions. (1) Define a failed search constant rather than hardcoding it in three places. (2) Iterate directly over Python collections, rather than iterating over the collection's indexes (and if you also need indexes, use enumerate). (3) Use isinstance() to check the type. (4) Very few Python programmers use for-else, because it's not intuitive (does "else" mean that the loop was broken or not, and are there any other tricky details I need to remember?), so just do the normal thing and put the failed return statement after the loop. And even if you find the for-else structure really handy in some circumstances (I never have), the current case isn't one them, because you never break the loop. def traverse_recursive(S, item, indices=[]): FAIL = ([], -1) if S: for i, x in enumerate(S): if x == item: return (indices + [i], len(indices)) elif isinstance(x, (list, tuple)): result = traverse_recursive(x, item, indices + [i]) if result != FAIL: return result return FAIL
{ "domain": "codereview.stackexchange", "id": 43412, "lm_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, algorithm, recursion, iteration", "url": null }
python, unit-testing, functional-programming, modules Title: UPDATE on Newspaper Bill Calculator CLI with Python (1 of 3, Core) Question: Code is posted after explanation. Due to the size of the project, this is being posted in three separate posts. This also ensures each post is more focused. Post 2 of 3, CLI: UPDATE 1 on Newspaper Bill Calculator CLI with Python (2 of 3, CLI) Post 3 of 3, Database: UPDATE 1 on Newspaper Bill Calculator CLI with Python (3 of 3, Database) This is a follow-up to an earlier version of the same project. The feedback from the last round is tracked in an issue. What is this? This application helps you calculate monthly newspaper bills. The goal is to generate a message that I can paste into WhatsApp and send to my newspaper vendor. The end result here is a CLI tool that will be later used as a back-end to build GUIs (hence learn about: C#, HTML/CSS/JS, Flutter). In its current form, everything will be "compiled" by PyInstaller into one-file stand-alone executables for the end-user using GitHub Actions. The other important goal was to be a testbed for learning a bunch of new tools: more Python libraries, SQL connectors, GitHub Actions (CI/CD, if I understand correctly), unit tests, CLI libraries, type-hinting, regex. I had earlier built this on a different platform, so I now have a solid idea of how this application is used. Key concepts Each newspaper has a certain cost per day of the week Each newspaper may or may not be delivered on a given day Each newspaper has a name, and a number called a key You may register any dates when you didn't receive a paper in advance using the addudl command Once you calculate, the results are displayed and logged. What files exist? (ignoring conventional ones like README and requirements.txt) File Purpose/Description Review
{ "domain": "codereview.stackexchange", "id": 43413, "lm_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, unit-testing, functional-programming, modules", "url": null }
python, unit-testing, functional-programming, modules File Purpose/Description Review npbc_core.py Provide the core functionality: the calculation, parsing and validation of user input, interaction with the DB etc. Later on, some functionality from this will be extracted to create server-side code that can service more users, but I have to learn a lot more before getting there. Please review this. npbc_regex.py Contains all the regex statements used to validate and parse user input. Please review this. npbc_exceptions.py Defines classes for all the custom exceptions used by the core and the CLI. Please review this. npbc_cli.py Import functionality from npbc_core.py and wrap a CLI layer on it using argparse. Also provide some additional validation. Please review this. npbc_updater.py Provide a utility to update the application on the user's end. Don't bother reviewing this (code not included). test_core.py Test the functionality of the core file (pytest), except anything to do with the database. Please review this. test_db.py Test the functionality of the core file (pytest), for anything to do with the database. Please review this. test_regex.py Test the functionality of the regex statements. Please review this. data/schema.sql Database schema. In my local environment, the data folder also has a test database file (but I don't want to upload this online). Please review this if you can (not high priority). data/test.sql SQL statements to generate test data for test_db.py. Please review this if you can (not high priority). npbc_core.py """ provides the core functionality - sets up and communicates with the DB - adds, deletes, edits, or retrieves data from the DB (such as undelivered strings, paper data, logs) - performs the main calculations - handles validation and parsing of many values (such as undelivered strings) """
{ "domain": "codereview.stackexchange", "id": 43413, "lm_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, unit-testing, functional-programming, modules", "url": null }
python, unit-testing, functional-programming, modules from calendar import day_name as weekday_names_iterable from calendar import monthcalendar, monthrange from datetime import date as date_type from datetime import datetime, timedelta from os import environ from pathlib import Path from sqlite3 import Connection, connect from typing import Generator import npbc_exceptions import npbc_regex ## paths for the folder containing schema and database files # during normal use, the DB will be in ~/.npbc (where ~ is the user's home directory) and the schema will be bundled with the executable # during development, the DB and schema will both be in "data" # default to PRODUCTION DATABASE_DIR = Path.home() / '.npbc' SCHEMA_PATH = Path(__file__).parent / 'schema.sql' # if in a development environment, set the paths to the data folder if environ.get('NPBC_DEVELOPMENT') or environ.get('CI'): DATABASE_DIR = Path('data') SCHEMA_PATH = Path('data') / 'schema.sql' DATABASE_PATH = DATABASE_DIR / 'npbc.db' ## list constant for names of weekdays WEEKDAY_NAMES = list(weekday_names_iterable) def setup_and_connect_DB() -> None: """ensure DB exists and it's set up with the schema""" DATABASE_DIR.mkdir(parents=True, exist_ok=True) DATABASE_PATH.touch(exist_ok=True) with connect(DATABASE_PATH) as connection: connection.executescript(SCHEMA_PATH.read_text()) connection.close() def get_number_of_each_weekday(month: int, year: int) -> Generator[int, None, None]: """generate a list of number of times each weekday occurs in a given month (return a generator) - the list will be in the same order as WEEKDAY_NAMES (so the first day should be Monday)""" # get the calendar for the month main_calendar = monthcalendar(year, month) # get the number of weeks in that month from the calendar number_of_weeks = len(main_calendar) # iterate over each possible weekday for i, _ in enumerate(WEEKDAY_NAMES):
{ "domain": "codereview.stackexchange", "id": 43413, "lm_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, unit-testing, functional-programming, modules", "url": null }
python, unit-testing, functional-programming, modules # iterate over each possible weekday for i, _ in enumerate(WEEKDAY_NAMES): # assume that the weekday occurs once per week in the month number_of_weekday: int = number_of_weeks # if the first week doesn't have the weekday, decrement its count if main_calendar[0][i] == 0: number_of_weekday -= 1 # if the last week doesn't have the weekday, decrement its count if main_calendar[-1][i] == 0: number_of_weekday -= 1 yield number_of_weekday def validate_undelivered_string(*strings: str) -> None: """validate a string that specifies when a given paper was not delivered - first check to see that it meets the comma-separated requirements - then check against each of the other acceptable patterns in the regex dictionary""" # check that the string matches one of the acceptable patterns for string in strings: if string and not ( npbc_regex.NUMBER_MATCH_REGEX.match(string) or npbc_regex.RANGE_MATCH_REGEX.match(string) or npbc_regex.DAYS_MATCH_REGEX.match(string) or npbc_regex.N_DAY_MATCH_REGEX.match(string) or npbc_regex.ALL_MATCH_REGEX.match(string) ): raise npbc_exceptions.InvalidUndeliveredString(f'{string} is not a valid undelivered string.') # if we get here, all strings passed the regex check def extract_number(string: str, month: int, year: int) -> date_type | None: """if the date is simply a number, it's a single day. so we just identify that date""" date = int(string) # if the date is valid for the given month if date > 0 and date <= monthrange(year, month)[1]: return date_type(year, month, date) def extract_range(string: str, month: int, year: int) -> Generator[date_type, None, None]: """if the date is a range of numbers, it's a range of days. we identify all the dates in that range, bounds inclusive"""
{ "domain": "codereview.stackexchange", "id": 43413, "lm_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, unit-testing, functional-programming, modules", "url": null }
python, unit-testing, functional-programming, modules start, end = map(int, npbc_regex.HYPHEN_SPLIT_REGEX.split(string)) # if the range is valid for the given month if 0 < start <= end <= monthrange(year, month)[1]: for date in range(start, end + 1): yield date_type(year, month, date) def extract_weekday(string: str, month: int, year: int) -> Generator[date_type, None, None]: """if the date is the plural of a weekday name, we identify all dates in that month which are the given weekday""" weekday = WEEKDAY_NAMES.index(string.capitalize().rstrip('s')) for day in range(1, monthrange(year, month)[1] + 1): if date_type(year, month, day).weekday() == weekday: yield date_type(year, month, day) def extract_nth_weekday(string: str, month: int, year: int) -> date_type | None: """if the date is a number and a weekday name (singular), we identify the date that is the nth occurrence of the given weekday in the month""" n, weekday_name = npbc_regex.HYPHEN_SPLIT_REGEX.split(string) n = int(n) # if the day is valid for the given month if n > 0 and n <= list(get_number_of_each_weekday(month, year))[WEEKDAY_NAMES.index(weekday_name.capitalize())]: # record the "day_id" corresponding to the given weekday name weekday = WEEKDAY_NAMES.index(weekday_name.capitalize()) # store all dates when the given weekday occurs in the given month valid_dates = [ date_type(year, month, day) for day in range(1, monthrange(year, month)[1] + 1) if date_type(year, month, day).weekday() == weekday ] # return the date that is the nth occurrence of the given weekday in the month return valid_dates[n - 1] def extract_all(month: int, year: int) -> Generator[date_type, None, None]: """if the text is "all", we identify all the dates in the month""" for day in range(1, monthrange(year, month)[1] + 1): yield date_type(year, month, day)
{ "domain": "codereview.stackexchange", "id": 43413, "lm_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, unit-testing, functional-programming, modules", "url": null }
python, unit-testing, functional-programming, modules for day in range(1, monthrange(year, month)[1] + 1): yield date_type(year, month, day) def parse_undelivered_string(month: int, year: int, string: str) -> set[date_type]: """parse a section of the strings - each section is a string that specifies a set of dates - this function will return a set of dates that uniquely identifies each date mentioned across the string""" # initialize the set of dates dates = set() # check for each of the patterns if npbc_regex.NUMBER_MATCH_REGEX.match(string): number_date = extract_number(string, month, year) if number_date: dates.add(number_date) elif npbc_regex.RANGE_MATCH_REGEX.match(string): dates.update(extract_range(string, month, year)) elif npbc_regex.DAYS_MATCH_REGEX.match(string): dates.update(extract_weekday(string, month, year)) elif npbc_regex.N_DAY_MATCH_REGEX.match(string): n_day_date = extract_nth_weekday(string, month, year) if n_day_date: dates.add(n_day_date) elif npbc_regex.ALL_MATCH_REGEX.match(string): dates.update(extract_all(month, year)) else: raise npbc_exceptions.InvalidUndeliveredString(f'{string} is not a valid undelivered string.') return dates def parse_undelivered_strings(month: int, year: int, *strings: str) -> set[date_type]: """parse a string that specifies when a given paper was not delivered - each section states some set of dates - this function will return a set of dates that uniquely identifies each date mentioned across all the strings""" # initialize the set of dates dates = set() # check for each of the patterns for string in strings: try: dates.update(parse_undelivered_string(month, year, string))
{ "domain": "codereview.stackexchange", "id": 43413, "lm_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, unit-testing, functional-programming, modules", "url": null }
python, unit-testing, functional-programming, modules except npbc_exceptions.InvalidUndeliveredString: print( f"""Congratulations! You broke the program! You managed to write a string that the program considers valid, but isn't actually. Please report it to the developer. \nThe string you wrote was: {string} This data has not been counted.""" ) return dates def get_cost_and_delivery_data(paper_id: int, connection: Connection) -> list[tuple[bool, float]]: """get the cost and delivery data for a given paper from the DB""" query = """ SELECT delivered, cost FROM cost_and_delivery_data WHERE paper_id = ? ORDER BY day_id; """ # return a list but convert the delivery data to Booleans because SQLite won't do it return list(map( lambda row: (bool(row[0]), row[1]), connection.execute(query, (paper_id,)).fetchall() )) def calculate_cost_of_one_paper( number_of_each_weekday: list[int], undelivered_dates: set[date_type], cost_and_delivered_data: list[tuple[bool, float]] ) -> float: """calculate the cost of one paper for the full month - any dates when it was not delivered will be removed""" # initialize counters corresponding to each weekday when the paper was not delivered number_of_days_per_weekday_not_received = [0] * len(number_of_each_weekday) # for each date that the paper was not delivered, we increment the counter for the corresponding weekday for date in undelivered_dates: number_of_days_per_weekday_not_received[date.weekday()] += 1
{ "domain": "codereview.stackexchange", "id": 43413, "lm_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, unit-testing, functional-programming, modules", "url": null }