# Tag Info

## New answers tagged python

-1

import math def is_sum_of_two_squares(n): """Check whether n can be written as i*i + j*j.""" s = int(math.sqrt(n/2)) for i in range(1, 1 + s): j2 = n - i * i j = int(math.sqrt(j2)) if j * j == j2 and j > 0: return True return False T = int(input()) while T>0: T-=1 n = int(input()) if ((...

2

Style Various tiny improvement can be made to make your code more aesthetically pleasing without changing the actual behavior: removing trailing whitespace removing useless parenthesis removing whitespace before colon improving the function names for something which brings more meaning defining docstrings for your methods I would highly recommend ...

2

You can speed it up by saving the squares in a set. If you wrote a function to do this, you can give it a mutable default argument for it to save all the squares instead of having to calculate them repeatedly. # dict used because there’s no insertion ordered set def sum_squares(n, saved_squares=dict()): # check for sum while saving squares for future ...

3

There is a potential race condition in update_display() def update_display(): sleep(0.5) while True: global pending_redraw if pending_redraw: <-- test flag device.display(output) possible race condition in between pending_redraw = False <-- clear flag time.sleep(0.2) If ...

3

my_first_c_program's answer is good and directly addresses your question. I'm just adding minor points and details about the rest of your implementation. (like doing the daily crossword ☺) Rather than a lambda, make the ordering key a method of the Player class. I don't suggest making it the innate ordering of Player though. It's not clear why you skipped ...

4

I will start by saying that I have no understanding of Daily Fantasy Football. Forgive me if I miss some important point. If I understand your rules quote correctly, individual players are subjected to the "stacking penalties". So this doesn't just reduce some arbitrary total score, but affects how each player is scored individually. Thus, you need ...

0

No one else has mentioned: Taking the mean of three uniformly random variables from 0-99 is the same as just generating one uniformly random variable from 0-99 (excepting fractional remainders).

14

Globals # TO-DO: GET RID OF GLOBAL STATE Yep. You seem to already understand this one. Having a reset betrays a place in your design that would be well-suited to an object that can be thrown away and re-constructed, which is usually a more useful model than existing state that can be reset. Moving on. Docstrings Rather than # parse_resp is the main function ...

2

Your def is_win(computer2, computer1): if (computer2 == "r" and computer1 == "s") or (computer2 == "s" and computer1 == "p") or (computer2 == "p" and computer1 == 'r'): return True could be shorter (and always return a bool, instead of True or None): def is_win(computer2, computer1): return (...

3

Good start! I like that is_win() and is_lose() are separate functions. They could be improved by returning the boolean directly. In general, if you have code that looks like if condition: return True else: Return False, it can be written as return condition directly. Also, is_lose() can be written as is_win() with the parameters swapped def is_win(computer2, ...

0

Not competing with @KellyBundy's linearithmic solution, but optimizing the quadratic approach: n | original AJ_no_islice superb_rain superb_rain_2 -------+---------------------------------------------------- 1000 | 0.13 0.07 0.05 0.04 10000 | 13.65 8.02 4.66 6.15 20000 | 60.31 35.07 ...

3

Your approach takes $O(n^2)$ time. Since n can be as large as 100,000, you'll likely need something better. Some benchmarks (inputs are the numbers 1 to n shuffled, and the table shows times in seconds): n | original AJNeufeld AJ_no_islice Kelly_Bundy -------+------------------------------------------------ 1000 | 0.12 0.07 0.06 ...

2

You’re right that you can shorten the penalization functions into a single general function. You can do it like this: def choose_players_to_penalize(team: Team) -> PenalizedPlayers: """ Returns list of tuples with players ids to be penalised and amount of points to be taken away from each of them. Raises ValueError if ...

1

Indexing in Python is relatively slow. If you have several thousand numbers, you are looking up number[i][0], and number[i][1] repeatedly in the j loop, despite those values being unchanged: You should find the following reworked code to be faster: from collections import Counter numbers = sorted(Counter(int(i) for i in input().split()).items()) sigma = 0 ...

6

Preprocessing Be sure to read superb_rain's excellent answer. The following code is meant as a preprocessing. It simply iterates over every single attack & defense configuration, and calculates the cumulative probability that the attacker manages to kill 0, 1 or 2 defense soldiers. It is slow, but it's not a problem since it's only supposed to run once ...

7

Python has an official style-guide, PEP8. It recommends using PascalCase for classes, so your class should be called Candidate. It also recommends using spaces after a , when passing multiple arguments to a function. The creation of the candidates is as simple as this: candidate_list = [Candidate() for _ in range(20000)] Note that the starting index of ...

5

candidate class should be named Candidate find_avg() is already covered by the built-in statistics.mean() candidates can be created by a list comprehension global variables such as candidate_list and candidate_selected_lucks can be replaced with return values import random from statistics import mean class Candidate : def __init__(self): self....

1

If you profile the code without using njit, you will find that most of the time is consumed in calls to randint and sort: atk_rolls = sort[n_atk_dice](np.random.randint(1, 7, n_atk_dice)) def_rolls = sort[n_def_dice](np.random.randint(1, 7, n_def_dice)) So, instead of generating and sorting those random numbers for each loop iteration, you could pregenerate ...

2

Your def evaluate(boart, turn): for pos in ([0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8], [0, 4, 8], [2, 4, 6]): if board[pos[0]] == board[pos[1]] == board[pos[2]] == turn: return 1 could be def evaluate(boart, turn): for i, j, k in [0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8], [0, 4, 8], [2, 4, 6]: ...

2

Well, an obvious improvement is not redoing work. You are currently doing twice as much work as needed because you don't save the results of the comparisons: def confused(sys1, ann1): predicted_true, predicted_false = sys1 == 1, sys1 == 0 true_true, true_false = ann1 == 1, ann1 == 0 # True Positive (TP): we predict a label of 1 (positive), and ...

0

for subentry in grid[row]: can be simplified as for subentry in entry:, meaning that you no longer need the row variable. As for That doesn't work : $diff <(python original.py) <(python my.py) && echo "No difference" No difference$ diff --unified original.py my.py --- original.py 2021-01-18 19:34:02.177350487 +1300 +++ my.py ...

8

You play with up to 199 dice per player. So most of the time, the attacker will attack with 3 dice and the defender will attack with 2 dice. As long as that's the case, you could simply pick one of the three possible outcomes (with precalculated probabilities) and apply it. Outline: def _attack_(n_atk,n_def): while n_atk >= 3 and n_def >= 2: ...

1

According to your guidances, I improved my code and it passed all tests. from collections import Counter number = input() p = int(input()) ans = 0 if p == 2: ans = sum(i for i, digit in enumerate(number, 1) if digit in {'0', '2', '4', '6', '8'}) elif p == 5: ans = sum(i for i, digit in enumerate(number, 1) if digit in {'...

7

I haven't benchmarked any of the following but I suspect that they can help you out. I'd check each alteration separately. First, selecting the number of dice (die is singular, dice is plural) as you have is confusing and probably slow. n_atk_dice = min(n_atk, 3) n_def_dice = min(n_def, 2) Second, using np.sort is (a) overkill for the problem and (b) ...

1

The issue that you're running into is two-fold. One, you're using bignum math instead of the much faster integer math. Since the original problem specifies that 2 <= p <= 10**9, integer math is certainly enough to deal with this issue (as Toby Speight's answer points out). The second is that you're enumerating all the (up to one million) subnumbers at ...

0

The question itself It's not great. The textbook makes some decisions that haven't done the programmer any favours. First, you will notice that the input and output are mirrored about the line $x=y$. This is not a coincidence: it's the result of the textbook using column-major order when row-major order makes much more sense in this context. Also, the grid ...

0

One thing we're missing is that we only care whether any substring is a multiple of the prime. That means we don't need to carry any state bigger than that prime. Consider this algorithm: initialize accumulator a with the first digit reduce a modulo p (i.e, a = a % p) if the result is zero, we found a multiple append the next digit (a = a * 10 + next) ...

2

If you say you get a 'time limit exceeded' message it would be interesting how large the string and the prime number and the time limit is. It seems that the prime is about $10^9$ , the string length is about $10^6$ and the time limit is about 2 seconds. You should use a profiler to find out where you spent the time in your program. I did this for a ...

0

They are not exactly the same, as they behave differently when given an invalid severity. For a fair comparison, the first example code should probably be something like: try: messages_dict = {'error':errors, 'warning':warnings}[severity] except KeyError: raise ValueError(f'Incorrect severity value: {severity}.') messages_dict[field_key] = message

3

It is not necessary to make a copy of seen when making a recursive call. Change seen before the recursive calls and then undo the change afterward. def dfs(x, y, seen, word = ''): """ Recursive Generator that performs a dfs on the word grid seen = set of seen co-ordinates, set of tuples word = word to yield at each recursive ...

3

Pre-compute your offset tuples for possible_directions Use type hints Use strings instead of character lists for immutable data Those aside, you should really consider avoiding printing every single line of output if possible. The printing alone, at this scale, will have a time impact. Suggested: from typing import Set, Tuple, Iterable Coords = Tuple[int, ...

0

It's not clear whether the parameters password and data should be passed as strings or as byte-arrays. Use type-hint annotations, or at least a doc-comment so that users know which they should be passing.

0

It's not clear why we need params={'__a':1}. Perhaps add a comment explaining why that is passed?

0

On the implementation of the dynamic The (first) value that animate passes to the update function as argument is the frame number, if you use that as dt you can expect some strangely accelerating particles. As your dynamic does not depend on time, the frame number should not enter the computation. The time step is a global constant related to the frame rate. ...

0

bashBedlam showed how to make it work, but you could write it better in a few ways. You could make each turtle object in a for-loop that iterates through a list of colors and y-coordinates. Then you could add each turtle to a list at the end of each of each loop. You could also pass the turtle list to the race function instead of having the function look for ...

4

This is fairly tight; I don't think there's much more performance to pull out without dropping into C. That said: possible_directions First, I would rename this to neighbors or successors; it's not really about direction but about the nodes in the graph that come next or are adjacent to your current node. Second, you can reduce the number of branches and ...

-2

You were almost there. In order for a for loop to work you need an iterator. So if you put your turtles in a list and then call your race function, it works as expected. I have modified you code slightly. from turtle import * from random import randint Andi = Turtle() Andi.color("red") Andi.shape("turtle") Andi.penup() Andi.goto(-300,200)...

1

The thing you're doing isn't OOP (object-oriented programming), and that's probably ok. OOP is just one way of structuring complicated programs, and I don't personally like the pure form of it much anyway. Your idea of making a function to handle repetitive code is good, but you're still basically writing imperative code. The function you've defined is a ...

3

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 ...

3

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 ...

2

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 ...

3

I would add some iteration to this, to reduce parts where you repeat yourself. Note that there are two things changing, the statistic you output (and its name) and whether you show it with the train or test results. The former is always constant, while the latter depends on your results, so I would pull the former into a global constant and build the latter ...

4

It is a bit weird to have two special cases and start with the case that it is neither of those. I would re-arrange your cases to if p == 2: ... elif p == 5: ... else: ... Unless you did this as a performance improvement, because a random prime is much more likely to be neither 2 nor 5, but in that case you should have some measurements to show ...

1

There is a method in bitarray.util called ba2int: from bitarray import bitarray from bitarray.util import ba2int ba = bitarray('1001') # 9 i = ba2int(ba) print(f'Value: {i} type: {type(i)}') # Output: Value: 9 type: <class 'int'> From the doc: ba2int(bitarray, /, signed=False) -> int Convert the given bitarray into an integer. The bit-...

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 \\$...

2

Global variables 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. For example if 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 ...

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 ...

4

If you have a regular pattern that describes what you want to do with a string, using a regular expression (regex) is usually a good idea. In addition to using re.split, as shown in another answer by @python_user, you can also use re.findall, which has the advantage that you don't have to manually deal with the opening and closing delimiters: import re re....

4

A Regex based solution >>> my_string_one '[A][B][C]' >>> re.split(r"$([A-Z])$", my_string_one)[1:-1:2] ['A', 'B', 'C'] >>> my_string_two '[A][B][C][D][E]' >>> re.split(r"$([A-Z])$", my_string_two)[1:-1:2] ['A', 'B', 'C', 'D', 'E'] You can use re.split with the expression \[([A-Z])\ having a capture ...

4

First, I need to say that this is a really cool project; quite fun. You ask: Other than consistency, would you see any advantages in using python? Bad code can be written in any language, but it's really easy to write bad code in PHP. At the risk of starting a language-religion flame war, there is not a single application I could in good conscience ...

Top 50 recent answers are included