New answers tagged

1

Just to add to the other answers, not sure if you've considered this, but keep in mind that the file name will be the same unless you create a new instance of your class. That means that if your logger instance is the same across midnight, you'll have the log of things that happened in one day written in the file of the previous day. Maybe this is actually ...


2

First -- document your code! I read through your d_func function and here's my attempt at writing a docstring for what it does, with Python-2-compatible type hints. Hopefully I got it right. :) def d_func(digit, mode): # type: (Union[str, int], int) -> Union[int, str, None] """Mode 1: give the int value of the hex digit. Other modes: give ...


7

Before speaking about the actual algorithm, let me hint you at the official Style Guide for Python Code (often just called PEP 8), a set of guidelines to write idiomatic-looking Python code. A core takeaway of the read should be, that in Python lower_case_with_underscores is the preferred way to name variables and functions. Fortunately you don't have to ...


5

WARNINGS First of all, let's listen to the warning we get when we run this and get rid off it: UserWarning: Using slow pure-python SequenceMatcher. Install python-Levenshtein to remove this warning warnings.warn('Using slow pure-python SequenceMatcher. Install python-Levenshtein to remove this warning') You can fix that by installing the ...


2

Just a few possible improvements. Variable Naming According to PEP 8, variable names, including parameters, should be in snake_case, not camelCase. This will apply to all the improvements made below. Type Hints You can use type hints to display what types of parameters are accepted, if any, and what types, if any, are returned by the function. Observe: ...


4

There is room for improvement in your code, I'll give a few pointers of things that stand out to me. DRY (Don't Repeat Yourself) There is a lot of copied and pasted code in your work. It makes it harder to read and much harder to maintain. To initialize the board, you manually put in 49 instances of a class with some parameters changing. What if you want ...


7

Docstrings should be on the inside of a function or class, not on the outside - before the def or class. Your logger doesn't automatically log to the next day's log. As YEAR, MONTH, DAY and filename are only defined once and never update. It's abnormal to see Logger.filename rather than self.filename or cls.filename. If you need to guarantee it's the class' ...


5

Yes, this is not a good class design. You are mixing global state with in your methods and using it only as a namespace. Instead consider something like this: from Time import Time from datetime import datetime class Logger: """If a log file for today already exist, open it in append mode. Else, create a new log file for today, and open it in ...


3

Obfuscation Tile.empty is a long, verbose way of saying None. Each time you use it, the Python interpreter must look up Tile in locals(), and then globals(), to find the Tile class object. Then, it needs to look up empty in the Tile dictionary to find the value None. If you simply used None, your code would be faster, because None is a keyword; no heroic ...


3

Bug in Solution3 (using heapq) The items being put on the heap need to be fully sortable. Tuples are compared element by element. If the first element of two tuples compare equal, then the next element of the two tuples are compared. In your solution, the second element of the tuple is a ListNode. But no methods for comparing ListNodes have been defined....


0

I had a bit too much fun playing with this and came up with a circular list implementation with a running total that's not much of a win (or sometimes even slower) for smaller sizes but gets a lot faster as you scale up. The fun part was coming up with a nice framework for testing different implementations with different sizes (I used both your original ...


4

Ultimate optimization avoid calling pd.DataFrame.append function within a loop as it'll create a copy of accumulated dataframe on each loop iteration. Apply pandas.concat to concatenate pandas objects at once. no need to gzip.open as pandas.read_csv already allows on-the-fly decompression of on-disk data. compression : {‘infer’, ‘gzip’, ‘bz2’, ‘zip’, ‘xz’...


4

You could make your life way easier if you used the deque data structure. from collections import deque d = deque(maxlen=2) d.append(1) d.append(2) d.append(3) sum(d) # gives 5, which is the sum of the last two inserted elements. With this, you call the sum function only when you really need to, which will improve your performance if you don't need the ...


1

Δ​t Since you have the timestamps of the velocity measurements, there is no need to calculate the step size. For all you know, the steps are not even all equal. You can use np.diff to calculate the differences between all the data points: time_differences = (np.diff(time)) or in pure python: time_differences = [b - a for a, b in zip(time, time[1:])] or ...


1

Readability Your code is visually unappealing. You have multiple PEP 8 violations, and your variable names really don't speak volumes. You have 2 spaces of indentation which is pretty much un-heard of in Python. If we move your code into a function and perform a little clean up we can get something like: import numpy as np def get_indexes(tokens, word): ...


1

Taking into account the three answers(at the time of posting) posted, I've come up with the below answer(hope I didn't miss anything). I have attempted to use every search every nth line as per Toby's suggestion but ran into issues with it finding a solution that was not the top, leftmost. I will hopefully get a chance to pursue it further and do some speed ...


1

Some small comments: In main.py: argparse can already deal with argument types and multiple arguments (it even enforces the type across multiple arguments). If you change it to multiple arguments being separated by whitespace, you can simply use this: parser = argparse.ArgumentParser() parser.add_argument("-p", "--pages", type=int, help="Pages per Setting",...


8

Your code performs one recursion per character and recursion depth is limited. For long inputs, your code will raise RecursionError: maximum recursion depth exceeded. Replacing recursion with an explicit loop solves the issue. Also, if you start the calculation at k = 1 with memo[-1] and memo[0] properly initialized and then work upwards to k = len(s), the ...


2

As a general feedback, the script looks quite good. I will nevertheless share a few of my thoughts with you. shebang Since you are using Python 3, the initial shebang should be #!/usr/bin/env python3. Otherwise it will depend on the system which interpreter is used to execute the script once the file is marked as executable. Documentation Only ...


1

Just a few things I noticed. Utilize built in functions This S = 0 for k in range(1, N): S += function[a + k * h] can be this S = sum(function[a + k * h] for k in range(1, N)) Python3's sum takes an iterable, and returns the sum of all the values in that iterable. So, you can pass in the for loop and it will return the sum for you. Looks neater, ...


6

Toby & Sam both make excellent points; I won't repeat them. I would like the add the following: Use sets with in You are repeatedly testing whether a letter is in the string VOWELS. This requires a linear search through the string, checking each substring to see if it matches. If instead, you declared VOWELS as a set: VOWELS = set("aeiouAEIOU") ...


6

We can use doctest instead of the asserts: import doctest def find_vowel_square(strs: list): """Return the top left grid ref of any 2x2 sq composed of vowels only. >>> find_vowel_square(strs=["aqree", "ukaei", "ffooo"]) '3-0' >>> find_vowel_square(["aqrst", "ukaei", "ffooo"]) '2-1' >>> find_vowel_square(...


5

Your second function is faster for me when simplifying it like this: @jit(nopython=True) def move_to_back_c(a, value): mask = a == value return np.append(a[~mask], a[mask]) In addition, Python's official style-guide, PEP8, recommends not surrounding a = with spaces if it is used for keyword arguments, like your nopython=True. Since numba ...


8

These are all relatively minor notes: You can use typing.List to provide a better type definition for the parameter (List[str]), precisely defining what it's a list of. I always try to avoid giving variables names that are just a variation on the Python type to tell me what its type is (that's the type annotation's job); the problem description calls this ...


4

To know the answer to your comparison to \$N\$, you need to attempt at least: \$N\$ next calls if you test with \$\lt\$ (succeeding will result to False) or \$\ge\$ (succeeding will result to True); \$N+1\$ next calls in all 4 other cases. Obviously, if the iterator length is fewer than \$N\$ there will be less calls. So, in order to simplify things, you ...


1

Your sys.stdout.write + flush is a fancy print call... You could just write if __name__ == '__main__': print(*complete(*sys.argv[2:]), end='', flush=True) instead.


3

You don't really mention what are the values used for. You'll always have a tradeoff between speed and memory (in this case memory amounts to how many digits you have). Some issues with your code: 1) You're casting your decimal.Decimal(line[0]) as float, that should negate the advantage of using Decimal. And this might be a reason why you see the ...


2

Old style declaration class Limiter(object): ... Using object as a base class is no longer necessary. Simply write: class Limiter: ... Same for the other classes Wrong receiver type-hint def __init__(self: object) -> None: ... self is not any object; it must be a Limiter (or class derived from Limiter). The proper type-hint to ...


1

I find the code presented here notably more readable than the previous iteration - the main apparent difference is meaningful naming of variables (most not in snake_case, yet). It looks like you want the results in one file per file of GpsData: such should be specified explicitly, as should be whether output records need to stay in the order of jobs in the ...


7

Modifying state in a recursive function is a bad idea if you can avoid it. If a function does not modify state, it becomes a pure function; such functions are easier to reason about and test. To produce output, the best way is usually to return a value. But first, a word on the terminology you chose. In computer science, the depth of a tree node refers to ...


1

I would suggest a turned around approach: compute the depth upon construction of the nodes. This is pure, and makes sure it is only computed once. It requires you to treat the class as immutable, though (i.e., no later extending of children), which might or might not be fine in your use case. class Node: """ Node in a tree, with children stored in ...


10

Optimization and restructuring Node class constructor (__init__ method) the arguments keyParam, childrenParam introduce unneeded verbosity and better named as just key and children the whole if ... else ... condition for ensuring children list is simply replaced with self.children = children or [] expression The initial dfsWithDepth function should be ...


5

My preferred way to solve the mutable immutable, is to just us a closure. This has the benefit that you don't have to pass currentDepthContainer, and you can return just the maximum at the end. Note I have changed your variable names to be Pythonic too. def maximum_depth(root): def inner(node, depth): nonlocal max_depth depth += 1 ...


8

It seems simpler to me to return the value: def dfsWithDepth(node, currentDepth, currentMax): currentDepth += 1 if currentDepth > currentMax: currentMax = currentDepth for child in node.children: if child is not None: currentMax = dfsWithDepth(child, currentDepth, currentMax) return currentMax # ... print(...


4

As @Peilonrayz said in the comments: You can just write class CustomList(list): def __init__(self, *args, setitem_callback, **kwargs): self.setitem_callback = setitem_callback super().__init__(*args, **kwargs) def __setitem__(self, *args, **kwargs): super().__setitem__(*args, **kwargs) self.setitem_callback() def ...


5

Splitting words The Python script splits the shell command's full line to words using shlex. I see a few issues with this: I'm not sure this will split the line exactly the same way as the shell would. Looking at help(shlex), I see "A lexical analyzer class for simple shell-like syntaxes", and I find that not very reassuring. I think command line ...


4

Your requirements could be summed up in a single regex. import re def is_fqdn(hostname): return re.match(r'^(?!.{255}|.{253}[^.])([a-z0-9](?:[-a-z-0-9]{0,61}[a-z0-9])?\.)*([a-z0-9](?:[-a-z0-9]{0,61}[a-z0-9])?[.]?$', re.IGNORECASE) I don't particularly condone this very condensed formulation; but this does everything in your requirements. Here's a ...


4

Comments: Use type declarations! These are (IMO) easier to read than docstring comments and they also make your code mypy-able. Your try/catch block is just an indirect way of requiring that the parameter is at least 1 character long. It's more clear IMO to just check the length explicitly, especially since you're already doing that as the next step. ...


2

Nice code, it does what it should and it is short. But it can be improved :) General python tips: Use type annotation. You can look at the type annotation of Sam Stafford in the previous answer, it will make your code more readable and will prevent bugs. Remove redundant imports. Is numpy really needed here? You can use a simple abs. Don't use lambda ...


1

Overall, looks very good and clean to me too, especially from a first poster. A few minor things: PEP 8 prefers triple double quotes for docstrings. I don't particularly care but it's in the contract to point such things out. And, in general, it's a courtesy to reviewers to get your IDE/linter to fix such things before posting. There are a few debateable ...


3

You can get an immediate speed-up by ditching the defaultdict(int), and using a bytearray(blockCount+1) instead. Both have roughly \$O(1)\$ lookup time, but the latter has a much smaller constant factor. In the former, each key must be hashed, then binned, then a linear search through the bin is required to find the correct key entry, if it exists, and ...


2

user_choice is your main loop, and so it would be better described as main. Whilst fairly undescriptive on what it does you can add a docstring to add information on what it performs. It is more idiomatic to use loops in Python rather than recursion. This is partly due to the recursion limit, and partially that the iterator pattern has a lot of support in ...


1

Conversion of a comment to an answer. Definitely avoid the recursion in user_choice. It will run out of stack if you keep exercising it for long enough. A simple while True: around the rest of the function body should fix it (obviously take out the calls where it calls itself). - tripleee


0

Since lambda expressions are hard to add types and decorators to, I'd start off by writing it like this: import numpy as np from typing import Callable def n_continued_fraction( a: Callable[[float], float], b: Callable[[float], float], err: float, i_min: float = 3.0 ) -> float: def d(i: float) -> float: if i == 0: ...


2

Here's a simplified version of this code: from typing import Dict, List def kdo_pack(): gifts: List[int] = [] gift_time: Dict[int, str] = { 1: "half second", 2: "one second", 5: "2 seconds", } sled_capacity = 12 # Pack the gifts onto the sled! while sum(gifts) < sled_capacity: try: ...


1

pandas library has rich functionality and allows to build a complex pipelines as a chain of routine calls. In your case the whole idea is achievable with the following single pipeline: import pandas as pd import numpy as np np.random.seed(seed=1234) df = pd.DataFrame(np.random.randint(0, 100, size=(100, 6)), columns=['constant 1', '...


2

It may not be what you are supposed to be learning, but if you use brute force to solve Sudoku, you'll do fine with easy ones (30 clues, asymmetric), but you'll struggle with difficult ones (fewer than 20 clues, symmetrical diagonally) - so why not use a SAT solver library like Google OR Tools to do the solving? Learning to use 3rd party libraries in your ...


0

After reviewing some of the answers I rewrited the code and added some descriptions This does not work because I have a index error in pandas... ''' This code intends to do an excel SUMIF between two tables with different indexes. The first tables has GPS data with timestamp, vehicle ID and distance The second table has vehicle ID and timestamps of events ...


1

It is probably easier to work with the underlying Numpy array directly than through Pandas. Ensure that all factor columns comes before all data columns, then this code will work: import pandas as pd import numpy as np np.random.seed(seed=1234) n_rows = 100 n_cols = 6 n_factor_cols = 2 n_data_cols = n_cols - n_factor_cols arr = np.random.randint(0, 100, ...


1

First a quick non-performance related mode: np.multiply could simply be replaced by * in your case since it's basically scalar x array. That would make the code less verbose. xh = K_Rinv[0, 0] * x xh += K_Rinv[0, 1] * y xh += K_Rinv[0, 2] * h My first intuition on your problem was that it lends itself to be rewritten as scalar product. See the following ...


Top 50 recent answers are included