New answers tagged

0

Normally, we don't want to repeat a certain line (or lines) a number of times. It makes the code long, and unreadable. Also storing the numbers in variables isn't so good because we don't want to create 100 variables to deal with 100 numbers (or even much more). The Solution: We use loops and lists. We use a loop that runs 10 times, each time we get an input ...


0

Write a Python program to input 3 numbers and find the largest. Print all the numbers, and the largest among them, with appropriate titles. n1=float(input("Enter number 1: ")) n2=float(input("Enter number 2: ")) n3=float(input("Enter number 3: ")) if n1 > n2 : if n1 > n3 : LNo=n1 else : LNo=n3 else : if n2 &...


0

@Airistotal already provided a nice review, I will focus on the generator part. I wrote this code for a fibonacci sequence generator In Python, a generator is a function that behaves like an iterator. A generator yields items instead of returning a list. An example of Fibonacci generator: def fibonacci_generator(b=1): a = 0 while True: ...


1

tldr; I'd say that this function is too complicated. Recursion should be avoided when possible as an iterative method is usually more readable and could be faster. Here's some other things to consider when making a recursive function: https://gist.github.com/abinoda/5593052#when-to-use-recursion-vs-iteration. I think that some of the naming is not as clear ...


3

As mentioned in the comments of another answer, you should use sets for membership tests whenever possible. Combinig this with building up uniques instead of cutting it down, we get this really simple implementation: def duplicates(numbers): uniques = set() result = [] for num in numbers: result.append(num in uniques) uniques.add(...


2

Check out unique's documentation again, it offers to give you indices: def duplicates(a): uniques = np.unique(a, True)[1] result = a == a result[uniques] = False return result


1

Deferring command execution with a simple lambda It is very similar to what you did, but no need to bring in heavier artillery like functools.partial, especially because you have no idea who is going to read your code and they may not understand it :( I'd go with def addText(self, x=0): if x == 0: button = Button(root, command=lambda: self....


1

Bundle your options You seem to have a series of variables that are similarly named and that encode options. Imagine you improve your calculator and it now takes 20 options. Will you have a variable for each one of them? Probably not! You can do several things here. The simplest thing is to bundle everything together in a list: options = [ st.checkbox('...


2

Bundle input calls: Like you said, some code is repeated. That's fine, you are here to learn :) The first thing I noticed was a bunch of ask calls in the beginning of many cases of your elif. What I thought was "why not bundle those together?" You could do this by writing an ask_multiple function that takes a list of prompts and applies ask to each ...


0

Your code is good code, I'd say. There's nothing wrong with it. The only thing is that you can write more or less the same algorithm in a much shorter way, and that essentially means you would refactor all of your code down to a single line. So, before taking a look at the boiled down version of what you wrote, let me just point out that variable names ...


4

Good first effort! On currentBudget: One of the things that is easy to tell you about is Python's context managers docs. The context manager lets you write code in a different context and takes care of preparing that context and cleaning it up. In your case, there's a context to deal with opened files :) So, instead of def currentBudget(): ...


1

On the style of the code: While I'm not saying the code is or isn't correct, there's some small tweaks you could make it to improve it's legibility: Spacing Write code like you would write English (in some sense :P). After commas you needs spaces, so do def crossover(p1, p2): instead of def crossover(p1,p2):; random.uniform(b[i][0], b[i][1]) instead of ...


0

One way to refactor the loop is to locate the desired rows with idxmax() and then index them in one shot: df = df[df.index < current_day] th_array = th_array[th_array < df.cumulated.max()] indexes = pd.DataFrame(df.cumulated.values[:, None] > th_array).idxmax() df.iloc[indexes] # cumulated # 2021-03-25 185 # 2021-03-30 ...


6

Never iterate over indices in python In Python this pattern is generally not recommended: for y in range(len(wordBanList)): if(Personne1 == wordBanList[y] or Personne2 == wordBanList[y]): printIt = 0 You almost never need to iterate over and access elements by their indices. Instead you should directly iterate over the elements of the iterable: ...


3

for y in range(len(wordBanList)): if(Personne1 == wordBanList[y] or Personne2 == wordBanList[y]): printIt = 0 This code is checking to see if Personne1 or Personne2 are in wordBanList and has O(len(wordBanList)) runtime time. You can change the data type of your wordBanList to set() and have a O(1) run time. So your code could be ...


1

Rather than os and os.path use pathlib.Path. def _save_config_data(content): CONFIG.parent.mkdir(parents=True, exist_ok=True) with open(CONFIG, 'w') as f: json.dump(obj=content, fp=f, indent=2) def _load_config_data(): file = CONFIG if CONFIG.exists() else DEFAULT_CONFIG with open(file, 'r') as f: return json.load(f) Your ...


2

How about unrolling the loop a bit, doing two steps per iteration so you don't need to "swap" a and b? (I'm not familiar with Cython, so didn't benchmark): cdef int fib_c(int n): cdef int a = 0 cdef int b = 1 while n > 1: a += b b += a n -= 2 return b if n > 0 else a


2

Using one less variable seems faster: cdef int fib_c(int n): if n == 0: return 0 cdef int a = 0 cdef int b = 1 for _ in range(n - 1): a, b = b, a + b return b Running your test on my machine: Original = 2.934 s Improved = 1.522 s


3

Reading into the question somewhat, there is emphasis on not only matching to a date pattern where the digits and separators are in the right places, such as 98/76/5432 which your pattern would accept; but to narrow this - with the pattern itself - knowing what digits are allowable in which positions. One basic improvement is to constrain the range of the ...


4

You can import and use datetime rather than validating date yourself. >>> import datetime >>> datetime.date(2020, 9, 9) datetime.date(2020, 9, 9) >>> datetime.date(1990, 2, 29) Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: day is out of range for month As such we can ...


2

Disclaimer: I'm currently the maintainer of python-telegram-bot. Hi. TBH I haven't tried to understand every detail of what you presented. I'd still like to comment on the design you chose to use methods of your custom classes as callbacks. More precisely I find it rather irritating that you define methods like class SEMarathonBotSystem: ... @...


4

This is a basic but important question. Most functions can be arranged to operate purely in the realm of computation: they take data as input, return data as output, and have no side effects in the "real world". Examples of side effects would include interacting with the file system or a database, getting user input, and printing. Basically ...


1

For O(n) space, I think you need to switch from your top-down DP to bottom-up DP. That lets you control the evaluation order so you can for example go row by row, and store only the numbers of paths for the current row. To simplify things, start with an imaginary row above the grid and say you have one path right above the real start cell and zero paths ...


3

Nice solution, few suggestions: Duplicated code: the functions len(memo) and len(memo[0]) are called several times. When working with a matrix is common to call m the number of rows (len(memo)) and n the number of columns (len(memo[0])). This can help to reduce the duplicated code. As @Manuel mentioned in the comments, m and n are also defined in the ...


2

If you are in an interview using Python, assume that the interviewer is reasonable and wants you to write fluent Python code. That means, among other things, taking advantage of the language's built-in powers: def defrang(ip): return ip.replace('.', '[.]') But let's suppose that the interviewer explicitly directs you to ignore built-ins and write your ...


1

Typos Globla -> Global Tookkit -> Toolkit? millesconds -> milliseconds Nomenclature By the PEP8 standard, your functions and variables would be called win_width win_height ball_diameter ball_count on_timer etc. And this is minor, but a name like moveTheBalls by convention would not include an article, thus move_balls. String interpolation "FD:&...


1

Typos caled everytime -> called every time MAX_CARACTERS_PER_SEGMENT -> MAX_CHARACTERS_PER_SEGMENT max_caracters -> max_characters And my first language is not French, but shouldn't Votre message dépasse le nombre de {{max_caracters}} caracters be Votre message dépasse le nombre de {{max_characters}} caractères ? Language consistency Your UI is in ...


0

If a factory pattern is indeed called for - much of the time it is not - there is an easier way that needs neither importlib nor explicit registration calls. If you follow something like this layout: mypackage/ mypackage/__init__.py mypackage/tracker_factory.py mypackage/trackers/__init__.py mypackage/trackers/type_a.py mypackage/trackers/type_b.py ... then ...


1

Another way that, as FMc's, has the advantage of not having to calculate/specify range limits (your 70 and i+10): from itertools import count, islice days = ['MON', 'TUE', 'WED', 'THU', 'FRI'] d = {day: list(islice(count(start, 3), 4)) for day, start in zip(days, count(5, 14))} print(d)


4

Overall I don't think the code is that bad, considering what is the purpose; but if you want to expand your game I think the greatest issue is the data structure. It'd be very easy to misplace some room or call it in a different way if you have to repeat yourself every time, so I suggest you to use a class to represent a Room: class Room: name: str ...


-1

Read about Python style guide (PEP8) Your case: PEP8: E302 - you have to write 2 blank lines before and after each of classes Both function and variable names should be snake-case (sendEmail -> send_email) Also: Don't be afraid of long names: it is a good practice to write self.notification instead of self.notif Use type annotations It is convinient ...


1

Review Imports import operator is being done twice, which is unnecessary. from itertools import combinations, chain: chain is never used, and can be removed. N Choose R As of Python 3.8, the "n choose r" function is built-in and can simply be imported: from math import comb. The function is never used, so may be deleted. Constants time_slots = 24*4*...


1

There's always the one-liner that assumes a is a row vector (1d array): (a.reshape((-1, 1)) == np.unique(a)).astype(int) This works by broadcasting the == operation. Let us see how. When you ask numpy to apply an operation, first it checks if the dimensions are compatible. If they aren't, an exception is raised. For example, try typing np.ones(3) - np.ones(...


5

One alternative approach is to take advantage of enumerate() -- which allows you to iterate over what could be thought of as a zip() of a list's indexes and values. To my eye, this version seems a bit clearer and simpler. days = ['MON', 'TUE', 'WED', 'THU', 'FRI'] d = { day : [ (5 + i * 14) + (j * 3) for j in range(4) ] for i, ...


9

Without seeing the rest of your code it's difficult to say how this is used, but I think your function has conflated logic and formatting, and formatting is being done too soon. You should hold onto real date information right up until the edges of your program when that's possible. The following demonstrates one way of keeping dates and moving them to the ...


8

Overall, it looks fine. I probably would've written it a little differently, and I'll explain the differences. import datetime def get_current_quarters(): """A function that returns an array with all the actual year quarters """ current_year = datetime.date.today().year quarter_values = ["31/03/","30/06/...


4

Interesting project, writing it python does come with some limitations. Numpy is mostly written in C and there are good reasons for it. The memory management is much better and most of the array-manipulation routines can be done in-place instead of copying back and forth. AFAIK, there is no equivalency for pure c-arrays in Python. A tuple is probably the ...


4

Remove sorted From the docs: numpy.unique returns the sorted unique elements of an array. You can simply remove the call to sorted: b = np.unique(sorted(a)) # produces the same result as b = np.unique(a) List comprehension In most cases you can and should avoid this pattern of list creation: result = [] for i in a: result.append((b == i) * 1) It can ...


2

Your implementation of Storage lends itself nicely to using a dataclass. from dataclasses import dataclass @dataclass class Storage: field1: str = "" field2: int = -1 field3: str = "" This makes your class definition really concise and readable and provides improved scalability and convenient implementations of built-in ...


1

it's a nice thing to teach your kid programming langage! I have several advises, ideas : 1: why use gif while those aren't animated, you could as well use png for those color styles. 2: second for your level layout, you can just store 1 value for wall and let decide the graphic render which part of your wall to draw (based on neighbooring cells), could even ...


4

I am looking for feedback on how to improve the professionalism of his code how to be more 'pythonic' The style you've used is atypical in Python as your code doesn't follow all of PEP 8. For example you've used camelCase rather than snake_case for function names and variables. Personally if your son wants to be a programmer, not a Python programmer, than ...


1

Looks fine to me, you could potentially shave off some repetition, but it's not like it matters that much for a small script. That said, I'd reuse the session, inline a few variables, fix the naming (constants should be uppercase) and use some standard library tools like os.path to make the script more error-proof. The list return type could also be more ...


0

I worked a bit on code and suggest that (i could encapsulate some parts as trivel suggest), what do you think ? I directly work with dictionaries and try to avoid redundance letting the try except jon in get_from_dict function. It looks better (but perhaps perform more slowly ...). def get_from_dict(dic, keys): """Iterate nested dictionary&...


-2

It's difficult for me to say whether this is well-written or not since there are no tests, and that's fundamentally your biggest problem. A complex regex like this couldn't represent a better subject for unit testing. It's already well-isolated, it's important, somewhat internally complex, and would benefit from spelling out exactly which inputs and outputs ...


4

You could use scikit-learn's TransformerMixin which provides an implementation of fit_transform for you (its implementation is available here for interest). I'd consider renaming RemoveScarceValuesFeatureEngineer to something that fits a bit more with other classes in scikit-learn. How about RareValueTransformer instead? What do you want to happen if an ...


5

How about simply this? all_colors = set(img.getdata()) Or let Pillow do the hard work: all_colors = [color for _, color in img.getcolors()] Benchmark results along with the set comprehension solution on a test image of mine (since you didn't provide any): 113 ms set_comp 68 ms set_getdata 1 ms getcolors 115 ms set_comp 65 ms set_getdata 1 ms ...


2

It isn't necessary to pass a list to set(). Use a generator expression: all_colors = set(pix[i,j] for i in range(width) for j in range(height)) or, use a set comprehension: all_colors = {pix[i,j] for i in range(width) for j in range(height)} I timed them by building sets of 1_000_000 items. On average, the set comprehension was a < 10ms faster and they ...


6

Here's a condensed illustration of how to achieve your stated purpose, namely to compute the outputs of a generator in parallel. I offer it because I could not understand the purpose of most of the complexity in your current code. I suspect there are issues that you have not explained to us or that I failed to infer (if so, this answer might be off the mark)....


2

A couple comments: _is_convertible_to_str() As you discovered, the second argument to isinstance() can be a tuple of classes: def _is_convertible_to_str(value: Any) -> bool: return isinstance(value, (str, int, float)) You can call str() on just about anything, so _is_convertable_to_str() isn't very descriptive. I'd drop the _is_convertible_to_str() ...


1

To emphasize what Reinderien already said, always check the return of your calls to requests. status_code should return 200. If you get anything else you should stop and investigate. It is possible that the website is blocking you and there is no point running blind. Also, I recommend that you spoof the user agent, otherwise it is obvious to the web server ...


Top 50 recent answers are included