The Stack Overflow podcast is back! Listen to an interview with our new CEO.

# Tag Info

1

The secret to performance is to choose the appropriate data structures which lay out the memory as raw arrays of bytes (or uint8_t values). This is done by creating cython typed memoryviews from numpy arrays or images loaded through PIL. This applies to the border list as well; that is, I create an array of (x, y) coordinates rather than a list of python ...

0

I have no familiarity with any of the libraries used here, so I can't comment on their usage. What I will mention though is the giant chunk of profile.set_preference calls in the middle of the script. It would be much cleaner and less repetitive to save the string/bool pairs of options as a dictionary (or another "paired" structure), then just iterate over ...

1

Error reporting Errors in Python code are better represented by exceptions than by printing. Exceptions are also usually more sensible than returning special values, because the exception does not need to be checked manually. The interpreter will tell you quite clearly if you forgot to think about one ... So you might change your code from print("wrong ...

1

Your second method is better than the first, solely due to the fact that it has one less bug than the first one: In [5]: match_with_gaps("a p e _ p", "apple") Out[5]: True In [6]: match_with_gaps2("a p e _ p", "apple") Out[6]: False However, both fail if a character is masked that appears more than once: In [7]: match_with_gaps("a p _ l e", "apple") Out[...

1

There is no need to comment your code. It is totally broken. Very first thing you need to do is to calculate your complexity. ACM is not about code quality, it is not about language. It is about algorithms. You can write the ugliest code ever but can it be executed? Not a problem if you have satisfying algorithm complexity. You can not just write different ...

0

Well! I'm not into data structures but when displaying or listing matrix is concerned, can help it out. Remaining things like functions, args, formating can be taken care of in later stages. hope this will not disappoint you... import numpy as np rows_cols = input('Enter the rows and columns in a single line (separated by space): ') rows = int(rows_cols[0]...

1

General strategy for optimizations on programming challenges To optimize your code, you need to be able to perform some measure on different inputs and you want to make sure your optimization does not break anything. You usually want both things to be performed easily - automatically and instantly if possible. This is usually possible with simple tests. ...

1

Your 2nd approach is better that 1st as it adds length comparison, but it has redundant else: branch. The 1st if condition, if positive, has unambiguous statement return False terminating function call my_word.count(my_word[i]), other_word.count(my_word[i] calls will traverse sequence of chars (word) on each loop iteration for equal characters (trying to "...

2

Complex refactoring/improvements: Involved Refactoring techniques: Rename variable, Rename function, Extract variable, Extract function, Substitute Algorithm, Slide statements, Split phase (well-known classics https://refactoring.com/catalog/) + eliminating duplication and rearranging responsibility Completely different OOP approach to your script, ...

1

To achieve the $\mathcal{O}(log(n))$ time complexity of insert and delete functions you should store the binary tree as an array - Heap implementation. Because you need to have a link to the last element for performing insert and delete operations and the easiest (common) way to track this link is an array representation of the binary tree. You can devise ...

4

One should almost never use a bare except clause. It should always list the exceptions to be caught. The code would be easier to read and understand, if it were written in section that each tested one aspect of a magic square. Like, is is a square, does it have all the numbers in sequence, do the rows add up to the magic number, do the columns, do the ...

6

I normally don't like to do complete rewrites for reviews as I don't think that they're usually helpful. Here though, the major problem that I see with your code is you're trying to do far too much "manually". You aren't making good use of built-in Python constructs that automate some of the painful elements. You also have everything in one massive block. I ...

3

Basically you need to reuse your session variable on the code, for example: print(login(session)) print(countries(session)) print(counties(session)) print(localities(session)) And inside that functions change the calls that referrers to "requests" to the "session" variable like: request_url = session.get( 'https://urgentcargus.azure-api.net/api/...

2

You needlessly loop through the whole collection in all the methods, instead of returning as soon as you find what you need. If the thing you look for is right at the start, you still go thru all other entries. for country in countries_dictionary: if country['Abbreviation'] == 'something': countryId = str(country['CountryId']) return countryId ...

1

Try to make the input and output types the same In your example, remove_outliers() takes a NumPy array as input, but returns a regular Python list. It would be nicer to have the function return a NumPy array in this case. The axis parameter only works when using the median Make sure that when you specify axes, that the resulting behaviour of the function ...

2

iterator There is no need for the intermediate list, just iterate over the text file line per line, and write the parsed line to the output file variable name f_name those 3 characters will not make writing or executing the code any slower, but writing it in full can help you understand the code later one re.compile You can compile the regular ...

1

Here's my take on it. I split the vocab into 2 set. The first set, heads if for substrings that start at the beginning of the string, and the second set tails for other substrings. The else clause on a loop gets executed when the loop terminates "normally", but is skipped when break is used. Some people don't like these else clauses, but I find them ...

1

JavaScript Javascript uses camelCase by convention not snake_case Undeclared variables are placed in global scope or throw a parsing error in strict mode. The further a variable's scope is from the current scope the longer it takes to get the reference and thus the slower the code. You have not declared words, capitalized_sentence and more in the testing ...

1

I think your button class should do more. It should know if a point is within it's boundaries or not and what its image(s) is (are). It should probably also have an update method that can optionally be called with the mouse position. I would also rename it to singular Button, since each instance of the class is a single button and not a collection of buttons....

1

That regex visualisation you provided is really neat. It shows that there is a lot of potential overlap in the conditions. You should be able to reduce it down to something similar to this: ^[+-]?\d+(\.\d+)?([Ee][+-]?\d+)?$1 Generate Hashmap There is a data structure that's well optimized for this task: collections.Counter. It will take any iterable and generate a dictionary with keys being elements of your iterable and values are the number of occurrences: from collections import Counter x, y = 'fairy tales', 'rail safety' c1, c2 = Counter(x), Counter(y) c1 Counter({'a': 2, ... 6 Releasing memory If you assign None to your variables, their contents is lost and the memory will (eventually) be reclaimed. tablou = input("Enter values delimited by space: ") b = tablou.split() tablou = None t = [] # initial list with int() contents for l in b: r = int(l) t.append(r) b = None l = None r = None Forgetting the variables The ... 2 I believe there are few missings in the solutions. When we are suggesting him to remove global variables or else the global variables must be declared at the top. The better part is to avoid it and pass them as an argument or make nested functions or a method and a function, whatsoever. Either the concat_list function may be a class with one arg lists and ... 3 I'd just go with @Roman's suggestion. You should just leave it up to the language to decide what is and isn't valid. I'd make two further suggestions though: I don't think the parameter to is_numeric should be Optional; either conceptually, or to comply with the challenge. None will never be a valid number, so why even check it? I don't think dealing with ... 1 Since you are a beginner, this is a good opportunity to learn about Python's standard library, its data structures and best practices. Before starting, you should always separate user in-/output and the actual calculations, as recommended in other answers. I'm going to assume that from now on. It is also not quite clear how to interpret your question. ... 2 For sequences (list, str, tuple, etc), this is rather straight forward: def chunks(sequence, size): return [sequence[index:index+size] for index in range(0, len(sequence), size)] 4 Instead of diving into cumbersome and lengthy regex expressions consider the following improvement/correction: The main thesis for the underlying aspect is: Numeric literals containing a decimal point or an exponent sign yield floating point numbers. https://docs.python.org/3.4/library/stdtypes.html#numeric-types-int-float-complex Therefore Python ... 1 Here I will modify the strings you printed such that it doesn't go over the screen. I don't see why you need to have GAME RULES as a separate variable. No harm and maybe more straightforward doing print("-----------------------------------") print("| |") print("| ROCK PAPER SCISSORS |") print("| PYTHON ... 5 Welcome to code review. Style Check PEP0008 the official Python style guide for maintaining code within Python acceptable standards. Class names: Apart from the fact that this is a bad use of classes, class names should be UpperCaseCamelCase which implies that since this delete_duplicates is a class, then the name should be DeleteDuplicates. Method/... 3 First off, this really shouldn't be a class, but a function. You should have a look at PEP 8, which is the closest thing to a Python style guide. For clarity, you should also split it up so that you have the processing separate from the input (and it's validation.) The general structure of your program might look a bit like this: def delete_duplicates(... 0 Below is the code I have come up with. It basically follows the code used for the web demo in the github repo you had linked to. I will add some explanation to this answer on how I had made some basic optimizations to better fit cython's memoryview model as well as potential room for improvement later, but figured I should post the code now as it might be ... 3 You have some odd stuff going on in chunk_with_slice; specifically these lines: def chunk_with_slice(input_list: List['T'], chunk_size: int) -> List['T']: if chunk_size <= 0 or not isinstance(input_list, list): return False First, you're using strings to represent type vars (List['T']). As mentioned in the comments, strings are used to ... 3 Argument Checking and Duck-typing Two problems with this code: if chunk_size <= 0 or not isinstance(input_list, list): return False If the arguments are the correct type, the function returns a list of lists. If not, it returns False? This is going to complicate the code which uses the function. It is better to raise an exception: ... 1 Part of the reason you're running out of memory is that you are allocating all of your items into memory twice. Once in the two lists weights and values, and once again in hash_table. Looking at your program, I don't see a need for you to keep your weights and values allocated as you do. You iterate through them one at a time in your outer for loop. What I'... 9 Python's string formatting has come a long way from the "%s" formatting days. Nowadays classes can even determine on their own how to handle format specifiers. Therefore I would write a matrix class that can be pretty printed with different format options determining the matrix style. class MathJaxMatrix: brackets = {'': 'matrix', 'p': '... 12 This looks like a handy tool to have around, maybe we can make it even better. Style As per the official Python Style Guide (often known by his nickname PEP8), keyword-arguments of functions should have no whitespace around the =. Matrix size numpy arrays have a property called .shape which describes their number of rows and number of cols (in case of a ... 3 Order your imports Imports should be ordered alphabetically in groups of standard library imports, third-party imports and local project imports: import math from operator import itemgetter import random import matplotlib.pyplot as plt import numpy as np import pandas as pd Make use of comprehensions You can rewrite def convert_class_str_to_class_int(... 0 Worked with gRPC client in C#. There you can initialize the client in the constructor with no additional code needed on request. It should be the same in Python. public MyClient(IConfiguration configuration, ILogger < MyClient > logger) { _logger = logger; _configuration = configuration; var config = _configuration.GetGrpcConfigObject(...); var ... 1 Welcome to Python! Choosing Rock/Paper/Scissors/ This if choice == 'R': choice = "Rock" elif choice == 'P': choice = "Paper" elif choice == 'S': choice = "Scissors" can be choice = [option for option in options if option.startswith(choice)][0] Since you're grabbing only the first letter, you can make this comparison, instead of checking ... 1 I decided that since I'll likely never need to associate the same function with multiple keys, I might as well just associate the keys with a function directly: def update3(self, **kwargs: Callable[[T], T]) -> GameSettings: return self._replace(**{k: f(getattr(self, k)) for k, f in kwargs.items()}) >>> sett = GameSettings(fps=30, is_running=... 2 collections.deque() The documentation for collections.deque() says it is more efficient than a list when appending/popping elements. (Popping the 0th element from a list, may cause the rest of the list to be copied forward one space.) So use a deque instead of a list for the queue. set() Use a set() instead of a list() for the adjacent nodes. Also use a ... 4 In Python, your check_palindrome function can be made more efficient and pythonic: def check_palindrome(original_string): """Returns true if an input string is a palindrome""" original_string = original_string.lower() return all(r == o for r, o in zip(reversed(original_string), original_string[:len(original_string)//2])) This only iterates ... 2 The following is a basic syntax and usage pass without looking into your algorithm in too much depth. I'll first show the suggested code and then highlight significant differences where it can offer improvements on the original. #!/usr/bin/env python3 from typing import Iterable, Set def tokenize( text: str, vocab: Set[str], ... 2 Regex compilation Your code here: # ratings ratings = re.compile(r"\b\d+\b") rating_vals = (ratings.findall(sms_reply)[:5]) # added meds add = re.compile(r"\+(.*?\))") add_meds = add.findall(sms_reply) # removed meds remove = re.compile(r"\-(.*?\))") remove_meds = remove.findall(sms_reply) gets only halfway to a good idea. It is useful to separate regex ... 1 Name shadowing next = addr + 1 # Skip length byte; filled in at end Don't call a variable next. That's already a built-in. You could use next_addr for example. Similarly, def test_depint(M, value, bytes): should not use the built-in name bytes. I'm not completely clear on what it does in context, but maybe message, deposit, deposit_span, etc.... 9 Boolean expression returns This applies to both your Javascript and Python implementations: if (reversed_string_1 === original_string && reversed_string_2 === original_string && reversed_string_3 === original_string && reversed_string_4 === original_string) { return true; // If the original string is not a palindrome } else {... 4 There are a few PEP8 issues: In Python3, class definitions have been overhauled a bit, and one can simply do class Node: instead of class Node(object):. The spacing is a bit all over the place: there should be two blank lines between class definitions, and I find the spacing within def bfs(self, start_node) difficult. The naming convention is to be ... 16 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 your list of enemies does not change (or changes less often than you need to find the closest enemy), I would use scipy.spatial.cKDTree. kd-trees take \$\mathcal{...

2

It depends. Mostly, it depends on whether it'll generally be in the dictionary or not. If it's nearly always in the dictionary, then the try/except method would win out, while if it's in there as often as not, then checking would be somewhat faster. However, python already anticipated your need. There's a better option: def GetSlot(self, slot_name): ...

12

First of all, let's talk about magic numbers. smallest_distance = 100_000_000 is a problem. Where's the hundred million come from? When you have numbers in your code, there should ideally be a specific reason for why you're using that number instead of any other, and numbers that are picked just to be ludicrously large have a weird habit of turning out to be ...

Top 50 recent answers are included