New answers tagged

3

I will first say, broadly: I understand that you're constrained by the demands of the assignment, but the assignment doesn't make any sense. It isn't your fault, but like - some of the features are pointless. Allowing the user to check whether a username exists in the list is pointless. There are ways to construct a semi-realistic scenario that exercise the ...


1

Hello and welcome to the Rust community. Correctness Are you sure the code is correct? The regex looks odd, but ok. It seems that Tag::Close does not carry any meaningful info, even though it contains a String. Manual Be sure to read up on if let statements. They are useful for concise and idiomatic code. Here, catch some reading material: https://doc.rust-...


3

Goal The goal is to optimize the program. I won't change the backtracking algorithm. General feedback Your code is good, but you should use structs and impls in this program, instead of passing grid: [[i8; 9]; 9] around. I show this in code below. Idea You check cell vacancy with many loops that check multiple cells. How about we kill many birds with one ...


2

This is a fun project. Here are a few things I noticed: $AlivePercChance implies that it's a percentage (30%) rather than a fraction (0.3). You might consider renaming it to $AliveChance Why did you flatten the 2D array to 1D? It adds substantial overhead (2 extra function calls * $Width * $Height per screen write, way more for checking neighbors) and ...


2

Good things You mostly follow PEP8 styling conventions, making your code quite readable. The only exception I see is an extra blank line at the beginning of the score and play methods. Also, it is good thinking to wrap your game state into a class for future integration into a more complex project. It is also a good use of a main guard at the end. However, ...


0

import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.Map; import java.util.Stack; import java.util.function.DoubleBinaryOperator; import java.util.function.DoubleUnaryOperator; import static java.util.Map.entry; public class Rpn { private static final Map<String, DoubleUnaryOperator> FUNCTIONS = Map.ofEntries( ...


0

I can't see how you got stuck. You just do like you said: use map instead of Strings, then collect into a Vec, and finally join into one String. Here is the code. fn main() { let phrase = "Test sentence for pig latin f 🎈🎆🎇 नर र स्का स्कास्का 🧨".to_lowercase(); let split = phrase.split_whitespace(); let pigifyed = split.map(|word| { ...


3

There's some odd features to this code, even for a coding practice exercise. Python of course has a couple of list sorting techniques which you should absolutely use in normal circumstances. So accepting that you are doing this for practice, I wonder what the point of the duplicatelist is? Or indeed temp? Are these development fossils of some earlier process ...


0

Great tips from the other answer, here are just some more bits and bobs. Use the library capabilities to their fullest char1 = a new_list = data new_list.remove(char1) char2 = random.choice(data) new_list.append(char1) This, in addition to the uncommon indentation sticks out to me. Why are we removing, why are we adding, why are we redefining? ...


0

I have done some Ansible tasks 5 years ago, so I looked at your code just out of interest, and I didn't read any documentation. Here are some things I noted by just looking at the code: The task apt_key looks strange to me. The basic idea of a GPG key is that it provides a trust anchor. You currently trust the URL of that task to always provide the correct ...


3

I'm not going to go too heavily into refactoring the whole thing. Some basic readability things: return_values = compare(options[0], options[1], score) score = return_values[1] lost = return_values[0] It would be much clearer if you did: lost, score = compare(options[0], options[1], score) You have indented things with two spaces, which is odd, normally ...


0

Your code and solution worked fine. Although I needed to change the inputData object's method: "name: raw_data," which contained an undefined variable. I then simply passed reference argument string as an input function and it worked perfectly. def inputData(): name = input('Name of employee: ') hours = float (input('Now enter the ...


1

welcome to the Rust community. Rust's borrow checker analyzes the control flow of your code. However, it does not take into account the state of your variables (current_node and found_child in your example). That would be something like symbolic execution. Instead, the borrow checker is pessimistic and it checks your if !found_child for conflicts with the ...


0

The hardest thing about programming is creating a good project structure, but this is also the most important thing to get correct. Your project is structured well, and cleanly follows the model-view-controller structure, so great job! Your view logic is cleanly separated from the underlying model, and your controller is requesting updates on both the model ...


3

Your previous question dealt with counting the number of levels in a nested data structure. This question deals with collecting values from a specific level (sort of). In both cases, your conceptualization of the problem strikes me as somewhat unintuitive, at least based on my experience with languages like Perl, Ruby, and Python. To help clarify things, let'...


0

Your code seems to work properly on the whole test suite provided which is a very good start. Also, splitting the logic in 2 parts, one preprocessing the counts and the other performing the comparison is a great way to proceeed. However, there are still various way to improve the code. Style Python has a style guide called PEP 8 which is definitly worth ...


4

Thanks for submitting this for a code review. I like the indentation and documentation in your code. The biggest problem I see with this is dealing with filenames that haves spaces in them. Your select line will almost certainly break. The find command will let you get the results null-terminated using -print0, but I'm not sure how to get the select to ...


2

In more than one place your code assumes that it is restricted to tuple, list, set, or dict. That's a perfectly reasonable policy decision for code like this. Given that decision, the code to check for iterability is needlessly complex. Something along these lines would do the trick: isinstance(obj, (tuple, list, set, dict)) If your goal is to count nesting ...


2

I think we could make use of recursivity, as well as dunder (double underscore) attribute. For example def is_iterable(a): if "__iter__" in a.__dir__(): print("I am an iterable ! You can do `for x in a`") else: print("I am not an iterable ! You can move on") >>> a_dict = {"5": 3} >&...


1

Know your standard library There's a standard function for finding one of a set of characters, and that's strcspn(). int password_check(const char *const password) { const size_t len = strlen(password); return strcspn(password, "ABCDEFGHIJKLMNOPQRSTUVWXYZ") == len || strcspn(password, "0123456789") == len || !...


2

So this is a great start for someone just starting out. I will go off on a huge tangent here, but hopefully you can take something away from how I approached improving a very minor part of your code. Player states class Player: id: int name: str = "" symbol: str = "" is_winner: bool = False Now we can build the list of ...


1

As a beginner, you have done fantastic! There is always something to improve, in your code, mainly, performance. print() Instead of priniting again and again, create a string of output, and print it in a single call. It is way faster than printing in sperate calls. Your code has doc-strings, follows pep8 and is overall very readable. You could also add ...


1

First impression: looking good. #ifndef GALLERY_H #define GALLERY_H The name is hardly unique. In real code, you need to consider that programs will include headers (possibly indirectly, several levels deep) from different unrelated libraries. Any simple name has a serious possibility of clashing. Use a UUID for this. Later: why is the #endif in the ...


2

In any event, I would avoid the inline logic at the initialization of your attributes and abstract that out to a validator funtion. There are several approaches to class attribute validations you can follow, some of which are mentioned here in other answers. This article describes several fairly well. Following the example presented by @Graipher's answer, ...


4

We start off reasonably well, defining some constants: #define DECK_SIZE 52 //to be used to randomly select each of 52 cards #define SUITS_PLUS_ONE 5 //to be used to generate any of the 4 suits #define PIPS_PLUS_ONE 14 //to be used to generate any of the 13 pips I'd argue that we shouldn't have _PLUS_ONE constants, but to simply add 1 where ...


1

Each Control does have a property called Tag. This can contain/hold any kind of information since its type is object. Assign the Title, ... ,Url values to the corresponding TextBox's Tag: private readonly TextBox[] textBoxes = new [] { titleText, ... , urlText }; public Form1() { InitializeComponent(); titleText.Tag = "Title"; ... ...


1

you can use Dictionary to store the TextBoxs and their representive name, then just iterate over them, something like this : private bool ValidInput() { Dictionary<string, TextBox> textBoxes = new Dictionary<string, TextBox> { { "Title", titleText }, { "Artist", artistText }, { "Genre",...


2

Addressing the print formatting part of your question, base R's sprintf function handles all the formatting you're looking for and a lot more besides. sprintf takes exactly one format string - which includes both your text and the placeholders for your variable data, including formatting instructions like numbers of decimal places and the variables. Its ...


5

Consider double Rather than int and float objects, consider double. Printing floating point Use "%e" or "%g" to see more information. "%f" prints many large values with dozens of uninformative digits. "%f" prints small values as 0.000000. Using "%f" takes the float out of floating point. // suggestions ...


0

Result Thank you all for your answers. :) I think I've come to a really satisfactory result to me. I've learned a lot. In this stadium I think I'm done with this program unless there's some bug I don't know about (may be, if I know myself). Rewrote the original program to making it a running script instead of reading the result from stdin. Used struct to ...


4

You should know that double is the normal floating-point type, and float is half sized and should only be used where you really need to save the space. Your program is mostly dealing with reading input, which is not the problem you came to solve! A real utility program would take command line arguments, not prompt the user to type things. That is, you ...


6

set_number_from_stdin has several bugs: if fgets fails, you assign the uninitialised variable final_number to *num. That’s undefined behaviour. In practice a compiler might assume that UB never happens, and it might thus for instance remove the break statement entirely. You need to handle the input error. Since your current function has no way of signalling ...


10

Overall clear and readable. Some remarks: atoi is one of those standard library functions that should never be used. It is 100% equivalent to strtol family of functions, except that the latter have error handling and support for other number bases than decimal. Since you are using this function on user input which has not been sanitized, you should not use ...


2

Big task OP's goal of "trying to write a generic dynamic array which is type safe." is admirable, but not a good task for someone new to C. I recommend to start with a write a generic dynamic array for void *. Later, research _Generic. Not so generic Approach relies on types not having spaces. Try struct DynArray(long long) llArr; Stand-alone ...


Top 50 recent answers are included