New answers tagged

0

Performance wise In general: You use numpy, but you write it almost like in fortran. Python with numpy is good for scientific programing and computing as long as you don't do many loops read this first A beginners guide to using Python for performance computing if you really need to do tight loops than use cython. But most of the time you can avoid that ...


2

It is simply not feasible to just parse the full set of (X|HT)ML with regex. I can't provide too much feedback on your solution as it simply isn't the correct solution for the problem, but I can provide plenty of examples where it fails to match valid input. <tag attr='"'></tag> <tag attr=""></tag> <tag attr=attr></tag> - ...


3

Docstrings Python documentation strings (or docstrings) provide a convenient way of associating documentation with Python modules, functions, classes, and methods. An object's docstring is defined by including a string constant as the first statement in the object's definition. def guess_word(): """Do calculations and return correct guessed word.""" ...


1

Random guessing will always take a long time. You can improve your code a bit if you dont append to a list and instead use random.choices. import random import string def main(word): ntries = 0 while True: ntries += 1 b = "".join(random.choices(string.ascii_lowercase, k=len(word))) if b == word: print("Mission ...


1

The Python program looks fairly good. I wouldn't call it bloated, but there are a few structural problems related to the Arduino class. They boil down to: Interpreting the data received from the Arduino is done in the Arduino class, which will make it harder to reuse the code it the future, and makes the code harder to quickly read and understand. The ...


1

I won't repeat the excellent comments made by the other answers on Prime Factorization, Dynamic Programming, Single Responsibility Principle, Indentation, f-Strings, Bugs, Naming, Documentation, and Separation of Input from Processing. Integer conversion After all those comments have been filtered out, the following programming style still jumps out and ...


0

I'm no mathematician, but here are some suggestions as a long-time programmer: Naming is one of the hardest programming skills to learn, but it is also incredibly important for readability and maintainability. Renaming things can make certain bugs and code smells obvious. I would recommend expanding any abbreviations within reason, as long as writing them ...


5

I've factored out the logic for transforming the cell-like string to a number, for example a7 -> 1, z8 -> 26, aa12 > 27 and so on. I've also factored out the logic to replace a character if it falls within the length of the target string. Finally I've parametrised the length of the input string. This approach makes your code more readable and easier to test ...


0

largest = None smallest = None while True: try: num = raw_input("Enter a number: ") if num == "done": break if largest is None: largest = int(num) if int(num) > largest: largest = int(num) if smallest is None: smallest = int(num) if int(num) < smallest: ...


3

DRY Code The code is very long when it doesn't need to be, and it is very repetitive. There is a programming principle called the Don't Repeat Yourself Principle sometimes referred to as DRY code. If you find yourself repeating the same code multiple times it is better to encapsulate it in a function. If it is possible to loop through the code that can ...


1

Since you compute the primes between low and high to get the number of primes and you compute the primes between zero and low to check if your len(primes) is prime, why not compute primes from zero to high in one shot? This also has the big advantage of increasing the speed of your computing speed (yes, you read that right). Right now, to see if a number ...


1

list A str is an iterable itself, so calling list on it in w = set(list(w)) and for x, i in enumerate(list(s)): is unnecessary. set a set only has the unique elements. If the word w contains any double letters, they will be only counted once. A Counter is a more appropriate data structure deque For the queue, a deque (double ended queue) would be a ...


3

First things first: while nloops<=llno: if __name__ == '__main__': would make more sense with the order reversed; and def f(l1,l2, q, r, s): ... q.put(distance) r.put((node1a, node1b)) s.put((node2a, node2b)) while nloops<=llno: if __name__ == '__main__': q = Queue() r = Queue() s = Queue() ...


0

class ContainsEverything: """Dummy container that mimics containing everything. Has .add() method to mimic set. """ The indentation is borked here, and needs correcting before the code will run. I profiled with guppy3 (inlining everything into one file for my convenience - that explains the __main__ below): lm = LanguageModel(4) lm.train(...


2

Firstly, use a PEP8 checker. It will raise a lot of issues about whitespace and also tell you to change if visited[k[0]-1] == False: to either if visited[k[0]-1] is False: or if not visited[k[0]-1]: The DFS is far more complicated than necessary: We don't need visited: given that we know that the graph is a tree, it ...


3

You have a problem with indentation in this line: elif (x % i) == 1 and i == (x - 1): primes.append(x) f-strings: if int(len(primes)) in primes or int(len(primes)) in primes_2: print("Huh, fancy that!", len(primes), "is also also a prime number!") print("The prime numbers are: ",primes) you might want to replace this with f'strings that looks ...


3

Welcome to Code Review! Here are some suggestions. Naming Choose a better name than primes_2. I'm not clear on what this variable does. Write some documentation ...in triple quotes at the top of your function. Describe its inputs and outputs. Separate user input from processing Put your calculation code in a separate function from your user input and ...


4

I suggest you get a linter such as Prospector or flake8, this can tell if your code is un-Pythonic. Some people prefer hinters like black. Your code doesn't conform to PEP 8 which is the standard when it comes to Python. Your comprehension is hard to read because it doesn't conform to best practices. I'd recommend moving your code into a main function and ...


2

The other thing that might make the code run slower is I am creating an arrow for each line, but I want the arrow to point correctly relative to the direction of travel so I need to manually calculate the direction of the arrow, which I believe is also making the code run slower. That would be it. trace_creator() alone takes 10s on my machine, which is ...


3

index is a singular noun that doesn't represent of group of things, therefor it isn't a good name for an array. Your method is named anagram_indices and returns an array, I like to call the returned array results, so it's clear that the array are the anagram indices. Using i and x is very confusing, so much that it made me question my own knowledge of the ...


3

Most of your code can be greatly reduced. Doing string addition is often a bad idea in Python, especially if you are doing it in a loop. Also note that a + "" == a for any string a. I would replace your mix of global code and the word_processor function with this short function: import string WHITELIST = set(string.ascii_letters + string.digits + string....


0

This can be achieved with no loops and no joins, just two print statements: def commalist(listname): print(*listname[:-1], sep = ', ',end=", "), print('and',listname[-1]) the end parameter in the first print will determine whether to use oxford comma.


1

It looks very procedural at a glance, it might just not be useful to use custom objects here. In any case you don't need to explicitly inherit from object, class Process: is fine already. So, more maintainable, well, the headers look dubious, but obviously chosen from a real-life browser. The character set / encoding values would be the most concerning to ...


0

Firstly I'd suggest following PEP8 and/or using an auto-formatter like black, but if it's just you working on it that is a bit less of an issue than if other people were involved. Suffice to say, most code follows that and it usually gets flagged first thing (because it's so noticeable). Reading the code, is that all there is, you are able to log in via a ...


0

In the request method the exception variable really doesn't have to be set before using it, just inline it and make the code more succinct: def request(self, endpoint, params=None): response = self.session.get(endpoint, timeout=TIMEOUT, params=params) res_code = response.status_code if res_code != API_OK: raise API_ERRORS[res_code] ...


0

Without knowing more about the kubernetes API that's hard to say, maybe you'd be more lucky on StackOverflow instead. That said, if there's no explicit function to check, probably not. Especially the status code 404 sounds like it would probably mean "not present", so this doesn't seem overly bad actually. Is it intentional that all other ApiExceptions ...


14

I think your program would be easier to use and create if you rearrange when you ask your questions. (This is mostly to show that I have consciously changed how your program works) You are correct it would be easier to use your data if you enter it as a dictionary and some lists. I personally would use the following layout: option_1 = { 'option': ...


5

Data instead of code You have a lot of repeated calls to input. This should really just be a tuple of strings that all refer to a choices dict; something like: choices = {} prompts = ( ('option1': 'Option 1:'), # ... ('option1a': 'Good. Now tell me a reason why {option1} is a good choice: '), # ... ) for name, prompt in prompts: choices[...


0

Is my algorithm slow because it has problems? Yes. The fundamental problem is that it always processes every character of the input. There are some obvious improvements which don't address this fundamental problem: Since the common prefix can't be more than min_len, truncate both strings to min_len before encoding them. bin returns a string, so str(bin(......


3

Python has some neat features, some of which might seem familiar from C++ and some note. The Python standard library is also very powerful. These comments are meant to be complementary to the answer by @Reinderlein, I will not repeat the useful advice given there. You can compare multiple things: MINIMUM_SIZE < x.size < MAXIMUM_SIZE. The itertools ...


0

The code's straightforward enough at a glance, I wouldn't have worried too much about the duplicate bits, especially since it's only double and not multiple times for each part! Overdoing abstraction can hurt readability too. See below for some thoughts on how I'd approach this with that warning in mind. First of I'd try and move some of the functionality ...


2

Some improvement, but there's still more :) Don't semicolon-delimit statements self.window = super(); self.window.__init__() There's nearly never a good reason to do this. Just use two lines. .ini support https://docs.python.org/3/library/configparser.html is what you should be using instead of manual parsing for an actual .ini file. Inline functions ...


2

Formatting There are some minor issues that would not pass PEP8. You should run a linter or inspector over your code, and it will suggest that you should change some whitespace. Another formatting suggestion is that you write PART_HASH_SIZE instead of partHashSize for constants, and size_parse instead of sizeParse for function names and variables. ...


3

I'm sorry, but this code is really hard to read. I must admit I don't know Cython too well, so I won't be able to comment too much on that part. But anyways, here are a few comments, in random order. While Cython does not fully support docstrings (they do not show up in the interactive help), this should not prevent you from adding some to explain what the ...


0

I don't fully understand your code, but it seems to look only at the presence or absence of the previous element when deciding whether to include the current one, so I constructed a test case and verified that it fails: print(get_max_sum(6, [10, 10, 0, 0, 10, 10])) should give 40 but actually gives 30. if main_output[0]['sum'] >= main_output[1]['...


2

Style Your code mostly follows PEP8 but is a bit more terse. Mostly: Using 4 spaces for indentation; Putting a space after every coma; Using two blank lines to separate top-level functions; should ease reading your code. You also use camelCaseVariableNames from time to time, instead of snake_case. Lastly, using an if __name__ == '__main__' would allow ...


0

Welcome to CodeReview! Good first post. Comments Having comments is great. Your convention is a little odd - there's no need for triple hashes. A single hash at the beginning is more common. File handling Your intention was good, but the execution could be improved. Firstly, at this level, don't except Exception. It's too broad. Let exceptions be ...


3

Functions are your friend Even in Jython, functions are a valid construct. They allow for scope, so that you can better reason about temporary variables; give better stack traces when things go wrong; increase testability; etc. So you should move your code into some functions. Invert your logic This: if len(laty) == 7 and len(longx) == 6: should ...


3

Assume you are referring to speed, not conciseness when asking about efficiency. In which case reducing the amount of loops will not necessarily improve performance. "type": next((data_type["type"] for data_type in DATA_TYPES if data_type["name"] == data_type_attr_name)) This can be improved so that you are not needing to go over DATA_TYPES looking for a ...


2

Your sudoku solver is missing a crucial part: the one that fills all obvious cells without backtracking. In your example sudoku, in row 1 column 7 there must be a 1 because that's the only place in row 1 where a 1 is possible. That's because the blocks to the left already contain a 1, and columns 8 and 9 also contain a 1 further down. With that improvement,...


2

Use itertools.product import itertools for device, data_type_attr_name in itertools.product(list_devices, data_types): result_list_element = { "device_reference": device.name, "device_name": "REF - " + device.name, "data_type": data_type_attr_name, "type": next((data_type["type"] for data_type in DATA_TYPES if data_type["...


2

With the list comprehension you are filling a whole list with your values, and then you are sending that list to join. Instead of a generating a list and then sending it, you can send a generator instead: similar to the list comprehension, but generates the values on-demand. With your old approach, if you had 10000 dates you would have them all at a list; ...


2

Don't shorten variable names. It's really annoying having to scroll back to the top of the page and read a comment to know what 'kog' or kohg' stands for. The interpreter doesn't care how long variable names are, but humans do. Use meaningful names. What the heck is H_PARAMATER and A_PARAMATER? Most of the time 1 letter variable names are also meaningless, ...


-2

first it will validate the both Base Number and Result are not equal to zero and both numbers are divisible are not. Here Count is iterating variable it will check condition for each pass. BaseNumber = 16 Result = 4096 count = 1 power = 0 if Result and BaseNumber != 0 and Result % BaseNumber == 0: while count != Result: count = BaseNumber * count ...


2

Overall your code is pretty clean. Abstract class There are a few different ways to do this. You can explicitly use the abc stuff, but the simpler thing to do is in your abstract methods (e.g. run), raise a NotImplementedError - at the Task level, not just KillTask. Then classes like KillTask that are effectively abstract children simply omit the ...


2

The main part of CX can be simplified quite a bit. cycles[pos] is the cycle number of that position, or -1 it hasn't been determined yet. cyclestart is a generator that returns the next place for a cycle to start. parent1 = [8, 4, 7, 3, 6, 2, 5, 1, 9, 0] parent2 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] if np.random.random() < pc: # if pc is greater than ...


3

Docstrings You should include a docstring at the beginning of every method, class, and module you write. It allows anyone to view how to use and implement your method, using your_function_name.__doc__ or help(your_function_name). Class Naming PEP-8 Compliance requires that all class names should use the CapWords convention. In your case, since Chromosome ...


0

Update - I was experimenting with numba lately, so I gave it a shot for this question. Here's some timeit code for the binning part of the question (calculating bin means). With some modification of the call/function, numba on-the-fly-compilation gave me a performance increase of ~70% import timeit setup_def = """ import numpy as np def default_mean(data, ...


2

The methods are too long. Strive to make smaller and more specific methods. This will improve the readability of you code, and it will allow you to reuse code. For example on a lot of places you ask the user to confirm his action. This is done with a call to the input method in a while loop until correct input is entered and then if-else statment, where you ...


3

A major drawback of this design is that you cannot reuse a single instance of structure.structure to read multiple records. Instead of s.fill(file_ptr), consider making a method s.read(f) that returns an OrderedDict of the deserialized data. (By the way, mentioning "pointer" in a parameter name isn't very Pythonic.) Note that that would also replace your ....


Top 50 recent answers are included