New answers tagged

0

As mentioned in the answer by Roland Illig, there is a module for that. Example: from urllib.parse import urlparse def get_domain_name(url: str) -> str: """Return domain name from URL """ parsed_uri = urlparse(url) return parsed_uri.hostname get_domain_name('https://www.ucl.ac.uk/alumni/services') Result: 'www.ucl.ac.uk' NB: this ...


0

Even if you didn't ask, I would just go ahead and comment on the code. Please use following so that you don't need so many lists. First use a dictionary: list_dict = {} i = 0 while i < (len(keys)) - 1: if 'a' <= (keys[i][0][0]) <= 'z': list_dict[keys[i][0][0]] = keys[i] else: #ignore pass i += 1 And second use ...


0

You described the idea very clearly, thanks for the example that you gave. The code looks only half-baked though. The most important part in getting the code right is to know all involved concepts and how these are called officially. When you know the correct names, you can search for them, and most probably someone else has already programmed everything ...


2

So it seams like you have a Pandas dataframe you are working with. At the moment it looks like this section of code does the following worldCases = [] for i in range(0,len(dd)): #iterate through all dates count = 0 #setup a counter for j in range(0,len(dd)): #iterate through all ...


2

Here is a simpler method that has the following advantages: No need to create a custom TestCase class. No need to decorate every test method. Use the unittest standard load test protocol. See the Python docs here. The idea is to go through all the test cases of the test suites given to the test loader protocol and create a new suite but with the tests ...


1

Quite nicely done. However there is always room for improvement. In order of severity Looping You do def estimate_triangle_probability(): num_success = num_attempts = 0 for _ in range(10000000): num_success += 1 if try_one_triangle() else 0 num_attempts += 1 If you were to need the loop counter inside the loop you would rather do ...


0

After battling off-by-one errors, I managed to refactor after revisiting the computation model. import math def max_subarray_sum(A): def solve_partition(lo, hi): if lo == hi - 1: return A[lo] m = lo + (hi - lo) // 2 L = solve_partition(lo, m) R = solve_partition(m, hi) left_sum = -math.inf ...


3

If you want to get rid of the global t you could consider creating a class to manage the data and updating. I quickly whipped something together, although I'm not well versed enough in stats to have a good idea about what names would be more appropriate. from functools import lru_cache import numpy as np import scipy.stats as ss import matplotlib.pyplot as ...


1

This is a good start for a script. The next step should be separating in-/output from the functions doing the actual work. In addition, whenever you make multiple requests to the same server, you should use a requests.Session, which will re-use the connection. You can also pass a dictionary params which will be the URL-encoded parameters for the request. ...


1

The first for loop can be simplified a lot by using collections.Counter. The generation of the distinct category_prefixes using a set and the final category_count dictionary using a dictionary comprehension: db = PesticidalProteinDatabase categories = db.objects.order_by('name').values_list('name', flat=True).distinct() holotype_counts = Counter(category[:3]...


0

Python 2 is end of life, many core libraries and tools are dropping Python 2 support. Python is dumb. If you tell it to calculate (1/(new_height*new_width) each and every loop, then Python will. Your style is not Pythonic, you should have more whitespace. If we change one of the for loops in calculate_mean to math, we can see we can that ΒΆ2 isn't needed ...


1

Matrix indexing The display function is a handful. It's often better to use a matrix library like numpy to allow better indexing features. For instance, import numpy as np one_thru_nine = list(range(1,10)) print(one_thru_nine) matrix = np.array(one_thru_nine).reshape(3,3) print(matrix) print(matrix[0, 1]) print(matrix[1, 1]) print(matrix[2, 2]) [1, 2, 3, ...


2

A note on terminology, 14 has factors [1, 2, 7, 14] Usually these are called divisors, while the factors of 14 are taken to be only 2 and 7. The Algorithm While it is not entirely clear to me what you need the result to be, there is an alternative approach to finding the answer to the following question: Does the number have any factors that are not ...


1

Just one contribution from me: you can get rid of redundant declarations and make your code lighter. The newspapers should be defined just once and then reused. You are almost there. Build a list of dictionaries (or use a database). # dictionary for newspaper names and their links newspapers = ( {"name": 'Economic_times', 'url': 'https://dailyepaper.in/...


5

Criticisms Datatypes Your data types own data they should not own. A Brewery has an identity, a location, and a set of beer it brews. It should not have a "distance to home" parameter, or a "visited" flag. Distance to who's home? Visited by whom? Usability haversine() is not a very usable function; it requires 4 parameters. It would make more sense ...


0

(Other people have already mentioned use recursive backtracking, avoid all unnecessary copying, modify the maze in-place if needed, and use efficient search heuristics like A*.) Here's my other advice, you need a major refactoring for clarity (also performance): 1) Declare a class with methods, not lots of individual confusingly-named functions 2) Give ...


3

Combined imports from selenium.common.exceptions import ElementNotInteractableException from selenium.common.exceptions import NoSuchElementException from selenium.common.exceptions import ElementClickInterceptedException from selenium.common.exceptions import TimeoutException should be from selenium.common.exceptions import ( ...


2

Type hints You're most of the way to having a well-explained constructor: ticker (str): Stock-ticker Ex. 'AAPL' It's better to move that (str) to an actual type hint, i.e. def __init__(self, ticker: str): Superfluous methods As it stands, make_request doesn't need to exist. It would make sense to keep it if you add a Session instance to the class, ...


3

source directory Put the module in a separate source directory. This has the advantage that you can install this directory separately with pip install -e for example, or by adding it to a .pth in your virtual environments site-packages. You are using virtual environments for the development? tools Use a good IDE, and the tools available to improve your ...


2

Globals Generally speaking it's not a good idea to use globals like this. It harms re-entrance. What if you want to support two stopwatches at once, either in one UI or as a web server? Having globals like this will prevent that. It also harms testability. It is more difficult to test methods that rely on global state than it is to test methods that are ...


1

Debug prints I made a function to print out the BST and use it as a visual means of debug, if need be. The problem is this then facilitates needing a debug flag (which Python doesn't really have). I ended up not really using it since the unit testing was sufficient in this case. Is a visual means of debugging like this strictly discouraged? [...] ...


4

Usage of requests Strongly consider replacing your use of bare urllib with requests. It's much more usable. Among other things, it should prevent you from having to worry about an SSL context. Type hints def is_downloadable(url): can be def is_downloadable(url: str) -> bool: And so on for your other functions. Boolean expressions content_type = ...


7

Locations The location documentation is confusing. In getCutLists, the input defaults to './input/input.json' but in your main, the example in the documentation is 'localhost:8080/foo/bar.json' Is this a file path or a URL? Based on your usage it looks like it must be a file path, and the host and port shown above should not be there. Also, './input/...


0

Input One thing I would suggest is provide a hint to the user about the format of their coordinates input. It's not immediately obvious that the format should be x y. I had to look at the code to figure that out. Intuitively, one might expect to type in x and y on separate lines or maybe separate them with a comma. One way to deal with this is to add a ...


2

I could have used a cron job to run this every 5 minutes (without the while loop) but that seemed like unnecessary configuration fiddling, with the problem of which user to run under as well (a user with minimal perms, naturally). Instead of cron, you can register this as a systemd service with a timer. This elevates the timing out of the Python script and ...


2

Great Code & Question Your codes look great and you seem to be a Python master already, but I would just raise a very minor issue that I'm not even myself good at it (not to mention that I'm not really a code reviewer and here is a good review). You can certainly improve on naming your variables much better: just_built, maybe realtime_built or ...


4

This # Define the Rosenbrock Function def f(x_k): x, y = x_k[0, 0], x_k[0, 1] return 100 * (y - x**2)**2 + (1 - x)**2 could be def f_rosenbrock(xy): x, y = xy return 100 * (y - x**2)**2 + (1 - x)**2 This # Gradient of f def gradient(x_k): x, y = x_k[0, 0], x_k[0, 1] return np.array([-400*x*(y-x**2)-2*(1-x), 200*(y-x**2)]) ...


4

You biggest time waster appears to be this loop: while f(x_k + alpha * p_k) > f(x_k) + (alpha * c * (gradTrans @ p_k))[0, 0]: alpha = ratio * alpha f(x_k), c, gradTrans, and p_k are all constant in the loop, so you can compute f(x_k) and c * (gradTrans @ p_k) before the loop and use these computed values in the test expression, instead of ...


2

Your checks are inconsistent at best, and wrong at worst. Your code counts the number of winners in horizontal and vertical directions. And if this is greater than 1, you complain Impossible. However, you are ignoring any possible diagonal winners. But you are also forgetting it is possible to win in two directions at once. Enter cells:OXOX_XOXO -------...


3

Flat array for display It looks like display_field accepts a one-dimensional array. By the time you're manipulating it with business logic and presenting it back to the user, it should be a two-dimensional array. Rather than one format string, you would then call '\n'.join(). Presentation vs. business logic In several places your presentation ("Impossible"...


1

Unpacking arguments This: self.x = pos[0] self.y = pos[1] can be self.x, self.y = pos One advantage of the latter is that it will catch weird sequences that have more than two items. The easier thing to do is simply have a uniform representation of coordinates, and use x,y everywhere instead of a random mixture of tuples and individual variables....


-1

I ended up solving it like this: def check_valid(cell, n): lst = np.array(cell) right = np.diagonal(np.rot90(lst)) left = np.diagonal(lst) if len(set(right)) != n or len(set(left)) != n: return False for i in range(n): cols = lst[:, i] rows = lst[i, :] if len(set(cols)) != n or len(set(rows)) != n: ...


3

Tests Given something this low-level, as well as your claims that it solves specific clustering problems - you need to test it. The tests for something like this, thankfully, are relatively easy. You may also want to do some rough profiling to get an idea of how this scales in comparison to the built-in hash method. Type hints def __init__(self, items=...


9

Direct boolean return As @Grajdeanu Alex says, this: if (ab > c and ac > b and bc > a): return True return False can simply be return ab > c and ac > b and bc > a Type hints def can_form_triangle(a, b, c): can be def can_form_triangle(a: float, b: float, c: float) -> bool: Sort unpack first_point = random() second_point = ...


3

I echo Reinderien's and Anonymous's comments re your a, b, c, d. I suggest renaming your a and c to left and right, and your b and d to top and bottom. (Two-word names such as topleft are not appropriate because each of these variables holds just one coordinate, not two.) Then you needn't mandate which corner the user starts from. Let them start from any of ...


1

Don't keep copying the maze The current code makes a new copy of the maze each time moveToEnd() is called recursively. You know what change is made to the maze (the next move). So just make the change to the maze, test to see if it's solved, make a recursive call if needed. Then undo the move and try the next one. def moveToEnd(mazeMap): global ...


0

Copying multi-dimensional arrays Save yourself some work and use some already written functions. from copy import deepcopy def copy_maze(maze_map): return deepcopy(maze_map) At this point any reference to copy_maze can just use deepcopy, since using a function with its sole purpose to call another function is an anti-pattern. sum Instead of using a ...


1

Yes there is a solution. The obvious solution is of course to use loops. Here is my try using a composite dictionary. It is functionally equivalent to your code and will save you about a dozen lines but hopefully adds flexibility. This was a quick job, so maybe you can take it further. from PyQt5.QtWidgets import * import sys class ButtonWidget(QWidget): ...


1

There are some interesting ideas raised by this problem, guard clauses (or perhaps we should say short circuits) being one of them, we can extend if len(lst) % 2 != 0: return False with if len(lst) == 0: return True This raises the question (from the point of view of efficiency) which order should they go in? The answer depends on the expected data. ...


10

The one thing that is immediately apparent to me (before scrolling the code window) is the naming of some variables: a, b, c, d. Why not use more meaningful names ? You're not being billed by length of variable name. If they are coordinates just call them topleft, topright etc. Ditto with variables names like: pth = args['path'] outp = args['output'] intrv ...


2

Some of these are not performance improvements but are improvements nonetheless. Brewery constructor def __init__(self, _brewery, beer, distance=0, visited=False): self.beer = beer self.id = _brewery[0] self.name = _brewery[1] self.longitude = _brewery[2] self.latitude = _brewery[3] self.distance_to_home = distance self.visited =...


12

Standard case Class names like class screenshoter should be capitalized, i.e. class ScreenShoter. The standard Python code style (which includes recommendations such as naming conventions) is documented in the PEP 8 - Style Guide for Python Code. Static variables These: a,b,c,d = 0, 0, 0, 0 path = "" last_image_sum = 0 output_file = "" ocr_path = "" ...


2

Also, you can use random.sample(num_tiles, num_mines) to avoid repetitive mine spawning.


2

As @David says, extensive replacement of your os and shutil calls with pathlib will get you 90% of the way to a better solution. The one exception is shutil.rmtree which does not have a pathlib equivalent. I'll go through most of the instances. Immutable constants git_repo_tags = ['AB', 'C', 'DEF', 'G', 'HILMNO', 'PR', 'STW', 'X'] should be ...


4

This problem appears to be a poster child for basic object-oriented programming. But please note that I don't know anything about sports betting, so I'll probably get some of the details wrong. A good rule of thumb is this: If you find yourself switching on internal data, look for a class instead. In your case, you switch on bet_type, you switch on ...


6

Optional I find it less useful to include None in an enum like Evaluation, and more useful to write Optional[Evaluation] where appropriate. It's useful to be able to choose whether you have a value that cannot be None at a certain point, or otherwise, based on context. In other words, this: sentiment: Literal[ Evaluation.POSITIVE, Evaluation....


4

Tests You've written some - great! Keep that up. If you want to add more structure, consider Python's unittest library. Unused globals BET_OUTCOMES, SUPPORTED_BET_TYPES and SIDES are not used. My assumption is that this is related to the other segment of your code that you deleted. If it stays deleted, then delete these, too. Similarly, this docstring: '...


2

find_segment loads the json file every time it is called. It would be much faster to load the data once and return a dict mapping province to segments. Also, key doesn't appear to be used, so remove that for-loop def load_research(filename='research.geojson'): """loads json data from filename and return a dict of segments keyed by province.""" ...


1

Here's a solution that only uses one extra data structure. I use the heapq library to maintain a heap, where it easy to check the smallest item and remove it when it's not needed any longer. You could also use SortedList from the wonderful sortedcontainers library. The basic idea is to loop over the intervals sorted by start time. If some intervals have ...


0

Check out the pyinputplus module. It's good for when you are asking for specific user input, such as when you want the user to answer with 'yes' or 'no', or in your case, 'X' or 'O'. So in that case you would do something like this: from pyinputplus import * inputChoice(('X', 'O')) Which will return: Please select one of: X, O Alternatively, as a ...


Top 50 recent answers are included