You're using dataclasses and typehints*, so you're doing reasonably well. Now you should learn about variable-length arguments. They're nicer (in my opinion) than checking to see if the argument is a list.
Also here's some fun with generators and unpacking, which may or may not be appropriate for your uses.
# totally untested.
def stocks(*codes: Union[str, ...
Prefer ordinary naming whenever possible. If a class is called Stock,
that's a perfectly sensible name: nearly all English speakers will correctly
assume that it refers to a single stock. That's how the language works and you
should use the language conventions to your advantage. There's no need to
overcomplicate things by giving the class a name like AStock....
You haven't said this explicitly, but I'm going to assume that you expect the subtraction of date and date_of_value to be in fractional days. This doesn't do what you think it does:
date_diff = (isbd["datetime"] - dsbd["datetime"]).days
Rather than the total fractional days, that produces the "days field" of a timedelta. ...
First, it's a bad idea to input your numerics as strings in your dataframe. Use plain ints instead.
Your code currently forms a predicate, performs a slice on the frame and then finds the size of the frame. This is more work than necessary - the predicate itself is a series of booleans, and running a .sum() on it produces the number of matching values.
This is so simple that there isn't much to improve.
In most cases you don't need a resolve() and should just omit this.
Use count += 1 instead of count = count + 1.
If you're always going to be checking for a prefix, use startswith instead of a regular expression.
Use path.open() instead of open(path).
from pathlib import Path
Don't rely on global variables. It's good that you are experimenting with
functions; however, you aren't really taking advantage of them, because they
operate on global variables rather than taking arguments. Global variables are
almost never needed.
Code repetition is a warning sign. The functions are repetitive: they all
contain the same conditional logic ...
If I want to use your functions; it'd be very hard.
I'd have to modify the global scope of the program and have to know the quirks around choose.
Always pass variables to functions as arguments.
def addition(choose, firstNum, secondNum):
if choose == 1:
print("Your result:", firstNum + secondNum)
Don't include choose in your addition ...
Your question and your code are both fairly confused, but let's attempt to dig into it anyway.
The return type of your function is a big, crazy mix of Python native sequences and Numpy arrays, when it should be a single two-dimensional Numpy array.
iter_func does a poor job of explaining what this is supposed to accomplish, but I'm leaving it for now.
Fiddling with bits is almost never fun. The crux of the problem is performing a matrix transposition on the bits. Performing this operation on Iterables is simplest as we can just use zip(*binary_string).
def binary_diagnostic_part_one(input_path: Path) -> int:
zero_counts = 
n = 0
with open(input_path) as f:
for bits in zip(*f):
I will first say, broadly: I understand that you're constrained by the demands of the assignment, but the assignment doesn't make any sense. It isn't your fault, but like - some of the features are pointless. Allowing the user to check whether a username exists in the list is pointless. There are ways to construct a semi-realistic scenario that exercise the ...
Don't use time.time; use time.monotonic - otherwise, certain OS time changes are going to deliver a nasty surprise.
Make a constant for your 120 seconds.
Is -> dict OK?
Not really. This:
params: dict = None
is first of all incorrect since it would need to be Optional[dict], which is basically Optional[Dict[Any, Any]]. Setting aside the outer ...
I'm just going to make one suggestion, which you should be able to apply across a lot of your code.
Use list structures, which are analogous to arrays in other languages.
That's it. Lists.
Use lists for counting values
Your first use should be to replace the 0/1 variables in counting code:
counter_1st_bit_0 = 0
counter_1st_bit_1 = 0
Let's make those two ...
Move your data, etc. out of the global namespace into functions
Rather than doing an even/odd check on an index, consider doing the slightly more Pythonic thing of a slice [::2] and zip
Consider making a generator function that converts deltas to height values
Separate your rendering code that uses /\ from your logical code that calculates heights
Avoid your ...
Global variables rarely needed. You have written most of the algorithm inside of a function, which is good;
however, you are not really taking full advantage of what functions offer. In
particular, they take arguments and return data. You aren't doing that;
instead, your function operates on global variables, which is bad in nearly all
Don't make the ...
Some simple things:
top and length could probably have better names (Top of what? Length of what?), maybe max_x, max_y? And print_list could be better as e.g. graph and populate_list as create_graph?
also print_list should probably be a local variable inside populate_list(), which can then return the list for you to print. Might also be better ...
You mostly follow PEP8 styling conventions, making your code quite readable. The only exception I see is an extra blank line at the beginning of the score and play methods.
Also, it is good thinking to wrap your game state into a class for future integration into a more complex project. It is also a good use of a main guard at the end.
Welcome to Code Review.
Your code is literally 4 lines. So there isn't much to review.
Do not use the is operator to compare the integers. See difference between is and ==
You can save the nested loop: you are already ensuring col == row so you can instead write:
for row in range(1,6):
print("* " * row)
If we want to get technical, the code ...
Some good stuff:
You're using error-specific except clauses.
You're using where blocks.
Items you can improve:
Use a main method. See here for an example; in particular Example 2.
Don't nest function definitions unnecessarily. Instead of calling c, which calls b which calls a, pass their return values to each other:
Give your ...
It seems rather inefficient to generate every date, then filter out non-Fridays, then filter out ones that arent't the first, third, or fifth Friday. Calculate directly them instead.
Find the first Friday in the range:
friday = start + timedelta((FRIDAY - start.weekday())%7)
Move forward a week if it's not the 1st, 3rd, or 5th Friday:
ONE_WEEK = timedelta(...
Which commandment did you violate? Using os.path and pathlib in the same breath! pathlib is an object-oriented replacement to os.path.
path = os.path.join(Path.cwd().resolve(), file)
with open(path) as f:
could be written as:
path = Path.cwd().joinpath(file)
with path.open() as f:
You are organizing your code in functions, which is good; however, you aren't
taking full advantage of their benefits because most of your functions operate
on the basis of global variables rather than function arguments. A simple
data-oriented program like this has no need at all for global variables. In
such a context, every function should take input ...
Here are a few pointers on how your code can be improved:
PEP8 recommends surrounding top-level functions by two blank lines. This improves readability somewhat.
Also, docstrings are supposed to come after the function signature, not before, as specified in PEP257. This is required for the docstring to be handled by Docutils and such software.
It isn't necessary to use regular expressions (the re module), use the str.index() method. For the examples given, re.search takes 3x longer.
def are_substrings_in_text_index(substrings, text):
start = 0
for substring in substrings:
start = text.index(substring, start) + len(substring)
Your function _get_nineoclock_time does two things, it replaces the timezone and it returns the next 9 O'clock time. The function will return different values depending on whether current_time has a timezone or not. That may be unexpected and seems a likely source of bugs. I'd set the timezone somewhere else.
It is easy to calculate how many hours to add ...
There's some odd features to this code, even for a coding practice exercise. Python of course has a couple of list sorting techniques which you should absolutely use in normal circumstances.
So accepting that you are doing this for practice, I wonder what the point of the duplicatelist is? Or indeed temp? Are these development fossils of some earlier process ...
The problem with your current approach is that it can give incorrect results
or raise an exception if any of the substrings contain characters that
have special meaning in Python regular expressions.
are_substrings_in_text(['a', '.', 's'], 'abacus')) # Returns True
are_substrings_in_text(['a', '+', 's'], 'abacus')) # Raises exception
The solution is to ...
I'd like to address how you handle the yes/no question controlling the loop.
The relevant sections of your code are:
again = 'yes'
while again == 'yes':
again = input('Are there any other questions?\n')
Almost all user input are interpreted as "no". However, the user has no information that they are supposed to enter ...
There is a much simpler approach using timedelta to do this.
You start by getting the current hour from now (now.hour). If you subtract this from now it will take you to midnight. Then we add/remove an appropriate number of extra hours to get to the 9am/pm you want - in this example I add 3:
now = datetime.now()
# datetime.datetime(2021, 12, 1, 10,...
What I see bad in your code is readability. It is good if you keep the proper spacing between each component.
If you have a long list, dict or tuple break it into lines.
list_of_predictions = [
"It seems to me - yes",
"It is not clear yet, try again",
"Do not even think",
Yeah, you are recreating tmp every iteration of your loop. This makes your solution O(n^2). You could easily make your solution O(n) by setting tmp before your loop and then updating it along with newlist. The reason your current solution is O(n^2) is that building the tmp set with all the items in newlist would take as long as new list. For example, if ...
if 'general' in input_data.keys():
if 'general' in input_data:
if general := input_data.get('general'):
and then use general instead of repeating input_data['general'].
Alternatively, instead of mostly repeated statements extracting the data, you could configure the ...
Great tips from the other answer, here are just some more bits and bobs.
Use the library capabilities to their fullest
char1 = a
new_list = data
char2 = random.choice(data)
This, in addition to the uncommon indentation sticks out to me. Why are we removing, why are we adding, why are we redefining? ...
I find programs like yours to be excellent vehicles for improving one's coding
skills. Why? Because they have the potential to be incredibly destructive. One
false move and an entire directory tree can be obliterated. In my youth, on
more than one occasion I wrote programs like this only to find myself
frantically pressing CTRL-C moments later. Let's use ...
I'm not going to go too heavily into refactoring the whole thing.
Some basic readability things:
return_values = compare(options, options, score)
score = return_values
lost = return_values
It would be much clearer if you did:
lost, score = compare(options, options, score)
You have indented things with two spaces, which is odd, normally ...
Picking the right tools
Your entire script can be written as the following one-liner
grep -RiIl 'search' | xargs sed -i's/.*\(here\|there\|why\).*//g'
Whenever your entire script can be expressed as a oneliner, it is a good indication that something needs to change. The onliner is intentially obtuse, but I would argue your code is equally obtuse. You just ...
Your code works and is readable, which is nice. It also mostly follows PEP8 style conventions, which is nice, although this can be improved, as it was already mentioned in the other answer.
Of course, there is always room for improvement.
What your code lacks is structure: everything happens at the top level, with no use of functions or ...
Your code and solution worked fine. Although I needed to change the inputData object's method: "name: raw_data," which contained an undefined variable. I then simply passed reference argument string as an input function and it worked perfectly.
name = input('Name of employee: ')
hours = float (input('Now enter the ...
Rather than 4.0 * pow(10, -7), prefer scientific notation literals, i.e. 4e-7
In nearly all cases there's no need for a .0 suffix. Float promotion will do the right thing with an integer value.
Prefer using inner tuples rather than inner lists for array initialization, since they're immutable; like np.array((0, 0, 1)).
Add PEP484 type hints.
Move your global ...
Please fix your code indentation, as it is now it's painful to figure out what's supposed to be happening. The comments provide the corect suggestions to make it easy for you as well.
The characters for living and dead cells should be module-level constants. Makes them easily changeable and the code more readable:
LIVING_CELL = '#'
By making a few observations an O(1) algorithm can be devised. First note that the statement
the sum of the digits in odd places have the same parity of the ones
in even places
is equivalent to the statement that the sum of all the digits equals 0 mod 2. Equivalently, the XOR of the low-order bit of all the digits equals 0. The following function ...
First some code simplifications and other adjustments. (1) Your sum
calculations don't need the conditional tests, because the ranges already
ensure compliance. (2) They also don't need to be wrapped in a . (3)
Even better, if you switch from ranges to slices, you don't need to loop with
in the sum calculations: just give a slice directly to sum(). In ...
Use type hints and unit tests
They are simple and make your code better.
Some improvements and pythonification
odd_sum and even_sum are initialized with zeroes before adding to them, so you can simply initialize them instead of adding:
for k in range(int(x)+1, int(y)+1):
k = str(k)
odd_sum = ...
even_sum = ...
range with step 2 already omits ...
Your previous question dealt with counting the number of levels in a nested
data structure. This question deals with collecting values from a specific
level (sort of). In both cases, your conceptualization of the problem strikes
me as somewhat unintuitive, at least based on my experience with languages like
Perl, Ruby, and Python.
To help clarify things, let'...
Your code seems to work properly on the whole test suite provided which is a very good start.
Also, splitting the logic in 2 parts, one preprocessing the counts and the other performing the comparison is a great way to proceeed.
However, there are still various way to improve the code.
Python has a style guide called PEP 8 which is definitly worth ...
Removing duplicates efficiently
ranked=[i for n, i in enumerate(ranked) if i not in ranked[:n]]
This line creates a copy of ranked at each iteration, which makes it inefficient.
Since ranked is already sorted, create a new list and add elements one by one if different from the previous.
Alternatively, you can use a dictionary that is ordered from Python 3.7....
I suppose you are using this wrapper, which appears to be somewhat minimalistic. To "rewind" the sound file it should suffice to re-instantiate the class like this before starting the loop again:
mp3 = Mpg123(filepath)
for frame in mp3.iter_frames(out.start):
See if that makes any difference. There may be a better way, like ...
Your uni.py is your "main file"; fine. As such, it should have a #!/usr/bin/env python3 shebang. The nicer option is to make a proper module directory tree containing a __main__.py such that running python -m uni runs your module's main entry point.
It's a good idea to ship a default config.yaml file inside of your module; this will mean that all ...
There are two promising alternatives to ordering nums and finding the index of the smallest element therein larger than each element of maxes:
order maxes (ascendingly) and
tally elements num in nums (ordered[m-1] <)
num <= ordered[m] and accumulate (finally reordering output) -
order both and take turns finding, for an element in one ...