Graipher
  • Member for 5 years, 11 months
  • Last seen this week
String reversal in Python
Accepted answer
52 votes

Yes, this can be faster. Adding strings using + is usually a bad idea in Python, since strings are immutable. This means that whenever you add two strings, a new string needs to be allocated with the ...

View answer
Send a tweet to ISP when internet speed drops
50 votes

Overall this is quite a nice module. Here are a few usability issues/nitpicks, though: When running the script, there is no easy way to stop it. CTRL+C does not work, I have to manually kill the ...

View answer
Comma Code (project from "Automate the Boring Stuff with Python")
23 votes

Ludisposed's answer is already a great improvement, however it fails to take into account some cornercases: It only works with lists of strings. For lists of length 1, like ["foo"], it returns " and ...

View answer
Large Number Limit Extravaganza
Accepted answer
23 votes

Your method of generating primes is horribly slow. Running your code takes on the order of 5 minutes on my machine. Consider as an alternative a prime sieve, even a simple one like the Sieve of ...

View answer
Count Even Digits In Number
Accepted answer
22 votes

You should have a look at Loop like a native!. Explicitly iterating over the indices is usually not the best way to do something in Python. By directly iterating over the string representation of n ...

View answer
Making a deck of cards in Python
Accepted answer
22 votes

You could just use str.join in a list comprehension and create deck directly: import itertools kind = 'HCDS' value = ['2','3','4','5','6','7','8','9','10','J','Q','K','A'] deck = ["".join(card) for ...

View answer
Goldbach's conjecture algorithm
20 votes

One thing that makes your code slow is your repeated calls to primes.index. Each of these calls needs to linearly scan primes until it finds the value you are looking for, making this \$\mathcal{O}(n)\...

View answer
Pythonic way to add each previous element in list
Accepted answer
20 votes

Note that Python's official style-guide, PEP8, recommends using lower_case names for variables, so I changed all your Ls to l and all your new_L to new_l. l = [4, 2, 1, 3] You should keep track of ...

View answer
Determine if a triangle is equilateral, isosceles, or scalene
Accepted answer
19 votes

A triangle has, by definition, three sides. I find it therefore weird to take a single sides argument, which could be of any size. This opens you up to obscure bugs, such as these ones, which are not ...

View answer
Python program to calculate GCD
19 votes

Python has an official style-guide, PEP8. It recommends (among other things) the following: Use whitespace around operators (so a = input(...)). Don't use unnecessary parenthesis (if, for, while, etc ...

View answer
Get the first item in a sequence that matches a condition
Accepted answer
18 votes

This is a use case for the walrus operator :=, which was introduced in Python 3.8. It allows you to write 1) without repeating yourself: runner = next( r for caller in inspect.stack() if ...

View answer
Chess game for my students
18 votes

Since @spyr03's extensive (and awesome) answer did not include it, here are some small comments. You want this to be an example for your students of how code should look like. You should include a ...

View answer
Calculate the Degrees of a Clock Hand Based on Input Time
Accepted answer
18 votes

Currently your code has user input, calculation and output all mixed up. This is OK as a first step (your code works, yay!), but the next step should be separating the calculation from the IO part. ...

View answer
Counting without zeroes
Accepted answer
18 votes

Well, what you want is just a product of the alphabet, with increasing numbers of elements. You can use itertools.product for this: from itertools import product, count from string import ...

View answer
Find the closest enemy
Accepted answer
18 votes

For small lists of enemies, linearly scanning all of them and computing the distance to the character is sufficient. However, if you have many enemies, a more efficient data structure is needed. If ...

View answer
Calculate Levenshtein distance between two strings in Python
Accepted answer
18 votes

There is a module available for exactly that calculation, python-Levenshtein. You can install it with pip install python-Levenshtein. It is implemented in C, so is probably faster than anything you ...

View answer
Determine added, removed and kept items between two lists
Accepted answer
18 votes

First, let's look at the naive implementation using sets: def diff_set(before, after): b, a = set(before), set(after) return list(a - b), list(b - a), list(a & b) This is (so much more) ...

View answer
Linux Commands in Python
Accepted answer
17 votes

Here are a few comments. In general, your code deviates in surprising ways from the UNIX commands (and not just by missing flags or options): Your ls command does more than you claim it does. os.walk ...

View answer
Generate 10 random 3-letter strings
Accepted answer
17 votes

Python 3.6 introduced random.choices, which allows you to write this even more succinctly than using random.choice: from random import choices from string import ascii_lowercase three_letter_words = ...

View answer
20 Ways to do Random Sampling
17 votes

You should not use eval without a very good reason. This is not a very good reason. Even though here you are actually fully in control of what gets passed to eval, this is good general advice. ...

View answer
Check if a number N is a power of K
Accepted answer
17 votes

You could have used the fact that if \$n = k^x\$, then \$\log_k(n) = x\$ is an integer. However, due to the limited precision of floats in Python, this will generate some problems. To get around this, ...

View answer
Raindrops in Python
Accepted answer
16 votes

Modular division is a well-known concept to almost everyone who has done any programming. In my opinion delegating it to a is_divisible_by function is not needed and only introduces unnecessary ...

View answer
Financial website scraper
16 votes

In addition to what @StephenRauch wrote in his excellent answer, let me add one more comment: Your class is completely useless. Not its functionality, which is fine, but it being a class is ...

View answer
"Guess the Number" game in Python
16 votes

I would probably combine these two if clauses: elif userInput>100: print("Our guess range is between 0 and 100, please try a bit lower") elif userInput<0: print("Our guess range is ...

View answer
Counting the number of consecutive 1's in binary
15 votes

This is a good opportunity to learn two things, separation of concerns and the standard library module itertools. You have three separate issues, each of which you can put into their own function: ...

View answer
Intersection of sorted lists
15 votes

While you don't want alternative solutions, you should take a look at the data in your specific usecase. As an example, for some randomly generated input (both lists of length ~600) on my machine (...

View answer
Divide a set of strings into those which contain "a" and those which don't
Accepted answer
15 votes

This usecase is actually covered by one of the itertools recipes. itertools is a package in the Python standard library that supplies fast and efficient tools for iterating over things or creating ...

View answer
List elements digit difference sort
Accepted answer
14 votes

Python has a built-in sorted function, you should use it. What it needs to sort according to some special criteria is a key function: def max_digit_diff(n): n_str = str(n) return int(max(...

View answer
Python function to map True, False, and None to symbols for display
14 votes

Even though return cuts the chain short if one matches, I would prefer to use an elif chain here, because it is more obvious, but YMMV (especially with automatic linters): def stringify(value): ""...

View answer
Bitcoin wallet address and private key generator
14 votes

Three very small observations: In your function generate_private_key_wif, you never use hashed, you re-compute it for the return value. In a nice self-contained module like this one, you should ...

View answer
1
2 3 4 5
26