New answers tagged

1

Are there likely to be some negative consequences of this decision? Absolutely. Calling help(DocumentObject) will not tell you what Property attributes exist in your class. An IDE won't have any information for autocomplete. Eg) Typing brick. and pressing the <TAB> key won't offer length and width as possible completions. Callers can add, remove and ...


2

Do not write trivial getters/setters; this is not Java/C++/etc. It's more Pythonic to simply have everything public under most circumstances. Private-ness is not enforced anyway and is more of a suggestion. Consider using @dataclass You can drop empty parens after your class definition Under what circumstances would it be possible for properties to be ...


1

In Python, you don't need to create your variables before using them, so the address = '' before your loop is unnecessary. You also don't need to reset a variable before using it again, so the address = '' at the end of each loop iteration is particularly unnecessary. You currently get the addresses from the DB and then concatenate parts of that address as ...


1

In terms of chess you seem to have missed some things (in addition it would be rare with such a tournament) that will require updates in the logic: If the number of players is not a power of two (there is likely to be some no-show) you will fail in make_pair as you will have an odd number of players and select one player and then not have an opponent. I ...


2

How do you describe this function / math problem? The input is a list of tests with the same duration. For example, \$input=[2,2,2,2]\$. Given the indexes from 0 to 3, we can see it in a graph: So we can define the input as a (discrete) function \$f(x)=2\$, or in general \$f(x) = seconds/tests\$. Where \$0<=x<=tests,x∈Z\$. The function \$...


1

one major suggestion - don't (over)use global variables, it's generally not a good practice and it will make more difficult to test the code. And for example you'd like to add a functionality for downloading multiple items at the same time you'll have a hard time with it. So instead of this: def av_select(): global av_switch # this function is setting ...


1

Right now the program will have a problem if you use a word which has the same letter more than once. string.index will only return the index of the first occurrence. What you could do instead is use a set to check what letters still need to be guessed. If a character in the word is still in the set, it hasn’t been guessed and an underscore should be printed....


0

Test harness: To build a modular test rig around this, it seemed easiest to wrap stuff up in a class. I'm pretty sure I left everything else in the original implementation alone. I'm just using time to measure how long the function takes with various input values. I'm too impatient to run it with your original parameters, so I'm mostly using smaller ones. I ...


3

Your current way of pairing players is \$O(n^2)\$ due to using the remove method. Each remove is \$O(n)\$ since all the values that come after the removed value need to be moved back 1 index position. To make the whole function \$O(n)\$, you could use random.shuffle instead of random.choice. You could do something like: random.shuffle(self.players) for n in ...


8

In addition to what @Reinderien mentioned, here are a few things I noticed. It would be beneficial to store the players and ratings in a more meaningful format PLAYERS = [ Player(name, rating) for name, rating in [ ('Jimmy', 600), ('Samie', 900), ('Elani', 400), ('Aron', 700), ('Emir', 1000), ('Sven', 1100), ('Nelson', ...


6

Use immutable sequences Turn NAMES = ['Jimmy', 'Samie', 'Elani', 'Aron', 'Emir', 'Sven', 'Nelson', 'Antonio', 'Isabel', 'Wally', 'Li', 'Noam', 'Francis', 'Danya', 'Danny', 'Engine'] RATINGS = [600, 900, 400, 700, 1000, 1100, 1300, 1500, 1600, 1800, 2000, 2200, 2300, 2650, 2500, 1000] into tuples instead of ...


2

I think your current code is working- it seems like it’s getting the same answer as other people who say they solved it (i.e. 23514624000). So I think it belongs here. Right now, if you wanted to use this for any string of digits and any length of consecutive numbers, it would be \$O(n^2)\$ time complexity because you would have to multiply at most (length-...


1

This first, superficial refactor does the following: Rearrange functions in order of dependency Represent the return value of get_multipliers as a range and not a list for greater efficiency You're accepting a fraction, not a percentage; your inputs are -1 through 1, not -100 through 100 some minor variable name abbreviations convert duration_spread to a ...


2

I suggest to refactor it as follows: import random def guess_number (answer): for num_tries in range(5): try: guess = int(input("Your guess: ")) except: break if guess < answer: print ("Too low") elif guess > answer: print ("Too high") ...


0

Apparently, the problem was that I needed to save a reference to the image, as: my_label.img=my_img1 It worked immediately. However, I don't know why this fixed it


1

What I have to add here, is that you should always validate/sanitize user input. guessing = int(input("Your guessing is? ")) Converting plain user input to an int, without checking, is prone to cause problems. I would suggest creating an isInteger(something: str) (something will always be a string) function to validate that. def safeInt(something:...


2

This might seem a bit much, but I'm reviewing this as if it were intended for production code: black and isort can reformat this code to be more idiomatic without changing the functionality. pylint, flake8 or both can tell you of some issues with this code: $ pylint --disable=missing-function-docstring,missing-module-docstring q.py ************* Module q ...


0

results of benchmarking various solutions from slowest to fastest using timeit(): building a list and appending to it: (52-55 seconds) def XORsubqueries(array, queries): result = [] for pair in queries: value = array[pair[0]] i = pair[0] while i < pair[1]: if pair[0] == pair[1]: result.append(array[pair[i]] ^ array[pair[i]]...


0

I would guess the biggest slowdowns are the append and list functions. In your second example, you attempt to pre-create a list, which is a good idea, but a) you use the wrong size, and b) you never use the created list. Here's an example using a pre-made list: def xor_subqueries(array, queries): result = [0] * len(queries) for i,q in enumerate(...


1

I think this is a strange use of the path library: "/" + path.join('sys', 'class', 'leds', 'system76_acpi::kbd_backlight') + '/' It would be clearer as a single string, given that we don't need portability to non-Linux hosts: '/sys/class/leds/system76_acpi::kbd_backlight/'


2

Your option1 and option2 functions are a bit confusing in that they use val_am, but up until that point, val_am hasn't been assigned yet. This forces me to read ahead a bit then scroll back a bit if I'm trying to follow the data, and also opens up the possibility of accidentally calling one of those two function before val_am has been set if you refactor ...


1

Validation This function _is_player_id_list_valid is stuck between two useful concepts - validating and returning bool, and throwing-or-not. Don't attempt to do a half-measure of both. Given its current name, it would be less surprising to do for player_id in provided_player_id_list: if player_id not in all_player_id_list: return False return ...


1

Unless I missed a major announcement regarding very new versions of Python, this isn't a proper type hint: def divide(parts: [str]) -> int: To type-hint a list, you need one of: from typing import List def divide(parts: List[str]) -> int: # Python 3.5+ def divide(parts: list[str]) -> int: # Python 3.9+ You have another bug as well: for e in ...


1

I think you overengineered this solution. Below is a barebones implementation in one file. The focus here is on keeping the runtime logic as simple as possible. That is, if you wanted a more robust system for adding operations, it should ideally still compile into a simple structure like a dictionary of operations before the calculator even begins. from ...


4

There'sa bug in your square and square_root functions: def square(self): self.set_prev_expr() if True: # If the last number is in paren applies to entire paren block match = re.findall('\[[^\]]*\]|\([^\)]*\)|\"[^\"]*\"|\S+', self.expression) print(match) try: last = float(...


7

Separation of business from presentation It's mostly good; Calculator is effectively your business layer. The one thing that creeps me out a little is using a tk.StringVar in it. One way to have a "pure" Calculator that has zero requirements on tk is to accept bound function references to answer.set and equation.set as arguments to your constructor....


1

Here's my attempt at trimming it down. Note that there's no real reason to prefix variables with the_. Also list comprehensions can help with making code more concise, removing the need for total_triangles() entirely. def make_triangles(lines: [(float, float)]) -> [(float, float, float)]: """ :param lines: the lines to make ...


1

Making an str(which makes a string from an object) for the node class which would simplify the graph return method the str converts an object to a string type is this a dense graph or sparse graph? Sparse Graphs have a lot less edges between vertices Sparse Graphs can be efficently used as adjency lists Dense Graphs can be efficnetly represented with an ...


7

Rather than using as e then raise e you can just omit e. except KeyboardInterrupt as e: raise e except KeyboardInterrupt: raise Rather than specifying an except block for KeyboardInterrupt and SystemExit you can just specify them in the same except by passing a tuple. except KeyboardInterrupt: raise except SystemExit: raise except (...


0

I would approach this a bit differently. Let's employ a bit of design to construct our function. What does the user of the function choose, versus us that write it? From your question we can gather that the user chooses a callable, the interval and maybe whether it is called indefinitely or stopped at some point. This becomes our starting point when we ...


1

This answer is meant to be for beginners from a beginner. I try to incorporate best practices as explained by Lev M. while not changing the original structure of the code too much. I guess the most important take away is to follow the DRY principle as much as possible. I changed the structure of the shop items to lists for easier access. The shop level then ...


1

Style: This is the exact same algorithm, with the code-format, variable-names, and the use of strings cleaned up. I'm not actually sure this is the exact same function as yours, because the way you were using strings was probably wrong (because of the ' '.join(...) in the surrounding use-code). def original_solve(N, T1, T2): final_list = [] for ...


6

Other minor points: Generators Your generator - for line in s: yield line.replace('\0','') can be simplified to return (line.replace('\0', '') for line in s) To see what the difference is, we borrow from some techniques in a different answer: >>> def f(): ... for c in 'a b': ... yield c.replace(' ', '') >>> def g(): ... ...


4

"Current" directory Your get_cwd is problematic for a list of reasons: It does not get the current working directory; it sets the current working directory and returns that, which is a surprising side-effect given the method's name It's not the current directory you're after; it's the directory of the source code Spooky changes based on OS that ...


15

There's A LOT going on in your code but I'll try to give you some hints and some suggestions regarding the overall structure/workflow of the code. you have really abused the use of globals in your code. Some of them don't even make sense. I'd suggest you try and understand what the use of it is and stop using it unless really needed. For example, the use of ...


4

First of all, your function doesn't return anything and so you can remove -> bool since it only creates confusion. You can either use -> None or use nothing at all. Still related to type annotations, I find it kinda hard to read your code with annotations everywhere. This is subjective and it's just my personal preference but I usually tend to use type ...


0

For an application like this, the builder pattern might be overkill. Your entire runtime logic for the Network object can look like this. class Network: def __init__(self, sort, color): self.sort = sort self.color = color Similarly, a network can be built using very simple lookups from your table. def build_network(sort_name='asc', ...


1

I don't see any obvious improvements to your algorithm. Tests: Your "main" section seems to be checking if the algorithm works, but you can make better use of the examples provided with the original prompt. Constraints: The original prompt makes certain promises about the inputs. It's reasonable to just take those as assumptions, or (maybe better, ...


6

Your speed-up claim: avoid loading the whole file at once, instead parsing a file line by line, which seems to be 2x as fast according to testing seems highly unlikely, and I would like to see proof of this. A compiled-and-tuned built-in JSON parser that operates on an in-memory buffer is nearly certain to outperform a non-compiled, non-built-in, line-by-...


2

This looks like a nice game. Let's see how we can improve your code. we can STOP using ;. This is Python, not C / C++ / Java etc reorder your code so that it reads easier. rename your functions / variables so that the words are delimited by _. we can use the string stdlib library to generate your alphabets without repeating ourselves so much: import string ...


3

I don't know what you mean by "more easily", but here are some comments on the code: No error handling In many statements like i=int(input());list.append(alphabet1[i-1]) you use user input directly to index a list, without checking if it is in range, or even if it is a number. One wrong keystroke from the user and the whole program crashes. Mixed ...


1

The biggest change needed here is to delete your DataReader class, replace direct use of Numpy with Pandas (which wraps Numpy), and use named columns in your dataframe instead of numeric indices. Pandas has excellent built-in support for CSV operations and structured tabular data where column names can be used to make the code more legible and robust. For ...


3

File storage Text files are not convenient for lookups. So your next logical step should be to learn about databases and SQL. With Python you can use SQLite to build a small, self-contained database file. Security Entering a user name is not enough, there should be a password too. I am assuming this is for a family business or a small circle of very trusting ...


8

Parametric files It would be trivially easy to have Conference accept filenames as parameters to its constructor, and will make this more usable. Variable names Track should be lower-case. O is a poor choice of variable name for a list of reasons: It should be lowercase It looks the same as a zero Generally speaking, single-letter variable names are ...


2

Namespaces... ... are not for creating taxonomies. They are there to avoid name collisions. Also the chosen module alias for argparse seems strange. It's name is derived from argument parser so, if any, the obvious abbreviation should be ap. However, it might be better to just import the needed names, instead of creating taxonomies, since there are no name ...


4

Functions Study functions. Your code would greatly benefit from breaking up into functions. Bugs User Management If you add the name "Anne", you cannot login with the name "Anne" until you quit and restart the program. If you remove the name "Anne", you can still login with the name "Anne" until you quit and restart ...


2

Try using pathlib over os when you're dealing with file/glob operations. It has a lot cleaner interface, and is part of standard library in python 3. Name constants in your code with the CAPITAL_SNAKE_CASE. It is recommended guideline from the PEP-8. Split your code into individual functions doing a single task each. Put the execution flow for your code ...


1

Function Arguments def get_lower_upper_limits(inps): ranges, multipliers = inps ... This is a curious choice for declaring arguments to the function. You must package two arguments together as a tuple for the inps argument, without any clear indication to the caller of the requirement. Why not declare the function as: def get_lower_upper_limits(...


4

This function is quite complicated. You should consider writing tests for it. For example: If the code you gave is in a file named shop.py. Put the below code in a file called test_shop.py: from shop import shop from unittest import TestCase from mock import patch class TestBuyingThings(TestCase): @patch('shop.input', return_value='3') def ...


2

Firstly, I really enjoyed reviewing this code, it is very readable and understandable. The code looks nice. I would just highlight few things that might be improve Reduce the use of Globals You want to always reduce your use of global variables. In your program, you have a lot of global variables, you can eliminate all of them by encapsulating them in a ...


Top 50 recent answers are included