31

I've heard of dictionary lookups but I don't really understand what they are so if anyone thinks that they maybe relevant and could show me how to implement it that would be great! Here you go! Use Dictionaries! The entire if/elif/else if yelling, if not screaming, to be put into a dictionary. This is a lot faster than your implementation because it's a ...


4

Here enemy_locations = np.where(grid == 2) enemy_locations = ((x, y) for y, x in zip( enemy_locations[0], enemy_locations[1])) the x/y-coordinates are swapped, and later the x-coordinate of each enemy is subtracted from the y-coordinate of the friend, and vice versa: moves = [sum((abs(friendly_coords[1] - enemy[0]), abs(friendly_coords[...


3

Probably the most important thing is to reduce the amount of nested loops. It looks like it's currently n^4, so for every 1,000 items it'll loop around 1,000,000,000,000 times. I solved a similar problem once by having an initial loop which mapped the data structure into a less deeply nested form, and then I didn't need to do as many nested loops. Also, as ...


3

I think what greybeard is getting at in the comments is that you could get away with squishing these images much more than you presently are. It sounds like you're basically using the reduced versions as thumbnails, but these "thumbnails" are almost twice the width (over three times the area) of a standard HD monitor. Dropping basewidth to 1920 (or ...


3

First of all, as per PEP8 I'd recommend you follow the best practices. Naming conventions allNagiosInfo -> this is most likely a constant, so: ALL_NAGIOS_INFO nagiosEntry, nagiosBaseURL, nagiosUsername, nagiosPassword, nagiosAuthType -> nagios_entry, nagios_base_url, nagios_username, nagios_password, nagios_auth_type. And so on with the naming, you got ...


3

Is numpy a good candidate module for this? Using numpy is fine, but you can get by just fine without it. Borrowing Martin R's wrapped_distance function, you could solve the problem without any external libraries as follows: def coordinates(matrix: List[str], subject: str) -> Iterable[Tuple[int, int]]: return ((r, c) for r, row in ...


3

Well, your biggest problem is the length of the scope of variables. You declare/define all the variables at the beginning before all the code. This is not required, nor is it any good. When I try to read the code I have no chance to find the usage of variables as I have to scan all(!) lines if it is altered somewhere. Such long scope is real evil. As you ...


3

Your code is small, but there's a lot going on that I find it hard to understand. Given that this is just the beginning, the complexity of the code will just increase as time goes on. I found the large amount of globals to hinder readability, as each time I came across another I had to scroll to the top of the code to find out what it is. Whilst I prefer ...


3

Towards better functionality and data structures prefer f-string formatting over multiple strings +- concatenation: f'_nl{EXT}', f'_en{EXT}', f'_de{EXT}' define constants WHITELIST and SUPPLIERS as immutable data structures to avoid potential/accidental compromising by subsequent callers. Furthermore, making WHITELIST a tuple helps solving the mentioned ...


2

The minor problem is that you are printing the result in the wrong place. The major problem is that n may be up to 100,000. This means you need to run 10,000,000,000 of your inner test. And you may have only 0.02 seconds to do that. The trick to dealing with that is probably to determine the maximum possible score of a given i and l[i], and skip the ...


2

General comments The parameters you're passing in to almost every function collectively represent the current game state, which is perfectly fine for this style of programming which favors using functions over classes. Some might prefer modeling Hangman as a class with the game state, i.e. word and guessed_letters, as instance variables, but both styles are ...


2

if correct_answer == 'True': self.correct_answer = ['yes', 'y', 'f', 'true'] elif correct_answer == 'False': self.correct_answer = ['no', 'n', 'f', 'false'] f is recognized as a correct answer for both True and False answers, so I can collect all the points without knowing the correct answer to any of the questions by consistently answering f. This ...


2

Use a dict comprehension to keep track of the last index for each order_id_local and skip blank entries: local_ids = {order['id']['order_id_local']:n for n,order in enumerate(data) if order['id']} Then reverse sort the dictionary keys by their value and slice off the first 3: sorted(local_ids.keys(), reverse=True, key=local_ids.get)[:3] result: ['...


2

Have you considered to split up your run_complete_flow() function? Personally I would prefer to put it in a class. The first part up to run_game would go into __init__(). Then I would try to split up the task into methods. E.g. you have a comment # in this case we only need to find the power button, not click it - why not put that code in a method like ...


2

Obvious (dumb) point - I'd suggest using logging instead of print I would have some kind of builder for _CFG so I could choose if I use environment variables for configuration or something else Instead of str.format, you may want to use fstring: f"{_CFG["user"]} connecting to {_CFG["database"]} on {_CFG["host"]}." Instead of yield None you may want to ...


2

Since letters is a list of characters (1 length strings) you logistically have made letters a string. And so you can simplify writing it as a string rather than a list of characters. letters = "ABCDE..." You can remove the need to define letters by using string.ascii_uppercase. It's good to see some type hints. Good job! I would suggest changing your ...


2

Your solution just doesn't work Your validation check always fails. Yes int(value) != int is always true. I don't think an instance of a class will ever be the class that it's an instance of. Your mutating a class variable. The tool you're utilizing forces you to take instances, normally there's a pretty good reason. If we remove the previous error and run ...


2

Coding style There is a well-established coding style for Python, the PEP8 coding style, and conformance to that style can be checked online at PEP8 online. In your case it reports “missing space around operator” in almost every code line. Fixing those issues increases the legibility of your code. Program structure It is better to separate the I/O from ...


2

So there's couple of things you can improve: a,b=str(input()).split(' ') a,b=int(a),int(b) cdiv=[] #list to store common divisors num=2 if(max(a,b)%min(a,b)==0): c=min(a,b) for i in range(2,int(c**0.5)+1): while(c%i==0): cdiv.append(i) c/=i if(c>1): cdiv.append(c) else: while(num<=min(a,b)//2): ...


2

I think that it's a bit weird to use classes as a way to return values, I don't know if that's common in python, but anyways. The problem with your code, in my opinion, is that if you are converting a unit to another, ex: cm to in, you don't need to create a class that will store information about other units, like: inches to m. That ends up happening in ...


1

You need to fix indentation for the program to run (the fix is easy though, just look at the elif branches on line 102 onwards). What you've essentially done is an explicit if-else structure where you've hardcoded all possible positions. While this works, it's quite difficult to read and it's easy to make mistakes. Thus, it would be a good idea to use a ...


1

Let me offer the following rewrite of your program and then let's walk through it: names = {'Addition' : '+', 'Subtraction' : '-', 'Division' : '/', 'Exponentation': '**', 'Radicalization': '**(1/' } print("Operations that you can use:") for op in names: print(op, names[op]) ops = { '+' : (lambda x, y:...


1

Basically you only need to iterate up to sqrt(a) because the inverse of every factor <= sqrt(a) gives you the one which is greater than sqrt(a). See the following code example: import math def factors(a): ans = set() for i in range(1, int(math.sqrt(a)) + 1): if a % i == 0: ans.add(i) ans.add(a // i) return ...


1

Just some general thoughts since I am not familiar with the ECM algorithm you are using: The standard implementation of Python is interpreted. The Python executive is switched to for every line of your source. Thus idiomatic Python will use Numpy or other libraries to express the algorithm as calls to matrix routines or as operations on complex values or ...


1

If "My target here is speed!" (and assuming you mean speed of execution) then the best advice is to move it into a compiled language. There are many, many benefits to Python but execution speed is seldom one of them. The first step, as Andre O suggested, is to get a good algorithm. Python can be very helpful with that. The standard profile module can ...


1

First of all, as per PEP8 I'd recommend you follow the naming conventions. A couple of examples: updateStates -> update_states defaultValue -> default_value I think you were headed in the right direction, but instead of overriding the __get__ and __set__ methods, I would just override the __add__ method, which would allow you to reuse the updateStates ...


1

There are still a couple of rouge non-PEP8-compliant variable names: serviceAll and hostsAll. This is a minor detail, but to avoid too much nesting I would suggest inverting this condition if response.status_code == 200:. Then you can write it like this: if response.status_code != 200: continue # or raise an exception html = BeautifulSoup(response....


1

Here is my updated script. Notable changes include the use of NEAREST instead of ANTIALIAS, as well as the inclusion of an EXIF copy and paste. I think the major hang on the original script was the inefficiency of ANTIALIAS, as this script gives me around 95% compression in about 2 seconds per image. from PIL import Image from pathlib import Path import os, ...


1

solve() shouldn't print anything, much less all the intermediate results. It should end with return ans and the main program should print that final result. You'll get the same answer for (i,j) as for (j,i), so for the inner loop j never needs to be less than i. The expression abs(l[i] - l[j]) + abs(i - j) gets calculated twice. Instead, assign the value ...


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