New answers tagged

0

Pythonic. Zen of Python. Idioms of Python. input() returns a string. int(str, base) returns an integer with the base of the given value (2 <= base <= 36) enumerate(tuple) allows for indices, is fast (because it doesn't need to make a new list). while 0==0: is ugly. while True: is infinitely more beautiful. print('user instructions') print('Please don'...


4

Welcome to Code Review and welcome to C++! Let's go through the code and see what can be improved. In C++, the headers of the form <xxx.h> are deprecated, which means they should not be used. You are recommended to use #include <ctime> instead of #include <time.h>. using namespace std; is considered bad practice because it causes name ...


4

Welcome to the wonderful land of computer programming! There are a few things you could do that could help clean up that code. However, if this is for a class, I would recommend not to add functions, make sure the player is giving a valid safe input, and avoiding namespace issues for future development. But if it is for a class, here are yet a few Where ...


2

PDF specification ISO 32000-1:2008. Funny, that's a roughly 800 page document if I see that right :) You might want to link to relevant parts if you want a reader to read it, otherwise that doesn't really help with the review here. The refactored version has less nesting, yes, so that's somewhat easier to read. However I've the feeling that the extracted ...


1

The stuff with counter_one and counter_two is rather oblique, and it seems that it would break if someone were to choose the same password as someone else (or username, but you do have safeguards against that). If I understand what you're trying to do correctly, you could just do account_match = any([(f"'{user_name}'" in line) and (f"'{password}'" in line) ...


10

Positive Changes getReader() is only called once, while called multiple times before. there are more early exits as before, which results in less nested and lesser deepened nested statements method getPdfStreamUf hides the fallback method away from the main method, this functionality deserves its own method Negative Changes I agree with the developer that ...


3

I see two race conditions. When you write the file, two processes may write it at the same time and one entry will be lost. Between reading the user list and adding a new user, i.e. in the time when the user chooses a password, another process could add the same user, so the user is added twice even when you checked that the user is not in the list when ...


3

A couple of things: Any time you have a function which could fail, it should return an Option<T>. Ask yourself, if someone calls convert_to_hex_from_binary("foobar") and gets back "", is that reasonable? They will need to manually check that their input makes sense, or that the output makes sense every time. Static checking of these errors is part ...


3

The "terminating" allocators work well for small programs like this; in larger projects or libraries, we want to do something better than terminate the program when allocation fails. A common naming scheme (perhaps taken from Perl) is malloc_or_die() - that's slightly clearer about the behaviour. It's usual to end your error message (and indeed program ...


2

Instead of creating an empty list and appending the values to it, try using list comprehension. so instead of y_location = [] x_location = [] for each in range(-size, size+1): y_location.append(parabola(each, size)) x_location.append(each) try y_location = [parabola(each,size) for each in range(-size,size+1)] x_location = list(range(-size,size+1))...


1

This code looks good. There are only a couple improvements I would suggest. Loop over operations The code is somewhat repetitive for the operations, which goes against the Don't Repeat Yourself principle. Those operations could be added to an array and iterated over. You might have to get creative with calling functions but the operation functions could be ...


10

Welcome to code review, and good job for your first program I suppose. Style Docstrings: Python documentation strings (or docstrings) provide a convenient way of associating documentation with Python modules, functions, classes, and methods. As you can see, even for a relatively simple function, documenting using comments quickly makes it unpleasant and ...


9

Your app function is just the same as the print function. So there is no need for it to exist at the moment. When working with files you should always use the with keyword to ensure the file is properly closed (even in the case of exceptions). The pathlib module has a Path object which makes handling file paths a lot easier. You are doing a lot of ...


4

As a preface: Your code works good, is readable and does its job efficiently. The following review, though long, doesn't mean there is anything substantially wrong with it :-) General comments In the constructor, you're binding the event handlers to this. However, since you declare these event handlers as arrow functions, they are already bound to the ...


3

We can simplify this quite a bit. At a high level, note that all you are doing is: Converting each digit of the input to an array of possible neighbors. Now you have an array of neighbor arrays. The answer is simply the cartesian cross product of those neighbor arrays. Sort them. Turn the into back into strings. The cartesian cross-product is a simple ...


2

Early returns are OK. if (args < 4) { printf(....); return; } .... emphasizes where the business logic is. The condition (c = **++argv) != '\n' looks sort of strange. It is indeed possible to embed a newline in an argument, but it doesn't warrant a special case. It is just one way to malform an argument, and there are plenty of them. c = d; does ...


5

Unfortunately, there is at least one blatant issue with the program in its current state: unused arguments. Let's have a look at it and find out why that's important. Before that, a short disclaimer, though: I'm not a F# developer. However, I know functional programming (e.g. Haskell). I don't know the .NET lands by heart. Take this review with a grain of ...


1

Avoid trying to combine assignment and compare in the same statement. The cast within the statement makes it even hard to read. Also, handle EOF with getchar. You can get EOF with redirected input. Instead of this: while((ch = (char) getchar()) != '\n') { . . . } This: int value = getchar(); ch = (char)value; while (value != EOF and ch != '\n') { ...


5

Your first code snippet has the problem that (in Python 3) input always returns a string, so type(user_in) will always be str, which will never compare equal to int. Your second code snippet solves the problem in the correct way: try to convert the result to an integer, and catch the exception in case that fails. Fixing that code is as simple as adding a ...


0

There are a lot of ways to accomplish this, one of them is to use recursion. Where in you write a "function" which executes your code & when you hit a certain condition, the function calls itself - def myf(): user_in = input('Input an integer value \n') if type(user_in) == int: a = user_in # continue with whatever you need to do ...


0

Realistically, you would want to check that the input characters are acceptable to your program.


14

/* Asks the user for string input. * Returns a pointer to the string entered by the user. * The pointer must be freed. */ Slightly misleading in that this function doesn't ask for input. (As written it is not responsible for printing the prompt.) Perhaps also should clarify the intended behavior: If there is input that is not terminated by a newline, ...


2

This is really not bad at all. I only found a couple of things worth mentioning - run a linter which will tell you that you sometimes have too many blank lines inside of your function. Also, this: if not selected_values: message_profile = "Please add sequences to the cart" messages.success(request, message_profile) return redirect("search") ...


4

Welcome to CodeReview! I'll start by saying thank you for posting a somewhat-complex package of code. At first blush, your code appears to be written in the generally-accepted style and appears well organized and somewhat documented. Functionality Before I actually review the code, I'll point out that I tried to play the game. Here's my experience: Your ...


6

First, I like how you have everything spaced out instead of crammed together. I definitely prefer over-spacing to under-spacing. I think though, in a few places it's a little much. For example: if usr_inp[0] not in dict_pos.keys(): return False x = dict_pos[usr_inp[0]] y = int(usr_inp[1]) return x, y - 1 At some point, the spacing begins hurting ...


0

Since you are asking about PyTorch's capabilities you are not taking advantage of, you might want to use: torch.linspace(-10,0,300) instead of torch.tensor(np.linspace(-10,0,300)) torch.zeros(5, dtype=torch.long) instead of torch.tensor([0,0,0,0,0]) tensor operations instead of iterating over each element of the tensor in a loop. This might not matter much ...


2

Rustfmt is a tool for automatically formatting Rust code to the community-accepted style. Clippy is a tool for finding common mistakes that may not be compilation errors but are unlikely to be what the programmer intended. Rustfmt points out that you are using 3-space indents (Rust uses 4), and that some of your lines don't need to be split. Clippy points ...


-4

C++ Program To Implement Manchester and Differential Manchester Encoding encounters a bit as "1" then triggers "10". C++ Program To Implement Manchester & Differential Manchester #include<iostream> using namespace std; int main() { int n,bit; int bitstream[50]; cout<<"Assumption : 0 -> +ve and 1 -> -ve"<<endl; cout<<"...


2

Welcome to Python! "Project Euler exists to encourage, challenge, and develop the skills and enjoyment of anyone with an interest in the fascinating world of mathematics." Like you, I went to Project Euler when I was learning Python as yet another language for my toolbox. Unfortunately, Project Euler is primarily a mathematics challenge site, not a ...


1

Instead of the printTitle function which is less efficient def printTitle(): print "----------------------" print "----- MASTERMIND -----" print "----------------------" print "" Just save the title to a variable and print it out or make a new file and import the variable from it. title = """ ---------------------- ----- MASTERMIND ----- ----------...


2

Welcome to CodeReview! This isn't great code, but that doesn't mean that this is a bad question. I think that you've come to the right place. Recursion if color == "": print("No skipping!") print(check(input("Enter Name Here>>> "))) This uses recursion when it shouldn't. In other words, check is calling itself needlessly, and ...


0

tablename doesn't need to be a var, it's never mutated, and it appears to be totally unneeded. Use the method's passed parameter directly. column_stack is also unneeded. You can go directly from selectColumns2 to collist without an intermediate variable or dropRight() adjustments. val collist = selectColumns2.flatMap(e => Seq(s"'$e'",e)).mkString(", ")


8

For deserialization, its a lost easier if you use serde. Then you can do something like this: use serde_derive::Deserialize; // the Deserialize derive is provided by serde, it causes the code // to be generated that is needed for deserialization #[derive(Default, Debug, Deserialize)] // this tells serde you want to use kebab-case, which is // with dashes ...


1

Coding Style First, I'm not a code reviewer. Your code seems to be OK though. There are some basic coding conventions in writing Python scripts, such as variable naming, commenting, docstring, and such, which I don't go through it, since I'm learning myself, and you can find it here. Implementation There are a few things that hold a basic ANN not to ...


3

The first thing about your code are the two lines inside your class Thing: private Random r = new Random(); private int a = r.nextInt(), b = r.nextInt(), c = r.nextInt(); If Random r is used just to initialize the array and not in other methods inside the class , it is better to use it in the costructor of the class : public Thing() { Random r = new ...


1

Immediately I'd ask if there's any specific style guide that allows these vastly different names, otherwise I'd suggest following IDE hints and/or a linter and rename the variables and methods to be more consistent (e.g. [cC]amelCase for everything). Also, "stuff" is not a great name for anything ... what stuff are we talking about? In fact the first line ...


1

Advice 1: code packaging I suggest you put your Thing related code into a package. That way you may practice industrial level programming: package net.tnm; Note that the above package name is just an example. Usually, is should be reversed domain name of your company. (For example, package com.oracle.xxx where xxx is the project name.) Advice 2: code ...


4

The problem can be solved using math formulas, which will lead to an O(1) solution. But here I show another way to implement it, which is more efficient than a naive loop: def sum_multiples(n): return sum(range(0, n, 3)) + sum(range(0, n, 5)) - sum(range(0, n, 3*5)) Or alternatively, def sum_multiples(n): numbers = range(n) return sum(numbers[:...


5

The keyword sum is a built in function and you shouldn't name variables from within the reserved keywords. Here's a list of the most common used keywords which you shouldn't be naming any of your variables: [False, class, finally, is, return, None, continue, for, lambda, try, True, def, from, nonlocal, while, and, del, global, not, with, as, elif, if or,...


1

def change_letter(original, new_message, key_number, alpha): docstrings: Python documentation strings (or docstrings) provide a convenient way of associating documentation with Python modules, functions, classes, and methods.It’s specified in source code that is used, like a comment, to document a specific segment of code. You should include a docstring ...


1

Laziness is a programmer virtue. These folks are spending more time on theory than doing it the lazy way would take in practice. The big problem here is you're doing a bunch of unnecessary work, particularly around storage. You're constantly appending to arrays for no apparent reason. You don't need the history of old numbers. Throw them away. ...


1

Warnings You should always turn warnings on during development. Your code generates 6 warnings, all of which are easy to fix: test.rb:1: warning: parentheses after method name is interpreted as an argument list, not a decomposed argument test.rb:51: warning: mismatched indentations at 'else' with 'if' at 45 test.rb:56: warning: mismatched indentations at '...


0

A quick caution on the solutions proposed in other answers. The translation table approach doesn't work because it's answering a slightly different question. The REVERSE complement of ACGT is ACGT not TGCA. Because when you do a reverse complement you have to start by complementing item -1 then -2 etc. Rather than item 0 then 1 etc. If you run proposed ...


0

As 200_success says, you can look at how the numbers are derived to generate the numbers one by one. So rather than creating all the numbers and checking for an intersection, a simple algorithm is to look at a pentagon and hexagon number. If they are equal, you're done. If the pentagon number is larger than the hexagon number, then check whether the next ...


2

let If you use let, you ask Kotlin to create an invisible function with a parameter. 1.let { println(5) } //changes to: fun func(it : Int) { println(5) } func(1) Do you see the it? That's the name of the parameter. Therefor, you can use it inside let. 1.let { println(it) } //changes to fun func(it : Int) { println(it) } func(1)...


1

Python is a great choice of language for a challenge like this, mainly because of how easy it is to use sets. Basically, any challenge which states "find a number that matches these criteria" can be thought of as a set intersection problem. We want to find \$T \cap P \cap H\$, the intersection of triangular, pentagonal, and hexagonal numbers. Depending on ...


0

You can easily check that H(n) = T(2n - 1). So all hexagonal numbers are triangular numbers, meaning we can ignore the triangular numbers altogether. To compute pentagonal numbers: Start with p = 1, dp = 4. To get the next pentagonal number, let p = p + dp, dp = dp + 3. To compute hexagonal numbers: Start with h = 1, dh = 5. To get the next hexagonal ...


2

Am I using the "right" type for the Add subnodes (i.e. Rc)? No. You probably don't want to do that. Just use AST. Good Rust code rarely actually needs Rc. Instead of using Rc<> in the definition of AST, use Box. #[derive(Debug)] pub enum AST<T> { ConstInt(isize, Rc<T>), Add(Box<AST<T>>, Box<AST<T>>, Rc<T&...


0

(I wrote this months ago and forgot to post it, so it may no longer matter, but I'll post it anyway.) wordsArray is used for two different things. At first it's an array of words, but then it becomes an array of the words' values. This tends to be confusing, so it's better to use a new variable. The first loop in solution goes through a list and collects ...


12

As this is a simple text transformation, the regular-expression module re is your friend. Processing letters one at a time is h-a-r-d. It would be simpler to process things one word at a time, as suggested by @Carcigenicate. The re.sub(pattern, repl, text, ...) function is interesting in that it allows you to specify a string or a function for the ...


Top 50 recent answers are included