New answers tagged

0 votes

2D array diagonals sum

PEP-8 The Style Guide for Python Code has several recommendations which you have deviated from in your code: White space Commas should be followed by 1 space, and should not be preceded by any spaces: ...
  • 32.2k
0 votes

Generating a selection of dates from a given date to the current one, in equal three-month intervals

There's no need to reinvent the wheel or use third party packages (dateutil) here. The datetime module already supplies you with a timedelta object that you can ...
  • 976
1 vote

Tool to concatenate video files

space is an interesting antipattern. UI toolkits were not designed for layout to be defined by placeholder elements; don't do this. Don't use globals. Use ...
  • 53.4k
3 votes

Python tool to organize downloaded media files

1. Coding style There's a style sheet called PEP8 ("How to write beautiful code with PEP 8") that is strongly recommended for any Python programmer. Your code violates a few of the ...
  • 428
6 votes

Python tool to organize downloaded media files

I'm sure Peter is a nice guy, but you shouldn't write programs only for him. Use a parametric home directory. Some of your extensions support either case and some ...
  • 53.4k
4 votes

Python tool to organize downloaded media files

PEP-8 This already looks very readable. You use snake_case as per PEP-8 for variables and functions. However, the global constants should be in ...
1 vote

Dice roll game with arbitrary face count

First off, I would say your code doesn't do what it's stated to do: ...
2 votes
Accepted

Tool to concatenate video files

TL;DR: To shorten the repetitive code-blocks and reduce duplication, go to 2nd section "Extract method". Make code readable (improve naming, express intend and self-explaining) ...
  • 820
0 votes
Accepted

Asking multiple choice questions in Python using an API

This is a good beginner project and a good API to practice writing a client. Add type hints to your function signatures. Python has a weak type system, and the more you can do to strengthen it, the ...
  • 53.4k
4 votes

Connecting ropes with minimum cost

Coding style I suppose your Solution class and function signature are not your call but were imposed by your programming exercise environment (I'm not familiar with ...
  • 1,685
1 vote
Accepted

Implementation of JSON schem parser to extract some attributes

First I will say, the fact that you're doing any of this raises just all of the red flags. This code and the data it consumes and outputs have all of the hallmarks of poorly-structured data lasagna. ...
  • 53.4k
1 vote

Simulation of sand particle collision

Don't write, never commit/publish uncommented/undocumented code. Tell, in the code, what "everything" is there for. Python got it right specifying docstrings such that it is easy to copy ...
  • 4,958
7 votes

ROT13 encryption using array indexing

There is already an example of better code serving your purpose, so here are some of the things that should be worked on in your code. Document your code Your code currently has no documentation, ...
  • 1,685
4 votes

ROT13 encryption using array indexing

You can achieve results more easily. In essence, displacement means cutting in half and swapping parts. You will also need a dictionary for quick substitution, then you do not need an array and join <...
3 votes
Accepted

Tic-Tac-Toe Code

Where to start… tuple assignment ...
  • 32.2k
30 votes

Python decibel meter-accurate?

Indent your code with a PEP8-compliant IDE or linter; it's a perfect mess right now. Move your global code into functions and maybe classes. There are two good use cases for classes here - one for a ...
  • 53.4k
1 vote
Accepted

python pygame snake game

Notice that, directly after construction, Game is unusable and requires a call to setup_game. You also have one ...
  • 53.4k
3 votes
Accepted

declarative package manager for Arch Linux

Minor: print(f"pacdef, version: {version('pacdef')}") doesn't need formatting, because the default separator for print...
  • 53.4k
2 votes
Accepted

Coordinate conversion program using pyqt

The members of UIInterface should all be lower_snake_case, as in main_window. ConvertChoice ...
  • 53.4k
1 vote

mypy does not recognize the correct return type

Consider your code: ...
  • 141
4 votes

mypy does not recognize the correct return type

Currently MyPy does not know that the function is_valid_credentials is a type guard that narrows the type of the passed credentials Introduced in Python 3.10 ...
5 votes
Accepted

Simplify nested list comprehension

Mypy doesn't know that calling _parse_name multiple times will always return the same value if the same value is passed to it. You could try using walrus operator ...
2 votes

input character name and age then print name and age list the characters that are older

PEP-8 The Style Guide for Python Code has several recommendations you should follow. White Space You should have a space around operators like =, ...
  • 32.2k
2 votes
Accepted

Iterating over JSON more effectively

Much more complicated than it needs to be. You extend a list, then traverse the list to construct a counter, then traverse again to get a sorted sequence, then traverse again to get a list of keys ...
  • 53.4k
2 votes

input character name and age then print name and age list the characters that are older

Don't treat the other characters specially - just put them in a sequence (a tuple, in this case), and compare them in a loop. Consider adding a validation loop for the age. Your code needs to be moved ...
  • 53.4k
1 vote

How to using custom colormap with pixel calculation, gray scale value by opencv and make it workable on camera

Looking at just the code, I find it difficult to see its purpose. In particular, I don't find colormap: Document your code. In the code. Define a function for the mapping presented. Find or define a ...
2 votes
Accepted

Create URL's, then download and print each RSS feed text

Your topics should be a tuple and not a list, and if you want they can be moved to a global constant. Add PEP484 type hints. I don't think that feedparser is able ...
  • 53.4k
0 votes
Accepted

API request into a dictionary

You could write a little bit simpler: Inline the returned ethereum_data dictionary, return it directly COINGECKO_COIN_URL is ...
  • 110k
1 vote

Pairwise Max Product

Making it faster The maximum product of two numbers in the input will be either: the product of the two highest numbers the product of the two lowest numbers note that this is possible when the ...
  • 110k
2 votes

Auctionsite API Wrapper in Python

Use the start position parameter of .find(...) instead of string slicing This code uses a string slice: ...
  • 110k
4 votes

Auctionsite API Wrapper in Python

Payload This code is pretty hard to read (and possibly prone to encoding errors): ...
  • 5,607
6 votes

Auctionsite API Wrapper in Python

In API.__init__, you're assigning a value to self.base_url. However, that value is never changed and thus is the same for every ...
3 votes
Accepted

Automate the Boring Stuff Chapter 9 - Regex Search

Use stronger input validation The code checks: if Path(user_path).exists() != True: And later it does: ...
  • 110k
5 votes

Number guessing game with difficulties and highscore

Adding to @DeathIncarnate's great answer: Don't use global variables It's fine to access global constants, but manipulating global variables such as dif is bad ...
0 votes

Efficient List comprehension with multiple conditions using shift?

Without even materially changing anything, the indentation of this code is impenetrable, and I had to do this to have any idea what the code is doing: ...
  • 53.4k
5 votes
Accepted

Number guessing game with difficulties and highscore

PEP-8 First off, some minor things your variable names aren't compliant with PEP-8, which recommends using: UPPER_SNAKE for top-level variables ...
2 votes
Accepted

Automate the Boring Stuff Chapter 9 - Mad Libs Exercise

Use descriptive names It's good to use descriptive names for variables (and everything) to help readers understand the elements of the code and how they might interact. Names like ...
  • 110k
2 votes

Reversing a Python string using [::-1]

Is there another way of reversing a string other than using [::-1] method? Yes there is. There are plenty of tutorials on the Internet, consider this one for example: Python Reverse String - 5 Ways ...
  • 5,607
6 votes

Print all "balanced" sequences of 'A' and 'B'

Avoid unnecessary computations The requirement that all prefixes of length \$\geq 4\$ must be balanced excludes a lot of combinations. For any prefix length, 80% of the combinations of that length are ...
  • 110k
5 votes

Reversing a Python string using [::-1]

Using string slicing as you have done is pretty much the best way, as discussed in this answer. You should consistently put a space before and after the = ...
1 vote

Find the missing and duplicated numbers from shuffled range

Use counting sort Since we know that all values of the array are within a range [a, b] with one missing value, this is a good opportunity for Counting sort: find ...
  • 110k
11 votes
Accepted

Print all "balanced" sequences of 'A' and 'B'

Refactor to use functions Try to avoid boolean variables. Pseudocode like: ...
  • 2,983
1 vote

Find the missing and duplicated numbers from shuffled range

As Toby suggests, you traverse the array multiple times; you need to cut that down. However, my proposal is going to be fairly different. Don't use counters and sets. Sort the input array first, then ...
  • 53.4k
2 votes

Derivative calculator simplifier using python

Firstly I recommend using some form of standard Python formatter, so your code is standardized and will allow others to more easily assist you. In my answer I use the ...
2 votes
Accepted

Estimate an average duration of every game state in a football match given implied goals for home and away teams

It's clear that you've been working at generic Python quality, and from that perspective this code is half-decent. Where it falls over is Numpy use. In one sense, well-written Numpy code doesn't look ...
  • 53.4k
1 vote
Accepted

Create a forecast matrix from time series samples

Yes, Numpy already has a built-in sliding window method (though it's perhaps a little obscure). This should indeed be memory-friendly, occupying about (W + N) and not W(W + N) due to it being a view. ...
  • 53.4k
1 vote
Accepted

Increase efficiency of stick cutting algorithm

Two reviewers advised how to avoid establishing the length of current longest piece from scratch, as that promises worst case run time at least quadratic in the number m of cuts. In greybeard's ...
3 votes

Increase efficiency of stick cutting algorithm

Consider time complexity When the code works but it runs too slow, it's usually because the algorithm doesn't scale well to larger inputs. It's good to review the time complexity and look for ...
  • 110k
3 votes

Increase efficiency of stick cutting algorithm

Hm. Interview. You tried something simple (good!) and it doesn't fit the time frame (pity). Well, if it seems to work, give it a name and use it as a test for advanced implementations. Make it a ...
  • 4,958
10 votes

Implicitly logging the filepath of the callsite of the log-statement

Unless I am missing something, adapting the formatter slightly would produce the same result: ...
  • 5,607

Top 50 recent answers are included