# Tag Info

17

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 recursively "walks" down from the current directory, so it returns the content of all subfolders as well (without indicating in which subfolder each file or ...

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{... 15 You're right, it can be turned into one line using comprehension syntax which would be your best option of you're looking for a slightly more efficient code. isdecimal() is better to use in this case than isnumeric() because the isnumeric() accepts types like ½ and ¼ and n² which might produce some side effects you don't want if you're using this function ... 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 ... 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 ... 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': '... 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 {... 9 Specific suggestions: I believe collection types should be taken from typing, so your signature would be something like find_closest(character: Tuple[int, int], enemies: List[Tuple[int, int]]) -> Tuple[int, int]. At which point you may want to pull out and reuse a Coordinate type. Because your coordinates could be anything from millimetres to light-years ... 7 This is an improvement on the answer by @coderodde. Just like they said, you can do this in$\mathcal{O}(n)$time by counting how often each digit appears and then using a fixed output format. However, I would use collections.Counter from the standard library and string multiplication to achieve this goal: from collections import Counter def ... 6 3x to 4x speedup using str.translate() Based on a quick test (see below), str.translate() is an order of magnitude faster than a regular expression for replacing a single character with another character or short string. So, use str.translate() to take care of most of the substitutions and just use the regular expressions for the few complex patterns. ... 6 There are a few ways to programmatically get the docs, and one that I find cool to use is inspect. inspect allows you, among other things, to check what's in your file (module): import inspect import sys docs = {} # a dictionary module = sys.modules[__name__] # Gets us a reference to the current module for name, object in inspect.getmembers(module): ... 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/... 5 PEP-8 Guidelines Your code violates the PEP-8 standard in several area, including (but not limited to): Operators should have 1 space before and after the operator (y + h instead of y+h) One space after commas (x, y, w, h not x,y,w,h) Slices should not have any spaces around the colon (y:y_end not y: y_end) Spelling Columns is spelt with an n. ... 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 ... 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 ... 4 I would make the function slightly more generic. After all, you do calculate all distances anyway. I don't think list length becomes a storage space issue here, so why not return a list sorted by distance to the player? from typing import Tuple, List def distance(character: Tuple[int, int], enemy: Tuple[int, int]) -> int: return math.sqrt((character[... 4 The real issue with repeating yourself here is that you are iterating over your dataframe twice when you don't have to. Fortunately, the devs for lxml make the elements behave like lists, so you can create everything that you need to in one go, then just do root.append(sub_element) at the end like you would with a list. Whenever you find yourself directly ... 4 Data structure-wise, it seems okay, and does what you're after. Code-style wise, I see a few things: It's not quite PEP8, the coding style. Whilst you can read it, which is always good, there are tools to automatize the process, such as flake8, black. Most likely, your editor will have a plugin. This is include things like underscore_names in lieu of ... 4 We could also do something like: def sum_numbers(string: str) -> int: """Return sum of numbers in string""" return sum([string.count(str(i)) * i for i in range(10)]) if __name__ == '__main__': print(sum_numbers('hel3l4o55')) #should print 17 print(sum_numbers('xdman')) #should print 0 print(sum_numbers('123456789')) #should print ... 4 Cannot comment on Python, but what comes to to the actual algorithm, you can do it in linear time$\Theta(n)$: def largest_number_3(string: str) -> str: counters = [0 for _ in range(10)] string = list(string) for ch in string: counters[ord(ch) - ord('0')] += 1 i = 0 for num in range(9, -1, -1): for _ in range(... 4 Confusing names: the function largest_number() has a string parameter it's generally not a good practice to name parameters by their types and their is a type hint in your code indicating what that is so you can call the parameter digits. Inside largest_num() there is string = list(string) where string is not a string(a list). This is super confusing when I'... 3 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 ... 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(... 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: ... 3 The initial approach definitely has a number of "bottlenecks" and space for optimizations. Let me present and explain the crucial points: starting with good naming: don't give Python identifiers/functions camelCased names. We'll have find_path, get_successors etc. explored dict accumulates a great number of dictionaries (nodes) indexed by their id ... 2 Error handling if response.status_code != 200: print('api response error: {}'.format(response)) return is better represented as a simple call to response.raise_for_status(). Also, this: try: response_payload = response.json() except ValueError: return is dangerous. Silently failing should (at the least) be left up to the caller to decide ... 2 Your solution computes all possible target sums that are obtained by distributing the signs$+1$and$-1$to the numbers. For an array with$n$numbers that are$2^n$combinations. This is a typical case where dynamic programming is of advantage. Instead of searching for all combinations which lead to the target sum$S\\$, one computes the number ...

2

I messed around with performance of some alternate implementations: #!/usr/bin/env python3 from collections import OrderedDict from string import ascii_lowercase from timeit import timeit def method_1(exclude): list_of_all_letters = list(ascii_lowercase) for char in exclude: if char in list_of_all_letters: list_of_all_letters....

2

I suggest you check PEP0008 https://www.python.org/dev/peps/pep-0008/ the official Python style guide and Flake8 http://flake8.pycqa.org/en/latest/ as a tool for style enforcement. Docstrings: Python documentation strings or docstrings are a way of documenting your classes/function/modules and are usually accessed through help(). You should include ...

Only top voted, non community-wiki answers of a minimum length are eligible