New answers tagged python
1
vote
Integer field in Python with extra constraints (Testable class)
Am I missing something in my class?
I'd say the most important thing missing here is a set of unit tests. Including good tests will help your readers understand expected behaviour better than prose ...
2
votes
backward induction algorithm computation
Your typehints are incorrect: current_reward etc. are np.ndarray (the actual runtime type), not ...
2
votes
Integer field in Python with extra constraints (Testable class)
negated identifier
def is_not_factor( ... ):
Reasonable people will differ on this point,
and that's fine.
But I'd prefer to call into a Public API
with the name <...
1
vote
Class for validating code in different Conda environments with PyTorch
The previous answer was thorough, but here are some additional suggestions.
DRY
Your LOGGER info and ...
3
votes
Class for validating code in different Conda environments with PyTorch
version hardcodes
To dry
up run_test_old_and_new_code(),
it looks like we want a helper
that accepts a version number
such as ...
2
votes
Calculating frequencies of each obs in the data
One of my main concerns is how to limit the amount of opening and closing of files
59 columns by 4400 rows by either 4 (single) or 8 (double) bytes is anywhere from ~1-2 MB. (This is a wild guess ...
1
vote
Script that logs chat data from Twitch.tv
Do you believe it's critical to adhere to the line length? I was
seeing mixed opinions of 'yes absolutely' and 'no just make sure it's
consistent and readable'?
Make sure it is readable.
In ...
2
votes
5-element clipboard for copy+paste
Mostly this looks good.
It's easily understood.
currying
...
2
votes
DFS implementation for 8 puzzle
Indentation
The code uses inconsistent indentation, and single-space indents make the code
very hard to understand. The black
program can be used to automatically indent the code with a more ...
1
vote
RC Plane Radio using the Raspberry Pi
Indentation
The code uses inconsistent indentation, and single-space indents make the code
very hard to understand. The black
program can be used to automatically indent the code with a more ...
1
vote
5-element clipboard for copy+paste
Simpler
These lines:
if pos < 0 or pos >= len(curr_queue):
return
copy(curr_queue[pos])
return
can be simplified as:
...
7
votes
Repository with SQLite in Python
Your code can benefit from a TypedDict or two.
Consider this assignment:
...
6
votes
Repository with SQLite in Python
Since I use SqlAlchemy with SQLite, here is my personal fix using SqlAlchemy events, basically these are hooks.
My models.py looks like this:
...
2
votes
Tarjan's Strongly Connected Components finding algorithm
Please point out any ... code style issues.
Certainly.
Layout
The code could use some breathing space in terms of blank lines between functions.
The black program can be used to automatically ...
10
votes
Accepted
Repository with SQLite in Python
We're using black, isort, ruff, and type checkers -- terrific!
Lots of best practices in ...
1
vote
AI learning to drive (simplistic)
UX
The GUI looks great.
You should remove all the print statements from the code. You probably used them in development,
but all the output to the shell is ...
4
votes
Calculation of clustering metric in Python
This is interesting, and by some miracle the sample dataset is still accessible.
Kullback-Leibler divergence
The entropy() calls aliased as ...
3
votes
Combining CSV files of simulation results
I am using Python 2.7.
Don't.
k() first of all needs a better name, among other reasons because you have local variables floating around that are also named ...
2
votes
Custom Day of the Week Manipulation
The code doesn't run because the current version of Pandas sort_values needs to accept booleans for ascending. (But those can be ...
2
votes
Accepted
Telegram userbot in python
pre-compiled regex
Your complaint is that response latency is high.
It's unclear how many milliseconds "high" is,
and what the target value after refactoring would be.
need to speed up its ...
1
vote
Read/write data structure + byte
Unused
ruff
identifies some unused code.
These lines can be deleted:
import numpy as np
import sys, string
count = 0
realsize = len(bytearray(byte_list))
The ...
4
votes
Weakly-Referencing Tree Structure in Python
Since you are on 3.12+ (with perhaps no intention of supporting older versions), you should use the new PEP 695 syntax. The old way (e.g., TypeVar, ...
3
votes
Python BeautifulSoup - preparing HTML rows and td tags for Pandas
Should I be dropping the columns before importing to Pandas or add extra column names in the header before importing to Pandas and then unwanted dropping columns?
Whereas Pandas technically can carry ...
5
votes
Accepted
Weakly-Referencing Tree Structure in Python
First impressions: we're using black, isort, and type checking.
Outstanding!
lint
nit: mypy ...
2
votes
Battle-based snake game in tkinter
tkinter imports
The following line unnecessarily imports many unused items:
from tkinter import *
It is common to use the following:
...
1
vote
Scraper to grab publicly available data
memory footprint
but it takes almost 6gb of memory
When the size of a pandas or polars data frame exceeds physical RAM size, almost always the appropriate direction to head in is to serialize that ...
3
votes
MCMC Metropolis Hastings for German Tank Puzzle
Imports
This line is repeated twice:
import matplotlib.pyplot as plt
Keep the line at the top, and delete the second one.
The ruff tool
also identifies these ...
1
vote
Scraper to grab publicly available data
Layout
Move the functions to the top after the import lines.
Having them in the middle of the code interrupts the natural
flow of the code (from a human readability ...
2
votes
Tic-Tac-Toe Backend for Commercial Use
Clearing the Screen
The code is very heavy-weight:
def cls():
os.system('cls' if os.name=='nt' else 'clear')
It is spawning an entirely new process to clear ...
2
votes
Tic-Tac-Toe Backend for Commercial Use
These definitions seem to be specific to ANSI terminals:
...
2
votes
Tic-Tac-Toe Backend for Commercial Use
UX
When I run the code, I see this:
Y-Coordinate Of Move:
I understand that it is prompting me for something,
but I don't know what to enter. I'm not sure how
a &...
1
vote
Uploading captured video to Google Cloud Storage
DRY
Nearly the same code is repeated 8 times, with only a variable name difference:
uploader1 = GCSUploader()
uploader2 = GCSUploader()
// etc.
I think an array in ...
2
votes
Simplified Smart Rockets using Genetic Algorithm
UX
When I run the code, I don't always see the value for "Generation" printed in the GUI.
It is sometimes clipped at the right edge of the screen. It would be better
to move it to its own ...
7
votes
Python OOP game of Hangman
Efficiency
You have several opportunities to make your code more efficient and Pythonic:
Where you have:
...
8
votes
Python OOP game of Hangman
Comments
Delete all commented-out code:
#print(new_word.word)
Simpler
The variable named position is unused:
...
2
votes
Filling values for nested dictionaries
Unreachable code
Since the 2 elif conditions are the same:
...
5
votes
Reading a webpage for its list of sites, but getting only the sites I want
This code is hard to test, since it depends on an external web server that's not under our direct control. It's better to separate the retrieval from the processing so that we can reliably and ...
7
votes
Reading a webpage for its list of sites, but getting only the sites I want
from urllib.request import urlopen, Request
Normally people instead use requests (or another 3rd party library) as such tools ...
4
votes
Finding combination of coins that can produce a given sum
As @kyrill says, creating all possible combinations is a problem. You should rework your algorithm so that it only ever chooses one combination.
I also think you should rework the representation of ...
1
vote
Finding combination of coins that can produce a given sum
Documentation
The PEP 8 style guide recommends
adding docstrings for functions.
...
1
vote
Customizable Multi-Agent Predator/Prey Simulation
DRY
In the following code, .33 and .66 are used twice each:
...
3
votes
HackerRank challenge: Box Operations
This is a review of the C code only.
Missing includes of <math.h>, <stdio.h> and ...
1
vote
Getting Graph and Block Animation to Run Smoothly Together
Documentation
The PEP 8 style guide recommends
adding a docstring at the top of the code to summarize its purpose.
It also recommends adding docstrings for functions.
You could convert the comments to ...
2
votes
Fully Constrained Least Squares (FCLS) Linear Spectral Mixture Analysis Method
DRY
There is a lot of repeated code.
For example, this directory path is repeated several times:
I:\MODIS_Processing\sma_block
You can set it to a constant, then ...
3
votes
Accepted
Merge two DataFrames with key over-write
Your terminology should be modified a little to conform better to the Pandas documentation: "keys" are really just the index.
Your function has a confused idea of in-place versus out-of-...
1
vote
Accepted
Follow up - Deep Learning Project for House Plant Identification on Kaggle Notebook
In function train_step:
for images, labels in dataloader:
images, labels = images.to(device), labels.to(device)
it seems ...
4
votes
Interpolating based on non-diagonal neighboring values
As one of the points brought up was insufficient dependency management, you were probably expected to deliver at least a requirements.txt, possibly and probably ...
2
votes
Optimization of startswith, list intersection with duplicates and substring search
You can replace your function signature with
...
Top 50 recent answers are included
Related Tags
python × 15565python-3.x × 5183
performance × 2366
beginner × 2002
python-2.x × 1232
algorithm × 1206
programming-challenge × 1039
numpy × 753
object-oriented × 725
pandas × 598
game × 543
strings × 489
web-scraping × 430
time-limit-exceeded × 396
tkinter × 351
parsing × 322
django × 306
csv × 304
hash-map × 295
random × 253
pygame × 246
recursion × 245
file-system × 236
regex × 234
reinventing-the-wheel × 225