# Tag Info

0

I don't know about how these scores are being figured, so I can't say what would improve your score. Your code looks like an OK "face value" implementation of the spec, with two three details "wrong". The spec doesn't say that the addition operation should modify self, it actually implies that the operation should not modify self. "...

1

This is SO COOL. Some minor improvements: from scipy.signal import savgol_filter should be moved to the top of the file You should be moving your global code into subroutines. distance can be replaced with the built-in np.linalg.norm. _,_ = cap.read() does not need any return assignments; just call cap.read(). left = target[0] - dx, target[1] - dy ...

0

Your linesplit repeats a little bit of code; you could phrase it as while True: buffer_bytes = socket.recv(4096) if len(buffer_bytes) == 0: break buffer_string = buffer_bytes.decode('utf-8') *lines, buffer_string = buffer_string.split('\n') yield from lines 'tail -0 -f {} '.format(log_file) could be simply 'tail -0 -f ' + ...

2

Influx should not be capitalized as it's a variable name None of this code: with open("config.yaml", "r") as ymlfile: cfg = yaml.load(ymlfile,Loader=SafeLoader) server_URL=cfg["InfluxDB"]["server_URL"] token=cfg["InfluxDB"]["token"] org=cfg["InfluxDB"]["org"] Influx = ...

8

The algorithm is good, but... Use a better function name than getMinimumCoins. The task isn't about coins. Python prefers snake_case and four-space indentation. If the list is empty, you crash instead of returning zero. No need to actually perform the increments in the array, and itertools.accumulate can help: from itertools import accumulate def ...

-2

def find_by_key(my_dict, target): def find_data(my_dict, target): for key, value in my_dict.items(): if key == target: return value else: if isinstance(value, dict): yield from find_data(value, target) return next(find_data(my_dict, target))

0

This should be quicker than the recursive version: def zeros(n): z = 0 while n >= 5: n = n//5 z = z+n return z

7

As already mentioned by Peilonrayz, your algorithm's time complexity is $\mathcal{O}(n\log{n})$, because of sort(). You also process the input array three times: once to sort, once to increment elements as necessary to ensure there are duplicates, and once to calculate how much you incremented. To get the best performance, you want to have a sorting ...

3

Review You don't need else after return, but it can be there if it improves readability. Removing the last else will bring the code one level down. Declare variables right before you use them, you can move fact=1 down to first while statement. There are math.factorial and divmod functions, you can use them to speed the code up a bit (but I'm sure still not ...

16

if n==1 or n==0: return 1 That looks incorrect. 0! and 1! are both equal to 1, which has no trailing zeros, so we should be returning 0 there. If we had some unit tests, this would be more apparent. We don't need to carry all the trailing zeros with us as we multiply; we can divide by ten whenever we have the opportunity, rather than waiting until ...

0

In method equalize(), the for loop counts n=n_taps,...,n_points. If n-taps=6 and n_points=100, you'll get n=6,...,99 in the for loop. In the next line, start with n=6 as the first iteration, you get x=[u(1),u(2),u(3),u(4),u(5),u(6)]. This means you will never use u[0] in your algorithm!

2

I agree with Toby Speight on recursion, id and reset issues, but also I should mention: Name consistency PEP8 recommends snake_lower_case for variable and function names. Of course, you can use something else, like lowerCamelCase for variables and functions and UpperCamelCase for arguments; but don't mix styles, you're puzzling the reader - and yourself in a ...

2

How can I make a custom data structure as fast as dict? You can't (at least, not in CPython). CPython's dict is written in C, as are other dict variants in the standard library such as collections.defaultdict. If you want to write custom data structures approaching the speed of a dict, go write it in C, Rust, or run your Python script using PyPy. Anything ...

5

Starting with the last line: menu() Standard practice is to put this in a "main guard", so that the file is usable from other programs: if __name__ == '__main__': menu() This bit looks fragile: key = str("0"*(6-len(str(x)))) + str(x) There's an assumption there that all employee ids are 6 digits (and that's a convoluted way ...

1

Nice code. In Python, for has else clause And I think it fits here perfectly. In for retry in range(3): if ...: break else: #else-part the else-part will be executed if there was no break. So: for retry in range(0, 3): if dump_snapshot(mongo, database, collection, str(metadata_id), folder_path, dry_run): logging.info(&...

2

The main issue I see with this code is the lack of any unit tests. It's quite simple to invoke the test framework at the end of the module: if __name__ == "__main__": import doctest doctest.testmod() Now, just add some test cases: def firstNonRepeater(s): """ Returns the first character in the input string which ...

9

As has been pointed out in the comments and @Kraigolas's answer, the existing algorithm doesn't work. Here's why. In the string "xxy": The algorithm first considers the third character, "y". It finds it has not encountered it before, so records it as a preliminary out value. It adds it to smap with value 1. The algorithm next considers ...

15

Python has a Counter data structure that is handy whenever you are ... counting things. Since strings are directly iterable, you can easily get a dict-like tally for how many times each character occurs in a string. And since modern Python dicts keep track of insertion order, you can just iterate over that tally, returning the first valid character. from ...

8

Style From PEP 8, function names should be lowercase and use underscores to separate words: def first_non_repeater(s): ... Implementation In Python 3.6+ dictionaries maintain insertion order and if you're using an earlier version, PEP 372 adds collections.OrderedDict. If collections.Counter used an OrderedDict, you could solve this problem with that, ...

2

What you have is neither crazy nor terrible. You've started some type hinting (good!) but it's incomplete. For instance self._issues: Set[str] = set() and @property def checkers(self) -> Tuple[ Callable[ [], Tuple[bool, str], ], ... ]: Note that it's good practice to add hints accepting the most generic possible type and return ...

1

In this case, I would really keep it simple. I would drop the OOP and just write a simple function that validates the radar and returns a list of issues. To be clear: def check_radar(radar: Radar) -> Set[str]: return { *_check_1(radar), *_check_2(radar), ... } def _check_1(radar: Radar) -> Set[str]: # perform check ...

2

You're converting your text to ASCII ordinals (good-ish) but then converting those ordinals to binary-formatted strings (deeply ungood). A change of thinking is needed: rather than managing a string where every single character is either an ASCII "1" or an ASCII "0", you need to understand that byte arrays such as b'I have a dream' ...

0

First of all: don't use Python2, it's end of life. The telltale sign that you're using it is the lack of parentheses to the print function. Since Python has a built-in library for reading CSV files, it would make sense to use it. The parsing would be more elegant and straightforward. Your function get_all_courses expects exactly two arguments. It would be ...

2

Your 'switch statement' is bad because you've chosen to not use the same algorithm as your JavaScript example: const commands = { append: (arg)=>lst.append(arg), remove: (arg)=>lst.remove(arg), ... } Converted into Python: commands = { "append": lambda arg: lst.append(arg), "remove": lambda arg: lst.remove(arg), } ...

5

if key4 != key1 and key4 != key2 and key4 != key3: If you append to key_order upon picking a non-duplicate value you can just use in instead. You can then more simply use a for loop to select the number of keys to output. key_order = [] for _ in range(4): while True: key = random.randint(1, 4) if key not in key_order: ...

1

Your code is good from a readability standpoint. I appreciate the type hints. My only minor suggestions are using if __name__ == "__main__": for your driver code and lst instead of arr (arr usually refers to a NumPy array, but there are also builtin Python arrays that aren't lists). Here's a somewhat terser suggestion that uses a generator ...

3

Warning: this is probably not better - the index juggling is ugly - and it may or may not be faster; I haven't tested. It's possible for you to write this with no explicit loops or conditions (with sufficiently narrow definitions for loops and conditions) and no external libraries. You can assign to a list directly, abusing Python's slicing semantics: from ...

7

I like your code, but I think the biggest potential issue with it is that in each iteration of the loop, both left and right need to be checked to see if they're not None. As @FMc pointed out, another issue is that your reversed(lst[:index]) and lst[index:] lists both have to be built in memory before you even begin iterating. If you're dealing with very ...

8

Here's an alternative approach that requires no conditional logic and does not create intermediate sub-lists — although at the cost of using a third-party library: from more_itertools import interleave_longest def bidirectional_iterate(xs, index): left = range(index - 1, -1, -1) right = range(index, len(xs), 1) return [xs[i] for i in ...

6

I'd dumb it down a little: no lambdas, no partials, no formatting (you only have suffixes and nothing else). Make your HTTP methods all-caps for uniformity, and also you can use a generator instead of a list comprehension. For your Capabilities you can accept boolean kwargs. Pre-register all of the possible capabilities in a constant dictionary roughly ...

7

I might be inclined to do something like this: class Capabilities: def __init__(self) -> None: self.canEditCompany = True self.canDeleteCompany = True self.canShareCompany = True self.canAddFiscal = True self.canAddCategory = True self.canEditCategory = True self.canGetCategory = True ...

2

Here's a slight refactoring of your code to improve readability and reduce repetitiveness. (I don't think anything I'm doing here will do much for you in terms of performance, sadly.) import curses as c from itertools import product world_map = [ '...

2

In addition to what Roman Pavelka suggests: Represent your keypress_list as a keypresses set (note that it's not helpful to embed the type of a variable in its name; this is what type hints are for) Factor out rectangle-with-margin calculation routines into your SimObject class Do not 'start' anything in your constructor. 'start' in a separate routine or ...

4

I agree with @Anonymous that you should not loop continuously like that, or you'll waste energy and CPU time continuously checking the values. To solve this you can just sleep, wake up every minute, check the state and go back to sleep. Another more code-style related observation is that you don't need to nest while loops like that, but only keep track of ...

5

Your code looks nice and readable in my opinion; I can understand most of what's going on. A few points I'm unsure about, however: (1) Your exception handling seems a bit weird to me In filestore.py, you catch all exceptions in your __getitem__ method. This is generally bad practice — if there's a specific kind of exception that you're anticipating, then you ...

2

Format your code according to PEP-8, there are automatic checker and even automatic formatters for that. This is often considered as code smell: def key_test(self, key): try: return key.name except: return See: https://stackoverflow.com/questions/10594113/bad-idea-to-catch-all-exceptions-in-python Some methods ...

8

Just curious, but have you checked CPU usage ? Programs that run in a while loop can be terribly inefficient and taxing. Here you are just probing a sensor, this does not look like a computationally-intensive task but it's still overkill. Seems to me that a timer would be preferable. Sampling values from your sensors at regular intervals, even every few ...

0

I decided to use an example of shape 20x5000. For which I could reduce the time from ~58 sec to ~3 sec i.e. almost a factor of 20. def combinations(arr): n = arr.shape[0] a = np.broadcast_to(arr, (n, n)) b = np.broadcast_to(arr.reshape(-1,1), (n, n)) upper = np.tri(n, n, -1, dtype='bool').T return b[upper].reshape(-1), a[upper].reshape(-1)...

0

If you are not going to write anything to X (which it seems you are not doing), and just going to read from it, you should be good to just have all processes access the same variable without some locking mechanism. Now, global is not necesarily the way to go. Here is different approach: from itertools import combinations import numpy as np from scipy.stats ...

6

If I understand what you are trying to do, I think you can (1) remember the prior state, (2) print only on changes, and (3) select the message to print based on the new state. def water_level(): messages = { False: "The system has water", True: "The system is dry and needs water", } previous = None while ...

3

Regarding: I do not like the fact that the four NodeGroups are hardcoded in the script but can't think how to achieve what I want with an array stored as an env var. We can start first by creating a dictionary with all the node_groups and then start to refactor a bit of our code: NODE_GROUPS = { 'core': [], 'general': [], 'observability': [], ...

1

For get_exp_dates - and everything else here - Selenium is unneeded. The dates you seek are not based on AJAX etc., but baked right into the HTML: <select class="Fz(s) H(25px) Bd Bdc(\$seperatorColor)" data-reactid="5"> <option selected="" value="1626998400" data-reactid="6">July 23, 2021</...

1

After doing some reading and taking the advice of FMc, I decided against async for what I was doing. I ended up with multi-processing pool = multiprocessing.Pool() # input list inputs = read_ticker_file() # pool object with number of element pool = multiprocessing.Pool(processes=4) pool.map(yfin_options, inputs) pool.close() pool.join() I've noticed some ...

2

Split the data When you are inserting, use multiprocessing.Pool() to distribute the workload by parallelising it = you push more data within the same time Why 1000? Don't use own 1000 limit, SQLite and other DBs allow much much more. Instead check the SQLITE_MAX_SQL_LENGTH and other limits to assemble queries efficiently as in push as much data as possible ...

5

Indexes! Tables basically has array-like access: to find something, an engine should check all the values in a table. If you have a big table, this can be slow. But there's a solution: indexes. Database indexes work pretty much like book indexes, helping to find information quickly. But indexes are not free, they use some time and space too. So you should ...

7

Other than @PavloSlavynskyy's correct recommendation to add indices: Whereas autocommit is off by default for the Python library, I doubt your code is doing what you think it's doing because as soon as your first commit occurs autocommit is going to be re-enabled. Explicitly start a transaction at the beginning of your 1000-row pages to avoid this issue. ...

2

Linux which doesn't have any good input display programs I deeply doubt this, but moving on: You have a one-outer-function program that leans heavily on closures. This is not a good way to represent state, and is untestable. There are better ways to pass around state. In my recommendation I show two based on context: either bind to some separated functions ...

1

Double Open There is no reason to open the product.csv file twice. The first time you open the file, you are reading and storing the entire file in memory. Instead of opening and reading the file a second time line by line, you could simply loop over the list_csv. This: with open(r'product.csv', 'r') as file2: my_reader2 = csv.reader(file2, delimiter=';...

0

I too am new to this forum as well as to python. Here's my version of your solution, its a fully functional interface and not just a code snippet, that will be useful Also I followed most PEP-8 conventions, do point out any deviations, I shall correct myself. def get_primes(start,end): l = [] for i in range(start,end + 1): flag = True for j in ...

0

Pavlo Slavynskyy's answer is excellent! Depending how concerned you are with performance, the built-in Counter class might work for counting digits (or it might be really slow; IDK). Another small point: The way the same_digits function is being used, the digits of i are being checked six (or seven) times. That should be avoidable... You don't strictly need ...

Top 50 recent answers are included