Tag Info

New answers tagged beginner

2

Prelude I think your code (sans bug) is fine. Your question is already a little nit-picky so my comments will mostly be nit-picks. I am not a Haskell expert either, so don't place too much authority in my comments. Evaluate them for yourself. My comments are in a somewhat arbitrary order, but I've organized them with headers. The section pertaining ...

1

Reliability I get that this program is meant for you to continue learning python, but please don't use any passwords generated by this program. Especially since your strength check is really weak. I.E, this function that checks the strength thinks Password123 is a strong password. Don't use it :-). Checking password strength This function can be reduced to ...

2

Good stuff lots of good comments indenting your function definition putting variables inside of double quotes when you use them Suggestions indent between then and fi, as you would in other languages with conditionals combine then with if line using ; use [[ forms of conditionals to avoid surprises Those three things would lead to code like: if [[ ! -d &...

2

Take a look at what translating 1241234113 results in when aligned slightly differently One Billion Two Hundred Forty One Million Two Hundred Thirty Four Thousand One Hundred Thirteen you can see that there are several patterns here. Every number can be chunked into groups of 3 digits like ...

0

I get that the objective here is to do it with Ruby, but if all you are looking to do is kexec based reboot, this is a little more complicated than necessary. You may find the script in this article handy for a simple fast reboot using kexec. The bash is trivial enough to easily convert to Ruby.

2

The code looks fine. At a high level, I don't think it really makes sense to say that this code follows a particularly object-oriented or functional style, maybe because the application is too simple. The difference in this case is really more a matter of perspective. From an OOP point of view, maybe you see a type with a bunch of methods. That's okay. (It's ...

7

Prelude First of all, good work! I can see the effort you put into grokking something so foreign, and I would like to commend you for it. I will be focusing on reviewing what I think you can improve, but don't let these critiques discourage you—all code can be improved, but not all code works. I'll be doing a combination of making general comments and ...

2

I have been working on this code to meet the best OOP standards for production. I think your biggest problem here is that PriceCalculator does too many things: Getting user input Calculating the price per checkout item Calculating the total price Printing the bill Let's try to split this up a bit first by introducing a BillRow for each line in your Bill ...

3

You've created an unnecessary scope by putting braces after int querylength. Do you have a good reason for doing this?

0

Edit: this is same algorithm as provided by Simon but different code. ....... One option is to use Euler himself to solve Euler Project #1. Namely triangular numbers (Elements of Algebra, 427). def triangular_number(num, max_num=999): """Return maximum triangular number of num in range max_num (inclusive). Calculate number of ...

0

Hmm, since your values are symmetric, it would be better to make the code better by using the "DRY"(Don't repeat yourself) principle. You can separate your data from the code and iterate on all species to avoid code duplication. I would suggest to store all species data in a json file and then use a for loop to iterate over them. Now in one of my ...

1

Make helper functions private Member functions that are not part of the public API should be marked private. You should know that by now :) Use uint64_t instead of size_t There is no guarantee that size_t is big enough for the calculations you are doing. While you might only need 32 bits to store the results, you need to do the calculations using 64 bit ...

1

inline std::string int2string(const int n) { if (n >= one_billion) { return int2string(n / one_billion) + " "+ BILLION + int2string(n % one_billion); } else if (n >= one_million) { return int2string(n / one_million) + " " + MILLION + int2string(n % one_million); } else if (n >= one_thousand) { ...

2

**Note: A lot of these might be very similar to tieskedh's answer but I drafted before it was here so I thought I should add it ** I'm not a fan of, when a user clicks on new item, calling notifyDataSetChanged on all items. You can use notifyItemRangeChanged(index) or notifyItemChanged(index) in order to specify which items have changed. This is incredibly ...

0

Timing of your algorithm def f(): x = 0 for i in range(1000): if i % 3 == 0 or i % 5 == 0: x += i return x %timeit f() 152 µs ± 12.5 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each) Using Principle of Inclusion and Exclusion (PIE) gives you the answer faster. %timeit (sum(range(3, 1000, 3)) + sum(range(5, 1000, ...

4

Overall This code is fairly well-structured and very well-documented. Excellent job. Type hints It's good that you specified types here: L : int, float Length of the reactor/lamp [m] r_outer : int, float Outer radius [m] r_outer : int, float Better would be to codify these in type hints: def reactor_volume( L: Union[int, ...

1

This is not a proper review. I just want to show an argument why passign the input by value is actually more useful then passing it by const reference, in this particular case. Yes, it's true you should not modify the input for the caller, because he didnt ask you to do so. But it is also true, that your implementation takes advantage of the ability to ...

2

Passing by reference or value Currently, std::vector<int> nums forces callers to pass a copy of the entire vector by value. You could argue that this is actually useful, since your algorithm needs to mutate it (or a copy of it) in-place. My preference is usually to make this copy-step explicit instead: Pass a const & reference, not a mutable copy ...

1

I don't know about this typevar but it seems over complicated. Why are you specifying the type and using two classes when you need only one. Here's my solution. class Node: def __init__(self, val): self.val = val self.left = None self.right = None def add(self, val): if val < self.val: if self.left == ...

0

I know this is old, but considering the amount of views it gets (and I also looked it up now) thought I'd also add. Couldn't you just use a dictionary, and convert all letters to upper (this way you don't have to import anything either)? DNA_complement_dict={'A':'T', 'T':'A', 'G':'C', 'C':'G' ...

2

Make clone_tree() private Make helper functions that are not part of the public API private. Avoid unnecessary nesting of statements if possible In allPossibleFBT() there's a lot of indentation. There's a risk of the code running off the right hand side of the screen, making it hard to read. Try to reduce nesting if possible (but only if it improves ...

3

You don't need to use useEffect and result states: liquidityRatio, dailyCost. Just edit like this When you change your inputs, the render will be called and excecute from top to bottom. And result variables will be computed again. Notes: That just basic answer for beginner in React.

3

Naming Naming is really important. There are conventions that help to give helpful hints to the reader about what a name refers to. camelCase names on their own are typically going to be variables, camelCase( with parenthesis are likely to be function calls. Capitals are typically used for classes, constants, enums. So, when I see something like this: ...

3

Question: method and normal variable names in java start with a small letter by convention. As opposed to C#. Is it a special convention of the course? Repetitive code for array entries. X == true is simply X and X == false is !X (not X). Parameters f(X[] array, int index) might just be f(X x). It also might be that then the called method should be a method ...

4

OOAD - Object Orientated Analyze and Design It's always a good idea to start with a pen and a pencil before you do any coding. Here is a demonstration on how such an Design could look like (I strongly recommend UML since this kind of diagramms is understood by everybody among engineers) Honestly I do not fully understand your requirements (your homework ...

1

Function signatures You've made the best out of a slightly silly situation. I think your function signatures, while abiding to the template, have improved since the last post of yours that I reviewed. I'm not sure whether this will break LeetCode compatibility, but if you want to enforce that no one can instantiate this class, try making a private default ...

2

I haven't used nasm, but superficially, it looks like you are calling out to the kernel for each character in the string. This is likely to be a relatively expensive operation. Looking at this, it would appear that edx can be used to specify the number of characters to output. With this in mind, it would probably be more efficient to find the string length ...

1

Thank's all for yours answers and solutions! I'm read every example and teaches myself something new. Guys - you are great! This is my solution. And of course I except from this global variables. import random class game(): num_wins = 0 num_losses = 0 num_ties = 0 def run_game(): choices = ["paper", "...

2

You forgot a std:: There's a string without std:: in front of it. I guess you secretly used using namespace std and/or #include <bits/stdc++.h> before submitting the result. The rest looks fine though. Consider using const TreeNode * everywhere I know the public API of the LeetCode problem explicitly takes non-const pointers to TreeNode, so you shouldn'...

1

On the continuum of good or bad, where do you think my code lies? The Eight Queens puzzle is already some advanced programming and if we consider that you just started programming ~6 months ago it is great that you came up with a working solution. I think it is a clever approach to store the valid and invalid position in a set which is an efficient way for ...

2

To address your immediate concerns, Using the return stack for storing your temporaries is a perfectly valid technique. pick is always frown upon (as well as tuck, roll, and friends). It seems that the len parameter to bubblesort does not participate in computation - except the very beginning - and mostly just stays in the way. Consider : bubblesort ...

0

Your code has several areas where it can be improved. The first is that you should separate the parsing code from the platform code (Toast). Kotlin has a great testing framework, in which it is easy to write "parsing "1 2/3" should return listOf(1, 2, 3)". This testing code works best if you run it directly on your developing machine, and ...

5

Many reviews, so some additional ideas. Programmable precision Rather than hard-code the 5, use a flexible variable. Perhaps code later may want to allow the user to adjust the width. // printf("Here is your answer:\nLg(%f) = %.5f (to 5 decimal places)\n\n", Num1, ans); int prec = 5; printf("Here is your answer:\nLg(%.*f) = %.*f (to %d ...

2

Namespaces Have a read through https://stackoverflow.com/questions/125319/should-using-directives-be-inside-or-outside-the-namespace . I agree with StyleCop's default recommendation of moving using within the namespace: namespace RockPaperScissorsLizardSpock { using System; using System.Collections.Generic; using System.Linq; using System....

2

Rewrite the code so all references are "Player", not "Human and/or Computer" Your code will shrink by more than half. Do not use class name in method names In ComputerPlayer ComputerRandomMove would be RandomMove SetPlayerName : SetName (Name may be ok too ) PlayerMove : Move Do not name classes as their inheritance chain HumanPlayer : ...

4

Whereas @pacmaninbw offers some excellent general strategies, let's look at some specific syntax. Pi This is a point of some contention, but - where a library defines M_PI, and most do - I tend to use it. Since you're including windows.h it's likely that you're using MSVC. In that case, it gives you math constants if you configure the compiler with ...

2

Code structure Treat main.c as boss who calls other people up to do their job. In this case, functions where one function does one thing. main is doing everything here. else{ printf("No. The correct answer is %.0d. Need to practice more!\n\n", c); system("pause"); system("cls"); } This error message can be one function which ...

3

In addition to what Reinderien said: Move class Trie inside class StreamChecker Your class Trie is not a generic class, but rather a specialized trie implementation specifically for StreamChecker. You can move it inside class StreamChecker, so that it is clear that they belong to each other, and so that class Trie does not pollute the global namespace: class ...

3

Template You can't rename functions; but can you change their signature? i.e. StreamChecker(vector<string>& words) { would be better as StreamChecker(const vector<string> &words) { Similarly, void insert(const std::string word) { should be void insert(const std::string &word) { The same for search. Also, the const in bool query(...

18

Welcome to Code Review, we wish you the best. General Observations Congratulations on getting this to work, one function that is 356 lines long and almost 17K of text is a bit large and very hard to code and debug. Complexity The function main() is too complex and should be broken into functions. A general rule of thumb in all programming is that a function ...

1

There is a lot of room for improvement in your code. First, I'd like to address an unusual request you made: Please don't recomend using functions. Why not? They are a fundamental notion in programming, and can't really be avoided. Glossing over the fact that you already use a bunch of functions like print, input, append, etc., and assuming you are ...

1

The algorithm you're using is excessively complex. There's no need to track total and negtotal separately. You also don't need tenttotal unless you want to support particularly exotic numerals like IIX (which is rare but apparently not unattested). And if you're not tracking tenttotal, then you don't need to distinguish the "current = next" and &...

1

You can simplify foo = foo + ... to just foo += .... For example you can simplify the following two lines: m = m + 1 m += 1 total = total + tenttotal + ref[roman[m]] - negtotal total += tenttotal + ref[roman[m]] - negtotal

14

Dict initialization and reuse This: ref = dict() ref['I'] = 1 ref['V'] = 5 ref['X'] = 10 ref['L'] = 50 ref['C'] = 100 ref['D'] = 500 ref['M'] = 1000 should use a dict literal: ref = { 'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000, } ...

3

For a first application in Java, good job! I have some suggestions for your code. When using regex, try to uses the java.util.regex.Pattern class instead of the java.lang.String#matches method. When using the java.lang.String#matches method, the regex pattern is recompiled each time the method is called. This can cause a slowdown in your method execution. ...

0

After @vnp's suggestions (input separated from logic, locals removed without too many stack manipulations, use MAX word, maximum product on TOS), the code changed to s" 731671765313306249192251196744265747423...450" 2constant e008-input-string \ stack comment legend \ a address; w width, p product, l length, M maxproduct \ multiply w ...

3

Disclaimer: my Forth is extremely rusty. length does not need to be local; is not a variable, it is a constant. Declare it as such: 13 constant length Dealing with input. The stack annotation ( a 1000 ) strongly hints that what follows wants to be the word on its own. Indeed, logic should be separated from IO. Consider, for example, something along the ...

2

Constant members n and k can be constant, so long as you remove them from being parameters to crackSafe you add them as parameters to a constructor the constructor uses inline initialization syntax, i.e. n(n) Basically, your two member functions should - in their current form - be bare functions outside of a class, since the class member variables only ...

4

Functionally not 100% similar but shorter version of code. Taking advantage of walrus operator and modulo 3 tricks: from random import choice choices = ['rock', 'paper', 'scissors'] results = ['user wins', 'computer wins', 'draw'] totals = [0, 0, 0] while True: while (user_choice := input('Please choose {}, {} or {}: '.format(*choices))) not in ...

3

Unless you have a valuable/deliberate reason to use and in your condition statements, I recommend consistently using &&. Condition logic can sometimes fall prey to unintended "precedence" complications. This whole line is "jacked" (wrong / incorrectly coded): if ($this->ValidateDate($testdate[0], false) && \$this->...

Top 50 recent answers are included