New answers tagged

1 vote
Accepted

Python CLI math game

I want to know if there are ways I don't know about to make it even shorter. Shorter isn't always better, and this is not code golf. Strive for good code, and the short code will come naturally as a ...
user avatar
  • 47.6k
1 vote
Accepted

Solution to arithmetic arranger from freecodecamp

Use PEP484 type hints. The too-many-problems and too-many-digits constraints are not good ones, but whatever: we'll keep them because the problem asks so. You call ...
user avatar
  • 47.6k
4 votes

Formatting a table using unicode symbols in python

First pass Good job in doing a first pass at type hinting! In the newest stable version of Python (3.10 as of this writing) it's no longer necessary to import List -...
user avatar
  • 47.6k
1 vote

Sampling from k circles with different radii

I don't have much to add to the answer of @Reinderien, maybe a slightly different solution. ...
user avatar
  • 1,339
2 votes

Sampling from k circles with different radii

Let's assume that your zip-shortest behaviour is intended. radii and centers should immediately be made ...
user avatar
  • 47.6k
3 votes
Accepted

Printing a JSON/HTTP response from a Cisco endpoint

Since this is the entire script, it doesn't need to exist and you can just invoke curl directly; and we can be a little more forgiving on exception-handling best ...
user avatar
  • 47.6k
1 vote

Call-flow graph from Python abstract syntax tree

Avoid from ast import *; ast is already conveniently short as a prefix to a fully-qualified name, and importing splat pollutes ...
user avatar
  • 47.6k
2 votes
Accepted

Text splitter using Regular Expressions in Python

Include spaces after commas. It's a virtually costless habit and it helps with code readability and editability. Constants are typically named with uppercase. Your program begins with several ...
user avatar
  • 9,475
0 votes

Find all pairs of natural numbers whose sum is 12

The spec is wrong, at least in its example data. There's one too many [6,6] and one too few [5,7]. The spec asks you to think ...
user avatar
  • 47.6k
0 votes
Accepted

Validator for 0/1 entries in a matrix

You already know the primary problem with your code: repetition. You have written reasonable code that is not difficult to understand. The problem is that you have four nearly identical chunks of code....
user avatar
  • 9,475
7 votes
Accepted

Wordle guesser, breaking out of loop by raising exception

Program structure The flow of control leaves a lot to be desired. Exceptions should be used for exceptional situations, not as a kind of break or ...
user avatar
1 vote

Validator for 0/1 entries in a matrix

Your operation is pretty strange and has lots of edge cases so there's a limited amount that you can do to shorten your code. But you should probably use Numpy to handle matrix operations. ...
user avatar
  • 47.6k
4 votes

Battle terminal-based game

Enemy and Player are really just the same class, right? Nothing is different between them. ...
user avatar
  • 47.6k
4 votes
Accepted

Can two knights pieces attack one another from current positions?

It's kind of a stretch to apply OOP here, but fine. Keeping it, you should type-hint your number and letter arguments. Consider ...
user avatar
  • 47.6k
4 votes

Battle terminal-based game

Fun little game, easy to win though :P As for the code: Naming things enemy in enemy class is a bit double. Same goes for player ...
user avatar
5 votes
Accepted

Abstract class with different derived signatures in Python

Pretty good! Overall you have reasonable types, especially Array (though that should only be declared once). But your use of ...
user avatar
  • 47.6k
2 votes

Find all pairs of natural numbers whose sum is 12

Reading the input. The format of the input file is not clarified in great detail, but it looks like the same format one would get from printing a Python list of integers. Which means that its format ...
user avatar
  • 9,475
4 votes
Accepted

Automate the Boring Stuff CH 10 - filling in the gaps

I believe that my logic is closer to a functional programming style It isn't, and new developers often confuse this with procedural programming; yours is the latter. Otherwise: Avoid ...
user avatar
  • 47.6k
5 votes
Accepted

Table Printer Project - Automate the Boring Stuff Chapter 6

One rarely needs to iterate over collections via indexes. Iterate over the thing itself (the list, tuple, or dict), not the indexes-of-the-thing. ...
user avatar
  • 9,475
1 vote

Porting PHP's array_push to Python

Some points to supplement @FMc's answer (though we'll put aside for the moment its excellent advice against mutation): The way you compute keys when extending dictionaries can be tidied with ...
user avatar
  • 533
4 votes

Porting PHP's array_push to Python

The list case. As noted in a comment, you can simplify to this: array.extend(args) The dict case. It looks like the goal is to find the max integer key, if any, ...
user avatar
  • 9,475
2 votes

Encryption algorithm for chat app

Cryptography self.key = hashlib.sha256(str(RSA.generate(2048, Random.new().read)).encode('UTF-8')).digest() So this generates two 1024 bit primes, creates an RSA ...
user avatar
3 votes
Accepted

Create new columns based on existing columns

Don't loop. Pandas is designed to be vectorised, which means that 99% of the time when you imagine an operation to require a loop, that loop should be baked into some Numpy or Pandas call rather than ...
user avatar
  • 47.6k
1 vote

What is the best way to retrieve all pages of a REST API route with Python aiohttp when the number of pages is unknown?

Don't format your token and page parameters into your URL. aiohttp supports passing a params dict to get. I assume that you've ...
user avatar
  • 47.6k
1 vote

Register/Login for Rock/Paper/Scissors

Recently I have been learning Python after years of putting it off, and I am having a really fun time with it. Keep it up! In register, your ...
user avatar
  • 47.6k
3 votes

A Simple Tic-Tac-Toe Game

You definitely need more functions. You state that you could put print(display_table) in a function, but not sure how you could update the table since it would be a ...
user avatar
  • 30.4k
5 votes

A Simple Tic-Tac-Toe Game

General Style Add a main guard This convention is specific to Pyton. Use a block if __name__ == '__main__': to put all your main logic into. Functions should do one ...
user avatar
11 votes
Accepted

A Simple Tic-Tac-Toe Game

Put all code in functions. This is what experienced programmers do, so you would be wise to adopt the practice even if you don't fully appreciate all of the reasons yet. After that change, you'll end ...
user avatar
  • 9,475
5 votes

Create new columns based on existing columns

The content of the loop is of the form if condition: continue else: action() It would probably be easier to read as ...
user avatar
  • 57.6k
3 votes
Accepted

List to Dictionary Function Project - Automate the Boring Stuff Chapter 5

Put all code in functions. Even the usage-demo code. This is one of many bug-avoidance and testability-supporting habits that experienced programmers adopt. Should the function return a new inventory ...
user avatar
  • 9,475
1 vote

Pascal's triangle solution in Python code

Use functions. You have a review with some useful advice, and its best advice is that you organize your programs around functions. Here I'll extend that idea. Functions should be focused. If we take a ...
user avatar
  • 9,475
4 votes

Alphabet Rangoli

You can simplify the code by a lot. The first simple change is that you don't need to define the alphabet this way: ...
user avatar
1 vote

Pascal's triangle solution in Python code

PEP 8 The Style Guide for Python Code has many recommendations that all Python programs should follow. These include: snake_case for variable and function names, ...
user avatar
  • 30.4k
1 vote
Accepted

Trouble with rendering speed of the animation of a simulation?

Don't import from math when you have Numpy. I didn't find mpl_use to be necessary. history, ...
user avatar
  • 47.6k
0 votes

Alphabet Rangoli

In order to print all rows you could use two cycles: an increasing cycle to print the first half rows a decreasing cycle to print the second half rows In order to print a single row, you can notice ...
user avatar
  • 136
2 votes
Accepted

Generating random integers in one of three ranges

An issue I see with this code is that it behaves unexpectedly if passed another value than 1, 2 or ...
user avatar
  • 1,215
1 vote

Generating random integers in one of three ranges

>>> 10**1 10 >>> 10**2 100 >>> 10**3 1000 So you can do randrange(10**(level - 1), 10**level) for a ...
user avatar
  • 8,717
1 vote
Accepted

Decision Tree for classification tasks in Python

You need to type-hint your code. Some of this will be made difficult by the dynamic nature of your field lookups, but you can get 90% of the way there. property and ...
user avatar
  • 47.6k
1 vote
Accepted

Single-file stdlib-only python backup utility

The overall code reads well, however there are some issues. Missing module docstring Your module has a docstring, but it only conveys its author and license, not its purpose. It should contain ...
user avatar
1 vote

Selenium web scraper to scrape Apple tweets of the last 3 years

Does anyone have any tips for me on how I can optimize my code to run faster? Measure what's slow. A typical approach is: Select some block of code you think might be slow. Try to make it about half ...
user avatar
-1 votes

Python modules for accessing the configuration of relevant paths

It should be as simple as--import path imports the paths. If you're having to think about the order modules load in, you're doing something wrong. If you want the <...
user avatar
1 vote

Single-file stdlib-only python backup utility

This code is not really ready for review, based on the inline comments you include. Bring us a finished piece of code please, not one that in progress. I have quickly skimmed the code without ...
user avatar
0 votes

Duplicate Binary Search Improvements

First, I want to say thank you to everyone who offered their critiques and advice. Not only did I learn a lot about binary search, I learned a lot about how to write better Python code. ...
user avatar
1 vote

Python script for zlib decompression

It works, it's reasonably clear in that you use a library. Mostly it's fine. Give inflate a docstring which clearly says what it takes in, what it returns. Rename ...
user avatar
3 votes
Accepted

Weird things to do to an image

You should bypass pygame and go straight to Pillow which is more narrowly targeted at image manipulation. It's good that you have type hints, but your functions are all missing a ...
user avatar
  • 47.6k
0 votes
Accepted

Newspaper Bill Calculator CLI with Python (3 of 3, Database)

SQLite supports check constraints. You should use them to ensure that delivered is only 0 or 1 (since booleans are not supported directly) ...
user avatar
  • 47.6k
2 votes
Accepted

Newspaper Bill Calculator CLI with Python (2 of 3, CLI)

The apostrophe here: "Edit a newspaper\'s name, days delivered, and/or price." does not need escaping since the string is double-quoted. This branching ...
user avatar
  • 47.6k
1 vote
Accepted

Newspaper Bill Calculator CLI with Python (1 of 3, Core)

Once you calculate, the results are displayed and copied to your clipboard This is not a good idea for a CLI. It may be a reasonable (opt-in!) option for a GUI, but for a CLI the overwhelming ...
user avatar
  • 47.6k
2 votes

Duplicate Binary Search Improvements

Style issue There is a style guide for Python called PEP 8 which is definitly worth reading. Among other things: Avoid trailing whitespace anywhere Comparisons to singletons like None should always ...
user avatar
  • 28.7k
1 vote

Regex and pandas to read forecast sky condition string

You've landed in trouble with your indices again. I think the shape of your dataframe significantly mischaracterises what your data are actually saying: Per station, per station observation time, per ...
user avatar
  • 47.6k

Top 50 recent answers are included