New answers tagged

3 votes

Sudoku Solver in Python Using Backtracking

PEP-8 PEP-8 is the standard style recommendation for Python. In it, it includes things like how many blank lines, how much indentation, recommendations for variable naming and casing. There are ...
1 vote

Sudoku Solver in Python Using Backtracking

Simplify Logic b calculation (get rid of un-needed logic/variables) ...
  • 748
1 vote
Accepted

Getting and setting dict items via paths

Overview The code looks good, properly typed, tested. This is a great starting point. Here are various details can could be improved. Documentation Your code could definitely be improved with ...
  • 29.1k
-1 votes

Block storage rewrites

...
  • 1
7 votes

Check validity of string, used return False too often? (CS50 plates.py)

A function with several returns is not necessarily a problem. Early returns are often called short-circuiting and they can be effective in keeping code readable: the intuition is to handle easy checks ...
  • 11k
1 vote

Mapping pandas' Series to dataclasses

Looks very pythonic to me. Thumbs up, LGTM, ship it! Ok, fine, I have a few minor remarks. Maybe the Any annotations could be finessed a bit to be more informative?...
  • 9,030
1 vote

Rewritten Python script to split Insyde H2O firmware files

Make you api easy to use and hard to misuse. Right now, your Splitter class requires a lot of initialization to be used. You have to first call ...
13 votes

Check validity of string, used return False too often? (CS50 plates.py)

def is_valid(s): You're not giving us many hints, there. What is s? What kind of validity criteria? As an engineer, why would I ...
  • 9,030
1 vote

DDD architecture pattern

To expand a bit more on the other answer: Does it make sense to use an ORM for a DDD project? Yes, it's pretty common to use an ORM in a DDD project (pretty common = I am sharing my personal ...
1 vote

iChemistry - Learn chemistry with python

Element and simple data classes like it should be modelled by something that is immutable - a properly configured @dataclass, or ...
  • 55.5k
5 votes

iChemistry - Learn chemistry with python

compund.py It looks like your Compund is not doing any business logic, so it would make sense to define it as a dataclass (or a pydantic model, which has benefits ...
  • 151
2 votes

Get list of dates that are the last day each month in a date range

General iter_completed_months is a poor name for a function that doesn't iterate over the months or return an iterator. The function returns the number of months in ...
  • 9,525
2 votes
Accepted

Get list of dates that are the last day each month in a date range

Put your code in functions. The benefits are numerous. Even if you don't appreciate them fully yet, you should do it anyway. Stand on the shoulders of the computing giants, who knew that functions ...
  • 11k
2 votes

Get list of dates that are the last day each month in a date range

Fixing your ranges, and making the function iterable This function name implies it is iterable, when it isn't. To make it iterable, it might be better to yield each ...
  • 2,482
2 votes
Accepted

How to better write this Python String manipulation

When parsing, attach meaningful labels to important markers, dividers, etc. Your code is littered with magic strings that drive the parsing logic. But those raw strings don't mean anything to a reader ...
  • 11k
1 vote

Graph function in console

Ok, there are a few things to unpack here, so I'm not going to do a full refactored code summary at the end, but here are some things to be aware of. PEP-8 PEP-8 is the standard style recommendation ...
1 vote
Accepted

Fully-functioning chess game in Python

Don't build everything on top of primitives. Your current code is carefully done and not difficult to follow. Its primary drawback is that nearly all of the logic operates on primitive data types: ...
  • 11k
1 vote

Fully-functioning chess game in Python

I like @tzaman's suggestions, especially dataclass. Here's a code organization detail: bury methods like get_color within the ...
  • 9,030
1 vote

Fully-functioning chess game in Python

Not exhaustive by any means but a few quick pointers: Instead of constructing bidirectional dictionaries for files, you can just use a string with normal indexing and lookup. And instead of having an ...
  • 411
4 votes

Create a list of all words in a string, the length of a word preceding it if even

Make the code simpler first. You question is an important one: how does one take a complex process in a computer algorithm and describe it in terms that are readily understood? Most software engineers ...
  • 11k
4 votes
Accepted

Making a game using python and pygame

It looks like you're actually mixing a few unrelated things here. Consider: how many of these are actually settings? That is, how many of these does it make sense for the end user to modify in some ...
  • 8,832
1 vote
Accepted

Poetry Web Scraping in Python

One thing that immediately jumps out at me is the fact you set num_processes = cpu_count() for the multi-processing pool. The absolute maximum I would recommend is <...
1 vote
Accepted

Counting Ads in webpage using XPath and EasyList in Python

You are apparently using this library: https://pypi.org/project/cssselect Measured time to process a scraped page is ~ 10 seconds, and we wish to reduce that. There are so many essential details left ...
  • 9,030
1 vote
Accepted

HTTP scraper for Python Package

I tend to be pretty happy with requests defaults, but I imagine you need specific retry behavior, so I won't comment on that. ...
  • 9,030
1 vote

Fourier Series of a given function

You have really clean code, I can only suggest a few improvements: The functions a_k and b_k have a quite long line, I suggest ...
  • 27.3k
2 votes

URL link scraper and analyser

We're calling retrieve_links_from_html() for every resource we retrieve, regardless of its content type. That surely can't be right. We should be using a ...
  • 67.7k
8 votes
Accepted

Fourier Series of a given function

I like it. This code hews closely to the underlying math, using lovely identifiers, and is very clear. For {a,b}_k, here's the only part I'm not super happy with: ...
  • 9,030
1 vote

Test generator I made for practice

Namespacing You have test_generator and test_dictionary. It might be better to put these in one package, so they're ...
  • 323
2 votes

Built a function to search a dictionary using key or value

Use proper naming The name get_children_if_parent is a bad name on two counts. Your function does not return a list of children but all leaf nodes in the tree that ...
1 vote

Wordlist formatter code

Follow the single responsibility principle Your WordListCleaner class is doing too many things. It is in fact not just a word list cleaner but also a word list file ...
4 votes

Test generator I made for practice

test_*.py is a bad name for the file. As per convention test_*.py files are for unit tests. A better word would be 'quiz'. There ...
0 votes
Accepted

Detecting timeouts in a stream of events

Here's a O(n) solution using just a dictionary: ...
0 votes

Optimize this Python Code

A few improvements I could see, which you could implement to handle such large datasets and speed up the program, are vectorized operations so it should perform on the entire dataframe at once. You ...
1 vote

Optimize system of equation function organizer with memory bottleneck in python

The original post asserts that sys = np.empty_like(v) takes significant time. I find no evidence for that, in the OP nor in these tests: (See new timing ...
  • 9,030
1 vote

A simple web scraper for nature.com news articles

...
  • 9,030
2 votes

password crack dictionary

Idea review That's 100 different characters repeated 8 times, i.e. 100^8 or 10000000000000000 different passwords or 10000 Terabytes. I guess you can't really make that faster. Even with really fast ...
6 votes

Built a function to search a dictionary using key or value

Just a few minor suggestions to simplify the code, lighten its visual weight, or otherwise enhance readability. Prefer normal language when feasible. If a regular word like ...
  • 11k
1 vote

Built a function to search a dictionary using key or value

I reworked my previous solution. It may, if your use case supports it be beneficial to flatten the data structure and include an all field. ...
5 votes

Built a function to search a dictionary using key or value

Work in progress Useless accesses to parent_dict You iterate over the keys of parent_dict and then retrieve ...
  • 29.1k
2 votes
Accepted

Reduce a list by filtering out repeated elements

The two programs are pretty similar, just that the first skips data[0] by catching an exception, whilst the second does it by slicing it off the input. In both ...
  • 67.7k
4 votes

Reduce a list by filtering out repeated elements

Put your code in functions. Among other benefits, it's easier to test that way. Consider using itertools.groupby. If given no key function, it organizes the data ...
  • 11k
6 votes

Find the shortest distance between two letters

You don't need list.index(). Just compute the difference between the two ord() values. You don't need to worry about ...
  • 11k
4 votes

Find the shortest distance between two letters

I think there are some things that become easier, if you directly transform to the indices and use Modular arithmetic. If you look at the definition of modulo % (in ...
  • 944
1 vote
Accepted

Fixing math library functions in Black-Scholes options pricing model

Would this be the method in solving this issue? No. You seem to reporting that some narrative discourse in a HTML web page omitted an obvious from math import log ...
  • 9,030
1 vote
Accepted

Finite difference estimation of partial derivatives for arbitrary grids in python

As @J_H said. This is not properly answerable in its current state, but as a review of the code and standards. Split your code into simple functions Instead of having your methods all in a block in ...
1 vote

A simple stock exchange app

Some good things - you use env vars, you use requests and check the return status, you use the datetime module. os seems unused so remove it. Don't bake query ...
  • 55.5k
4 votes

Calculate overlap of two datetime objects

Set up your code for ease of testing. This is useful both for your own debugging and when asking others for help or code review. Instead of writing an English paragraph giving us example inputs and ...
  • 11k
5 votes

Mini project #2: Guessing a number loop

Handling input well is hard: guess = int(input("What do you think my number is? ")) Try this a few times, and see what happens if you enter something ...
  • 67.7k
10 votes

Mini project #2: Guessing a number loop

The reason you need the break statement is that the variable guess is never modified after the user's first input. If you ...
  • 1,940
3 votes

Mini project #1: Weight Converter

There's nothing wrong here. But it will take some practice to craft more mature code. The whole thing is at __main__ top-level. Consider ...
  • 9,030

Top 50 recent answers are included