New answers tagged

0

Depends on what you want to do with it. It seems a bit odd to store each top 5 in its own variable. For starters, you can slice a DataFrame by continent using .groupby: for continent, continent_data in data.groupby("Continent"): # `continent` is now the name of the continent (you don't have to type the continent names manually) # `continent_data` ...


1

Repetition You write: discriminant = b ** 2 - 4 * a * c followed by: if discriminant == 0: x_one = (-b + sqrt(b ** 2 - 4 * a * c)) / (2 * a) # x_one ... if discriminant > 0: x_one = (-b + sqrt(b ** 2 - 4 * a * c)) / (2 * a) # x_one ... x_two = (-b - sqrt(b ** 2 - 4 * a * c)) / (2 * a) # x_two ...


0

Your solution is broken. Consider: 1 1 1 1 1 99 It should be obvious the answer will be 101. >>> longest_slide_down([[1], [1, 1], [1, 1, 99]]) 3 >>> Your problem stems from: idx = pyramid[i].index(x) It doesn't handle the case when a number appears more than once in a row. Fix this issue, then post your corrected code as ...


3

Instead of using the isPalindrome function to determine if x + y is a length five palindrome, you can create the set of all length five palindromes in the range [10000, 20000) and check for set membership instead. Use the efficient method suggested by Sam Stafford to generate them. This does not change the time complexity, but should be faster.


4

Covering what others suggested (e.g. @Srivaths), please follow at least PEP8 Python PEP8 Then, put your code in some function. Give meaningful names to variables. (What's a, c, x, z ... why are you not using b? ) You don't need import math -- instead of f=row/2 f=math.ceil(f), you can do f = row // 2 (assuming you use python 3). Note that you can solve ...


3

Two opportunities for optimization that suggest themselves to me: Seems like you should be able to produce an exhaustive list of 4-digit palindromes by taking every 2-digit number and then appending its mirror to it, rather than having to iterate through every 4-digit number and throw most of them out. That would let you build your palindrome list in about ...


2

A few notes on your code above: connect_mssqlserver and connect_mysqlserver could be condensed to a single 'connect' function that takes a conn_str arg to be used in create_engine. I believe create_df seems to be unnecessary at this point. If the process for creating the df involves more than just calling read_sql in the future, then I would opt for moving ...


3

As @JanKuiken mentioned, your idea is probably clever, but I can't understand what your code does either! Please add it to the question if possible! You need more spaces in your code! Prefer += and -= operators as they are more compact than assignments such as x = x + 1. for variable in range(0, end) is not necessary as range starts the sequence with 0 by ...


2

To add to @AJNeufeld's answer, select_weapon and select_shield should probably validate their input. Those two functions could be refactored to remove duplicate code. def select_enum(enum_class): items = [f"{item.value}-{item.name}" for item in enum_class] items = ", ".join(items[:-1]) + " or " + items[-1] valid_values = set(item.value for ...


2

Good start but a few things should be cleaned up. Try to follow a standard. Preferably PEP8. You have extra spacing between = and no spacing between , in places and its messy. delete from tkinter import * this is for 2 reason. The first is you are already doing import tkinter as tk so you do not need a 2nd import of tkinter. Two import * can cause problems ...


8

Since I think this is worth more than just a comment on another answer, in your codes_from_csv you are (ab)using the new walrus operator. Assignment expressions are not the right thing to do here. What they do is assign local variables (outside of the function!), and then the values of those local variables (but not their names) are passed by position to the ...


6

All in all your code looks quite good, it even has documentation! It's interesting to see assignment expressions in actual use, though I have yet to decide if I'm a fan of them. But of course Code Review would not be Code Review if there was nothing to nitpick about ;-) As per PEP 8, isbn13(isbn, writer = ImageWriter()) should be isbn13(isbn, writer=...


1

Three things to add to MJ713's answer: For mutually exclusive options, use if ... elif .... When a match is found, the rest of the conditions are skipped. It may also help to put the order the tests so that the most common case is first and the least common case is last. dict.setdefault(key, default_value) returns dict[key] if it is in the dict. ...


2

There are a few points in the existing code that I think could be improved. Confusing function name write_new_json Naming is important. Good names make your code more readable, and easier to understand. Bad names make it less readable. Names are bad when they don't describe what the thing is/does, or conversely, if they seem to describe something that the ...


4

This looks like a interesting program. General It took me a while (a few seconds) to figure out the meaning of "i:" and "r:" in the docstrings, perhaps "parameters" and "returns" are more clear. function checkBrackets I do not see the use of the continue's in this case, the if-then statement will finish anyway quickly. I do not understand the variable ...


5

Since you mention that this was originally C++ code, well it shows. First, style. Python has an official style-guide, PEP8. It recommends writing if condition instead of if(condition) and using lower_case instead of camelCase for variables and functions. You should also have a look at the standard library and this excellent blog post about better looping. ...


2

Naming Function names usually read nicely as verbs, since they "do" stuff. So word_splitter() might be a good name for a class, some reusable thing that splits words, but as a function it reads more descriptively as split_word() or split_term() (or maybe tokenize_term()). Similarly, result_print() reads more smoothly as print_results(). It's a command, it's ...


2

Looks pretty good to me! I liked that you used type hints. A few tips: The library pathlib is very good for path manipulation. You'll still need os.walk in this case, but you can use it to get the full filepath, just the filename, the stem (filename without extension) or the suffix (extension alone). I use it a lot. You could use re.sub to take care of the ...


21

f-strings Beginning with Python 3.6, there is a friendlier way of formatting strings. Instead of using "format string" % (tuple_of_args) where the argument and the format codes are separated by significant distance, the arguments are embedded in the string itself, surrounded by {}'s. The string itself is prefixed with an f. For example, instead of: ...


3

isdigit() str.isdigit() does not do what you think it does. "1²³4".isdigit() returns True because all the character in the string look like digits, despite some of them being superscripts. You want the str.isdecimal() function, which returns True if all the characters are in the set of the 10 decimal characters (ie, base-10). Dictionaries You should be ...


2

You got yourself in trouble by using plt.pie, and especially the keyword argument autopct, beyond its intended use. The basic idea of the pie chart is to have the wedge labels outside the pie and perhaps percentages inside. You wanted the wedge label and percentage inside the pie and manipulated the autopct keyword with a function to achieve this. This ...


3

asathryne.py PlayerCharacter.learn_ability.check_ab This helper function can be reduced to one line: def check_ab(abi, abl): return any(a.name == abi.name for a in abl) The any returns True if any of the values passed by the iterator are true. In this case, if aname == abi.name results in a True value, then the function will return True. I've ...


1

your algorithm is flawed. you need to reset the array when you start a new sequence. keep a record of the current longest sequence so you can work out which is longest import copy arr=[5,2,7,4,3,2,0,8,9,100,99,98,97,93,92] z = [] l = [] for i in range(1, len(arr)): l.append (arr[i-1]) print(arr[i-1]) while( i < len(arr) and arr[i-1] - 1 == arr[i]...


0

The problem with the algorithm is: 1. there is no logic that recognizes the ending of the on-going consecutive decreasing sequence. 2. there is no logic that compares candidate sequences and tracks the longer one. If we walk through the code, we can see it encounters a sequence of 4,3,2 starting from 4th iteration and then it encounters a sequence of 100,...


3

I strongly feel that you should separate the logic of the graphics and the algorithm of solving the sudoku. The algorithm is just some operation defined on some data structure of your choosing (actually a good way to regard solving sudokus is as extending a colouring of a graph). I would write this algorithm to act on whatever data structure is most ...


1

Class Names Classes should be in PascalCase, not lowercase. So your class should be App. Operator Spacing There should be a space before and after every operator (+-*/=, etc) in your program. It improves the readability of your code greatly. Comments When commenting, it's common to put them a line before, so the reader sees the comment then the ...


1

In general visitor patterns in other languages are manage with tables, maps or any other struct/object type, here is the improvement that you can make on your code class TaxVisitor(CostVisitor): def cost(self,node): if isinstance(node, Milk): return 150 if isinstance(node, Sugar): return 100 if isinstance(...


1

Tkinter is already in a loop. The window handler gets all messed up because of your own loop, which is called synchronously. Effectively you're running a loop in a loop and wonder why the outer loop takes so long to get to the next step. That's because of the inner loop taking so much time. Long story short, your next window update will only commence once ...


1

Let's have async implementation: async def async_next(url): if url is None: return try: response = await async_send(url) return response.json() except HTTPError as e: if e.response.status_code == 404: return else: raise Then you can provide following sync bridge: def next(url): ...


2

First I got same approach than previous answers (@Roland Illig & Luapulu) that are very similar. But then I remembered Item 72 of Effective Python (Brett Slatkin's book): 72: Consider Searching Sorted Sequences with bisect. Python’s built-in bisect module provides better ways to accomplish these types of searches through ordered lists. You can use ...


9

Your code looks well-formatted, it's easy to read and to follow, and the explanation you gave matches the code exactly. Well done. :) for item in my_list: This statement looks strange since in the body of this for loop, you neither use item nor my_list. You can express the idea of that code more directly: for _ in range(len(my_list)): The variable _ is ...


12

Since the goal is the best possible implementation of this algorithm, I'd suggest the following. However, faster algorithms do exist. To conform to PEP8 make sure you have two blank lines after your imports and surrounding function definitions. Since, you aren't editing each item, but rather adding and removing items until the list is sorted, I'd use the ...


3

well done providing doc strings sticking to the Style Guide for Python Code makes Python code easier to grasp, especially for someone who didn't write it to make the naming more convincing, you should factor out sequential_deterministic_stand_in_for_seeing_the_required_result() and sequential_deterministic_stand_in_for_checking_the_result() As a bonus, this ...


4

There are a couple of issues with destructors, firstly is the issue with closing pipes on Linux/Unix as discussed here (though the pipe is actually no longer necessary once we fix the second issue). Secondly the functools.partial method appears to capture a reference to self which causes the wrapper object to not be destructed when expected, I have fixed ...


6

Quick bits You have some issues that some linters would pick up: I would suggest moving your main code into a function. So that it doesn't pollute the global namespace. You've got some trailing whitespace. Add some docstrings to your code. Even something basic like "Fetch words in answers." Your imports are kinda all over the place. I can't make any sense ...


2

I think iterators are amazing. However not everything should be an iterator, or use comprehensions. Statements like: Obviously I need to replace the loop with proper code. Only make me see short-sighted snobbishry. Which I only see in the FP vs OOP part of the programming world. Iterators and comprehensions can't and shouldn't be jammed into everything. ...


3

You don't need to actually build a whole list of the digits. It's unnecessary memory consumption. You can pass a generator to max. use python's -= syntax when subtracting from a variable. The break is unnecessary as it's covered by the while condition Final code: n=int(input()) count=0 while n: n -= max(int(i) for i in str(n)) count += 1 ...


11

To reduce memory usage you can exploit the mechanics of zip and iter / iterator / generator expression. Make tmp an iterator. You can achieve this by changing the brackets from [] to (); changing it from a list comprehension to a generator expression. You can alternately wrap the list comprehension in an iter call. However that would still be using \$O(n)\...


0

Use alphabetical order for imports import bpy import os import shutil import time


0

@Linny. First of all thanks for your solution. It's a real improvement and very good explained. This push me to try to enhance it even more. This new proposal is based on your solution, and it includes two additional changes. Both of them according to Jeff Bay's Object Calisthenics (some basic rules to write better Object Oriented code): Rule 2: "Don´t ...


3

A couple of things that I would suggest that you do: A level of nesting can be removed by using a generator expression to filter the list of files: files_to_convert = (f for f in os.listdir(path1) if f.endswith(".jpg")) for filename in files_to_convert: ... process the file ... Ensure that the listing of *.jpg are files, not subdirectories named *.jpg:...


5

function I would abstract this into a function you can call. Then you can also easily incorporate a few checks to see whether the source path really is a directory, that the destination path actually exists,... pathlib.Path Has a lot of convenience methods that help with file path handling. from PIL import Image from pathlib import Path def ...


4

In general the code is simple and concise. Depending on the target usage, apart from what other answers suggest, I would add: support for files ending on ". jpeg" not only .jpg; likewise I would make filename filter also find uppercase or mixed case JPEG files; if I had to deal with unreliable sources I would add also Image.verify() and/or imghdr checks to ...


15

Apart from what's already mentioned I would like to point out that the file super.picture.jpg will be converted to super.png That can be a problem if someone runs your program in a loop and iterates through a folder with files named anniversary.1.jpg anniversary.2.jpg.... Instead, because you have used endswith('.jpg') you can just use a substring of ...


5

So, you want to count something and afterwards get the top k? That sounds like a job for collections.Counter! from collections import Counter def leading_candidates(votes, timestamp, k): vote_counts = Counter(vote['candidate'] for vote in votes if vote['timestamp'] <= timestamp) return [...


10

Consider using __main__ to make your script easier to import (see here ). Also, consider the use of functions to isolate the different steps, so that it is easier to add new functionalities in the future. One last thing, you could use a more explicit log message, something along the lines of Converting {filename} from jpg to png instead of Lets go, maybe ...


29

The variable names path1 and path2 are bad since they are not as descriptive as possible. They should rather be srcdir and dstdir (if you prefer abbreviations), or source_directory and destination_directory if you want to have them spelled out. Instead of manipulating strings, it's better to use the pathlib library, which has the handy function with_suffix. ...


34

Not much to improve upon, just some minor housekeeping. Help the end user! If I was using this script, and forgot to put one or both of the filepaths when calling the script, there would be this error: IndexError: list index out of range. This error wouldn't help the user in a significant way. Consider this: try: path1 = sys.argv[1] path2 = sys....


1

Just have the time to take a quick view on your code, but one of the first thing you have to learn to do (before using design pattern and such things), is to refactor your code. By simply scrolling, we can see df_additional[col] more than ten times. For all the places where you just need to read this value, use a local variable to store it. If you need to ...


6

While working on my answer, @Graipher already introduced the idea of a generator. This generator variant does not rely on an external library, but should still be robust enough: import itertools import datetime from typing import Iterator FRIDAY = 4 def friday_13_generator(start_date: datetime.date) -> datetime.date: year = start_date.year ...


Top 50 recent answers are included