Hot answers tagged

8

This is not the kind of thing you should loop for. Just calculate a mask: def parse_out_bits(bit_field: int, start_index: int, end_index: int) -> int: mask = (1 << (end_index - start_index + 1)) - 1 return (bit_field >> start_index) & mask In English: If you're getting bits 5-7, that's 3 bits 2^3 == 8, - 1 = 7 (or 111 in binary -...


5

These will not impact performance, but are useful to address nonetheless: Type hints Some wild guesses here, but: def calculate_OSA( µ_deg: float, uv: float, chl: float, wavelengths: ndarray, refractive_indexes: ndarray, alpha_chl: float, alpha_w: float, beta_w: float, alpha_wc: float, solar_energy: float, ): That ...


5

There are three obvious suggestions here. Measure! First, and most important: develop a timing framework to measure your changes! You can't know if a change is beneficial if all you have is "the old version doesn't pass" and "the new version doesn't pass". Build a standard set of test cases, and a timing framework, and subject any change to measurement ...


4

eval(...) What is the purpose of: compilt = "r'(?=(" + genes[i] + "))'" ... eval(compilt), ... It takes a string like "aa", and forms a new string "r'(?=(aa))'", which is source code for the raw string r'(?=(aa))', which when evaluated yields the string "(?=(aa))". There is no escaping being done, no obvious reason to do the raw string formation and ...


3

TLE You're probably getting a TLE because, if value not in array: Is a O(N) operation meaning it has to traverse the entire array (worst case) to check if the value exists in the array I can understand why you felt the need to have an extra array, because of dictionaries are not ordered. But you can make use of the collections.OrderedDict module, to ...


3

concatenate There is no need to do the concatenation pairwise np.concatenate([img[:, :, :, i][0] for i in range(img.shape[-1])]) should improve the speed already numpy.moveaxis You can use numpy.moveaxis new_array2 = np.concatenate(np.moveaxis(img[0],(0,1,2), (1,2,0))) To check whether the result is the same: assert np.array_equal(new_array, new_array2)...


3

Specific suggestions Usually when you find yourself numbering variables it's time to put all of them in an iterable of some sort. In your case I would simply inline my_img1 etc. into image_list. Usually names like images would be used instead of image_list. Python is a duck typed language, so it doesn't really matter which type of iterable you use for the ...


3

Your use of y_coord and range is suboptimal here. You're iterating over a range(3) and ignoring the produced number, while also using y_coord as an iteration variable. Just iterate over the range of numbers that you want from the start: def check_surroundings(self, y_coord, x_coord): enemies = [] for cur_y in range(y_coord - 1, y_coord + 2): # ...


2

Welcome, there are some aspects to comment about. First is that, you should use specific names for your functions pp is ok and sounds quite interesting, but it would be better if you use primePowerCheck. Now, for the first function, I would change only two things: def primePowerCheck(q): fact = factorint(q) p = int(list(fact.keys())[0]) n = int(...


2

Readability formatting You have very long lines, and don't follow the PEP8 suggestions everywhere. The quickest way to solve both problems in one go is to use black. this can be integrated in most IDEs and in jupyterlab type hints In this I have to agree with Reinderein. Now it is not clear which parameters to your function are scalars, and which are ...


2

This works, but is essentially O(N**2); you can make it O(N) fairly easily by turning your whitelist/blacklist into dicts: def __init__(self, users_filepath, whitelist_filepath, blacklist_filepath): """ Get filepaths and load the following files: users file , whitelist file and blacklist file users_filepath: Path to a text file which contains ...


2

I think this should work: extras = ('country_code', 'price_type') for field in extras: if filters[field] is None: filters.pop(field) if any(field in filters for field in extras): items = Price.query.filter_by(**filters) else: items = Price.query The key is realizing that if there are any filters defined, you have to .filter_by() them. ...


2

I guess you are aware more or less of this (given your PS), but comments have to be there just when they are useful. Some of them that you should remove: # Empty dictionary to store info later on. # List of seats the user can choose from. # All prompts. # Runs until it reaches a break statement. # Find out how many times to run the while loop. # Convert the ...


2

Aho-Corasick algorithm Perhaps another approach is in order. I'd suggest the Aho-Corasick algorithm. Here's the original paper Efficient String Matching: An Aid to Bibliographic Search (pdf). Create a mapping from gene to gene index and weight. Build the DFA with the all of the genes. Loop over the DNA tests Scan each DNA test using the DFA. For each ...


2

Bug elif q1 == "catch" or "Catch it" or "Catch" or "catch it": Because: >>> q1 = "a" >>> q1 == "catch" or "Catch it" or "Catch" or "catch it" 'Catch it' >>> "catch" == "catch" or "Catch it" or "Catch" or "catch it" True >>> "0" == "catch" or "Catch it" or "Catch" or "catch it" 'Catch it' So it is true for all strings.


2

Review Bug on Capitalization mm = regex.match('^([a-z]+)([0-9]{4,5})|^([a-z]+)', input) This does not work for the given use case of California1998 But it can be easily fixed by adjusting the regex to include [A-Za-z] capital letters Stop overshadowing! You use multiple built-in keywords as variable names ie, input dir this makes it that the ...


2

Please consider below as opinions, not the source of truth. I write what 'should' be but read it as 'I think it should...' As for your questions: 1) It is not a good idea. For me, parametrize decorator means 'those are the inputs to the function you are testing' not 'this is the function that you are testing'. 2) I think it is a bad practice. Unit tests ...


1

Names I've renamed: hmn_* -> human_* cpt_* -> computer_* g1 -> max_score human_1 -> human_name game_score -> print_scores game_running -> check_scores rps -> start rps_running -> running rdm -> random GameOptions -> GAME_OPTIONS (we usually use pascal case for a class in Python, and capitalization for variable constants) Reason for all this renaming was ...


1

In my testing with mysql-connector 2.2.9, bulk insert queries using executemany() were automatically batched as described in the mysql-connector documentation UNLESS they used 'INSERT IGNORE'. (I have yet to test 'ON DUPLICATE KEY …' statements.) I found that the difference was up to 100x faster for plain 'INSERT' statements vs. 'INSERT IGNORE'; batching is ...


1

Looking at the jupyter notebook, I wonder if a bit of caching might help? How many of those datapoints are really unique? Something as simple as wrapping the often-called functions in a memoization decorator might help. Any of the calculate_ functions that take just floats are good candidates - I don't think memoizing anything that takes vectors would ...


1

Like it was mentioned in the comments, it's difficult for us to tell you how to get your code faster witbout more information about the runtime context of your code. But based on what you have shown in code, I would do these modifications: import numpy as nm import pytesseract import cv2 import ctypes from PIL import ImageGrab def im_to_string(): ...


1

groupby When iterating over the values in a column, it is bad practice to hardcode the values (for pivot in [1, 2, 3]). A better way would have been for pivot in df["dof"].unique(), but the best way is with DataFrame.groupby To see what happens in the groupby, I try it first with an iteration, and printing the groups for pivot, data in df.groupby("dof"): ...


1

Getting lines from a file You can use simple list comprehension to get all the lines from a file. words = [word for word in open("dictionary.txt", "r")] However, this does not ensure the file will be closed. To be safe, I would do this: with open("dictionary.txt", "r") as file: words = [word for word in file] The with ensures the file will be closed ...


1

I don't know about the other programming languages but it's quite easy to implement this particular program using inbuilt functions. So here is my code: from itertools import groupby def output(n): binary_num = bin(n).replace("0b","") print(max(len(list(group)) for i,group in groupby(binary_num) if i== '1')) if __name__ == '__main__': ...


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