New answers tagged

5

Don't use bare except statements. Under nearly all conditions, you should specify some kind of Exception; otherwise, even low-level exceptions (like SystemExit or KeyboardInterrupt) will be caught. try: ... elif players_turn == 'q': sys.exit() except Exception: # Just catch garden-variety exceptions, not low-level. ... Global ...


4

Use a collection rather than spawning lots of similarly named variables. Anytime you find yourself creating a bunch of numbered/lettered variables, stop and figure out a way to put that information in a collection. If your data is smart, your code can often be simple. Applying limits when collecting data by type. You appear to want to control the number of ...


2

I noted the use of the := operator aka walrus. That means your code requires Python >= 3.8 so consider adding a guard to make sure this requirement is satisfied. Since you are aiming for recent versions of Python you could as well "upgrade" to a data class that will make your code more concise. Thus you could declare your class EMail like this: ...


3

Solid work. One thing you might consider doing is taking all of your program and wrapping it into a main() function. Then, at the bottom of the script, you can call the main() function in order to simplify the look of your code. def main(): pass def turn_generation(): pass main() Note how this simplifies the overall readability and makes it more ...


1

When possible, iterate directly over collections. Most of the time, you don't need indexes when iterating over Python collections. As an example, here's an easier way to initialize an independent copy of the matrix. (Or just use deepcopy). rotated_matrix = [list(row) for row in matrix] Put all code inside of functions or methods. Some will say it's alright ...


1

I'm not sure I understood the problem you're trying to solve, but instead of writing: class FooJSONMixin: @classmethod def from_json(...) -> 'Foo': ... I wanted to point out that you can do: from __future__ import annotations from typing import TypeVar, Type class BaseModel: ... ModelT = TypeVar("ModelT", bound=BaseModel) ...


3

As other answers already pointed out, you should not compile call re.compile several times, and there is no need to try to filter according to all filters at the same time. I would go even further and suggest to use iterators, which are great tools in Python. It would allow you to write a single function per filter, and apply a bunch of function to each ...


2

FMc put it well in his commendable job: Your code is reasonable. My main gripe: The code does not document what it is to accomplish. The Style Guide for Python Code cautions Comments that contradict the code are worse than no comments. - to which I'd add where the code is right. (One might with no less justification state code that contradicts correct ...


2

Add a main guard This is a standard idiom: if __name__ == '__main__': n = int(input("Enter size of the square matrix: ")) matrix = [[int(input()) for j in range(n)] for i in range(n)] print("original matrix --> ", matrix) print("rotated matrix --> ", get_rotated_matrix(matrix)) This allows your definitions ...


3

Your code is reasonable. The primary advice I have focuses not on anything particularly wrong with your current implementation but on simpler ways to complete the task using the standard library. The first part of your function assembles the data into triples, and you're on the right track in the sense that you are sorting the data by user ID. But you can ...


4

A data-oriented function should return data or raise an exception, not print. If there are no matching stacks, just return an empty list or raise. Establish a habit of defining regular expressions with raw strings. If you always define regex patterns with raw strings, you never have to waste time thinking about whether your pattern contains things like \n, \...


2

PEP 8 The Style Guide for Python Code recommends snake_case for function names and variable names. findEarliestMonth violates this, but it is a requirement of the assignment, so it gets a free pass. stockPrices however should be stock_prices. You already changed the name from stockPrice, making it plural, demonstrating that while it was a name provided by ...


1

Here, I shall work with the assumption that the "playing sound" part works fine. Firstly, congratulations! The concept you came up with to resume the execution of the recin function is known as a continuation, and it is available in Python natively through generators and the yield keyword. Rewriting your code to use generators and still polling the ...


5

Simplifications re.compile("(nonprod|non-prod)") is just a complicated way to write a badly performing regex for re.compile("non-?prod"), which does the same, but better. extract re.compile("all") into a variable like you did with non_prod_regex, or better yet, do a string comparison: if environment == "all"... ...


3

According to your code the first optimization that came to my mind is to group your if statements by the variable accounts_ids like the next example if accounts_ids: if non_prod_regex.match(environment): do.... elif re.compile("all").match(environment): do.... else: do... else: ...


1

Your current implementation is reasonable and understandable. There are probably "clever" ways to solve it differently or with fewer lines of code -- I even wasted some time on one of them -- but I'm not sure they are worth it, other than for fun. Some notes on the your implementation. (1) Python has a built-in sum() function, so you don't need to ...


5

Your data structures are a jumble, especially the inner lists. Before worrying about your code, I would encourage you to rethink the data structures. At the outermost layer, you have a dict mapping dates to lists -- so far, that's reasonable. Those outer lists contain inner lists, which consist of a string (eg "Mesure 1") followed by two dicts ...


2

a down and dirty solution. Itterate the dict and use the key to index the dict. pass that into a function -> compute the return a more complete solution using list compression rather than using append you can nest multiple loops into a single line, index the object and pass that into a function to perform some logic operation. def compute(cval): ...


9

PEP8 You should use snake_case for function names. You did so with ip_information, why not with to_binary as well? Naming The function name ip_information does not convey what it precisely does. You might want to rename it. Docstrings Both of your functions are excellent candidates for docstrings to describe what they are supposed to be doing. Use existing ...


2

Separate, small comment, would be the formatting for multiple-line imports. Most recommendations are to not use \ to extend lines, but group via an expression syntax, which will automatically extend over lines if not yet closed: # not recommended: from AModule import \ a, \ b, \ c # recommended: from BModule import ( a, b, c )


-1

Depending on your bigger needs/situation another, completely different, approach you could take is just parse the entire string using regexp's. So conceptually you're just looking for patterns in a string, ignoring the fact it's json, and any data structure/hierarchy contained within. However, for you needs it may fit perfectly, or it may be completely in ...


5

I don't find PerfCounter to be well-modelled as a class. start and end aren't valid on construction, which should be a red flag. The current contract also allows for the calling user to initialise start and end themselves, which doesn't make sense; so even if this were to be modelled as a class it shouldn't be a @dataclass. The more natural calling pattern ...


0

First some problems. (1) Your tokenizing function tries to accomplish the task character by character, but that fails if any operators are multi-character. (2) The tokenizer fails if the input string contains spaces, which seems user-unfriendly. (3) Because it returns the hard-earned results as an non-delimited string, the infix-to-postfix conversion ...


10

At a wild guess, it seems like you want to perform a flattening operation. Your current code definitely hasn't done it correctly, and it's not even clear what "correct" is; but if you replace your loads with a load; use a with on your file; get rid of all your numerical indices, and use a nested list comprehension on your dictionary, you can ...


5

I was trying to implement an efficient (in terms of size of code and time and memory-efficient) of Infix to Postfix in python without the use of any modules and with only necessary parts (such as without class). First of all, there is nothing intrinsically bad about classes. You should feel free to decide between object based programming or not based on the ...


3

Quick improvement*: put your code through an automatic formatter. Python has a guideline called PEP8 which gives recommendations on where to put linebreaks, spaces, how to name things consistently. I use black to format code since it is PEP8 compliant and does all the decision making for you so you can focus on more important things (it doesn't do everything ...


7

If a function just calls another function, delete one of them. You don't need both main() and testing(), since the former does nothing other than call the latter. Global variables are almost never needed. Don't organize programs around the need to modify global variables. Instead, organize your programs around functions that rely only on their local ...


7

Currently, you have print statements mixed throughout your game logic. I would suggest separating your code into the part that decides what to do with the latest input, and the part that prints a summary of what happened. To do this, you can replace your prints with properties on a game state object. By extracting a GameState object, you can also replace ...


1

Apart from the existing suggestion to raise errors (I've stuck with AssertionErrors to keep things simple for now), I noted three points of interest: the string padding was explicitly coded twice, we can DRY the difference between two sorts as shown below, and itertools.count provides a better option than a while loop that manually increments: from itertools ...


1

Let's start with some conventions. Class definitions typically have two leading whitespaces before them and two after. Uppercase variables generally means it's a global variable. Single letter variable names can occasionally be fine, but I'd only use it if it relates to a known mathematical formula, and I'd want that formula kept with the code somewhere; for ...


3

I've never seen anyone use a dictionary for argparse before, and as such it throws me somewhat off. What is reasonably standard for larger sets of arguments is to have these defined in a separate function (like your make_parser one). You're kind of limiting yourself, as can be seen with the boolean argument; imagine how complicated it would become if you ...


2

I am not convinced, that using dicts to initialize the argument parser is sensible. Do you need the dicts anywhere else? If not, why not just pass the data in the dicts to the argument parser's methods directly, i.e. why have them in the first place? But if you insist on doing this, you can use dict unpacking to remove unneccessary code: ARGUMENTS = [ { ...


3

Argparse is a pretty object-oriented API, so I'm not going to test any of this bc/ that would be a chore. Sorry. Are you/can you use MyPy? I'm a big fan of type-checkers in general, so if you're using one that's great! But (python being python) not everything I'll suggest can necessarily work with MyPy. Bullets: What does "Ronseal." mean? The ...


1

What you requested advice on LinkedList.insert You probably want to do your boundary-checking as the first thing, before any manipulation. This is not very easily readable in my opinion: prev = None cur = self.head # insert between prev and cur idx = 0 while idx < pos: prev = cur cur = cur.next ...


1

The name of the game is reduction of redundancy. You can already tell that your three rounds have many, many aspects that are identical. You can reduce this to one function with the right parameters and lambdas. Move your Are you ready? Y/N prompt into the input call. Take advantage of the else statement, or early returns, instead of restating the negative ...


2

Get a book Tutorials are fine to get understanding of what your behavior should be while coding (this is important too); but to know what to code you should read books. And manuals too. How about "Head First Python"? Unneeded pieces of code print("Are you ready? Y/N ") decision = str(input("")) Here, you're asking user to input ...


2

Don't repeat yourself def run_non_essentials(self): """ Run the installation processes. """ result = True print("Installing Google Chrome...") if not self.install_google_chrome(): self.failure_log.append("Install Google Chrome") result = False ...


3

I stuck with the book's methodology since it already provided much of the code except the block but I incorporated the default sum method in my block so I don't have to create a global variable set to a false-y value. I used the f'string so I could easily print the keys and values in the required format rather than use the pprint module. Inventory_List = {'...


3

The nuclear option it's necessary to wipe these devices every so often - sometimes as frequently as multiple times per week Having a script like this is useful, because reproducible environments are useful; so long as you're not relying on it to cover over other problems. Your two scenarios: At work: we were manufacturing embedded Linux devices, and we ...


4

I mean to say this in the gentlest possible way, but from top to bottom this is a bad idea. It would take a more detailed explanation of why this creature exists to convince me otherwise. Your default callback produces some pretty crazy results: ^ and 1 both evaluate to False, for instance. A critical step in security is to limit DOS potential by ...


4

To test whether the libraries do what you would expect simply create a very simple dataset (e.g. y = 2x + normalerror) which OLS should deal with without any issues. From my understanding of the documentation, what you call "accuracy" here (sklearn.linear_model.LinearRegression score method) is R2 calculated using data out of the training set. With ...


2

Comments above aside (this precision seems unnecessary), since you have a fixed precision you're better off operating in integer math. Numpy's uint64 will not be enough to hold a sum of millions of 18-digit integers, so use Python's built-in arbitrary-precision integers instead. You jump through a lot of hoops to convert your grouped sum to a column for each ...


4

Caching your MD5 hash is premature optimisation, and indeed there are more important things you should be caring about. For instance, you're serialising JSON twice; instead you should use a Requests prepared request that does the serialisation once. Even this is insignificant in comparison to the time in flight on the network. I don't know that __all__ is ...


3

CLI-program feedback You have used argparse. This is ok, but very basic. There are at least two options that are way easier to read and write: typer and click. Click comes from the Flask ecosystem and is battle-proven. Typer is rather new and in the pydantic ecosystem, but makes excellent use of type annotations. This makes it super easy to read. I try to ...


0

Comments should not repeat what is already obvious from the code. Here are several offenders from your current comments: class MyHTMLParser(HTMLParser): # Define a new html parser # Initialize tense self.tense = tense # Initialize tag list with verb self.tag_list = [["verb", verb]] for attr in attrs: # Loop through attributes elif attr[1] == ...


0

First of all well done - it works! I went through and made a few edits to your codes, making notes as I went through. I hope this is useful. Comments and style I don't think you need the comment # Get packages above your import statements. These statements will appear in every Python module you ever write, so save yourself the trouble. You can assume the ...


1

In addition to @FMc's answer, I noticed some further issues with my code. Recursion vs. iteration On large mine fields with few mines the program raises RecursionErrors due to the recursive implementation of visiting neighboring fields with no surrounding mines. I fixed this upstream by using an iterative approach instead: [snip] def _unvisited_neighbors(...


5

Your code is thoughtful and well organized. The user interface is needlessly burdensome. By far, the most common action is visiting. Don't make the user type "visit" every time. Similarly, users would appreciate the ability to abbreviate the action. With a couple lines of code you could easily support inputs like the following: visit 1 4 # ...


4

When writing tests, try to break things. It's excellent that you are writing tests. One purpose of testing is to probe your code -- and the plan behind the code -- for weaknesses. For example, what should the function do in the following circumstances? In some of these situations, your code raises an error (somewhat legitimately in the first example, less so ...


1

If you truly do not want to use strings, this could be done mathematically by determining the number of digits in the integer, which can be done with a simple while loop and counter, dividing the original number by 10 until it is = 0. Using this length, a series of operations (num // (10 ** pos)) % 10 is done to isolate a the value. Note you will have to ...


Top 50 recent answers are included