22

You should have a look at Loop like a native!. Explicitly iterating over the indices is usually not the best way to do something in Python. By directly iterating over the string representation of n you won't even need the second argument (and you should remove it if the assignment/defined interface would not require it). This will help you a lot later, when ...


13

As mentioned in another answer, iterating with indices in Python in most cases is a bad idea. Python has many methods and modules to avoid it. For your problem Python has powerful decimal module to work with decimal numbers. Here is how it can solve your problem: from decimal import * def count_even(number, length): return sum( d % 2 == 0 ...


11

Some suggestions: The trailing slash in the mkdir command is redundant. $(…) is preferred over backticks for command substitution. Why use seq in one command? They both do the same loop, so you might as well use {1..100} in both places. Semicolons are unnecessary in the vast majority of cases. Simply use a newline to achieve the same separation between ...


11

functools.singledispatch functools library includes the singledispatch() decorator. It lets you provide a generic function, but provide special cases based on the type of the first argument. import functools import random @functools.singledispatch def shuffle(arg, order): """this is the generic shuffle function""" lst = list(arg) return type(...


11

This is a fun problem. I've taken the liberty of writing an alternate implementation, which I will describe below. Note that I've not focused too much on performance at all, only on simplicity and good structure. Suggested from typing import Iterable N = 11 class MBI: letters = tuple('ACDEFGHJKMNPQRTUVWXYZ') numbers = tuple(str(i) for i in range(...


10

Since you are dealing with digits, you at some point must pick a base (in this case base 10). So converting the number to a string is not a bad way of getting the digits. I would keep it simple, and just check each digit and see if it is one of the digits you want. # Incorporating the other suggestions to loop over the chars directly rather than using an ...


10

In my opinion, this code is all right. As any explicit code, these loops are quite straightforward to follow. And making it more concise will likely make it more cryptic as well. I would only make a minor brush-up, removing the unnecessary default clause and make the proper indentation. Variable interpolation is also more natural to read, in my opinion. ...


9

I agree with what "Your Common Sense" said, but I would like to have better variable names. Names that make clear what a variable contains. Seen in isolation variable names like $e, $array and $v don't really convey what they contain. Abbreviated variable names don't make your code easier to read. Also $errors does contain errors, but more precisely it ...


7

I think your solution 2 is heading the right direction here. What I consider it's advantages over solution 1: It is much more readable It clearly shows that every member of *args is treated the same. You might want to generic-ify it a bit more to handle more types. For example, the following has a good chance of also handling custom container types: ...


7

While I do agree with others that Solution 2 is more readable with some improvements, there are also a few improvements that can be done on Solution 1. It is unnecessary to construct lists from iterables (e.g., generator expressions) when all that is needed is an iterable. For example, _args = [arg if type(arg)!=dict else arg.items() for arg in args] ...


6

First off, this is buggy. If one of the input arrays is empty, you'll get an ArrayIndexOutOfBoundsException - and even if you correct that error, the iterator will stop if it encounters an empty array. Consider using proper tests with multiple scenarios, especially with edge cases, in order to catch errors like that. Then I get two warnings from Eclipse (...


6

There are a few quick improvements you can make. First, always remove as many things as possible from for loops. In this case, the date formatting and the open file lines can be removed. Dates. Format the dates in your dataframe before the first for loop with something like df['Date'] = pd.to_datetime(df['Date']).dt.date Notice I’m converting the datetime ...


6

My main concern is the use of cw as a "persistent pointer". Specifically, might people be confused when they see for code in cw? No. Instead, you can just remove the line cw = iter(code_words) as long as it's a native iterable. "Persistent Pointer" isn't a thing in python, because all python knows are Names. What should be the typical best practices in ...


6

Explicit is better than implicit. Simple is better than complex. Readability counts. The easiest way to make it faster would be to simply convert it into code: def generate_mbis() -> Iterator[str]: """ Generate MBIs, starting with 1A00A00AA00. An MBI is a string with the following rules: [1-9] # No ...


6

As @AustinHastings pointed out, the itertools.product solution below doesn't work right unless you start at the beginning. So here's an alternate solution: DIGIT = '0123456789' LETTER = 'ACDEFGHJKMNPQRTUVWXYZ' DIGLET = DIGIT + LETTER def mbi_gen(start=None): pattern = [DIGIT[1:], # leading non-zero digit LETTER, ...


6

Before I get started with the script polishing, I just want to voice that I don't think it makes sense to bloat/hydrate your otherwise lean data storage with redundant text. If you are planning on presenting this to the end user as a means to communicate on a "human-friendly" level, then abandon the array-like structure and write plain English sentences. ...


5

You have access to the stack array directly so you can copy the unsorted stack it to a new stack and sort it in place using Array.sort "use strict"; function sortStack(stack) { const sorted = new Stack(); while (!stack.isEmpty()) { sorted.push(stack.pop()) } sorted.storage.sort((a, b) => a - b); return sorted; } or "use strict"; ...


5

Is a best practice to define a variable as type of the interface the instance implement it(see OOP principles) Just a little bit out of scope, you can declare your arrayList inline, like in the example I wrote. Try to use available features of List(in this example) like subList rather than cycle(what if you have thousands of elements?) toString on a list ...


4

Minor, but I'd expand your foreach a bit to make it clearer that func is a side-effect function that happens to return an indicator. In its current form, it looks like the function is only being run for the purpose of the condition. Something closer to: def foreach(self, func): for key, value in self.json.items(): should_continue = func(key, ...


4

A few notes: Firstly, I would add some docstrings to each function to document what the expected behaviour is. In select when you're not doing any mutations (i.e. under the * case), it seems you could just return self. Is there any reason to make a new copy? In select, where, astype instead of creating a temporary dict, you could use a dict comprehension ...


4

Using GNU Parallel you code will look something like this: #!/usr/bin/env bash export script="path_to_python_script" doit() { i="$1" j="$2" $script -args_1 "$i" $script -args_1 "$i" -args_2 value -args_3 value } export -f doit parallel --resume --results data/file_{1}-{2}.txt doit ::: {1..100} ::: {1..100} In your original code if one ...


4

You seem to have some extra code in your function that is not needed. The code below does the same thing as your function: const sortStack = (stack) => { sorted = new Stack(); while (!stack.isEmpty()) { tmp = stack.pop(); while (tmp < sorted.peek()) { stack.push(sorted.pop()); } sorted.push(tmp); } return sorted; } The ...


4

I think RangeCollection would be a better name than Ranges. To my mind, the RangeIterator is doing too much. It's iterating over a collection of ranges and over each range in the collection. To me it would make more sense for the Range class to have its own iterator and the RangeCollection its own iterator


4

The point of this answer is to illustrate that the most efficient way to do things in other languages can be different from Python, and in this case is. IDK if this different low-level perspective on the problem is a good code-review answer, but putting it here in case people find it interesting. In an efficient compiled language, all that casting to ...


4

I agree with Mike Brant's comments that it would be better to have the complete code posted for a broad review but that likely won't happen- if you do want to do so then I advise you to do so in a new post, since editing your post might invalidate the advice below. Nonetheless i see a few idiomatic PHP aspects that could be improved. The code could be ...


4

Review Function hasAceInHand could be boiled down to a one-liner using array.find. It returns the first element of the array that passes the condition x => x.face === "A" provided. const hasAceInHand = (cardsOnHand) => { return cardsOnHand.find(x => x.face === "A") != null; } Function countHandValue iterates the items, and calls the other ...


3

I'd suggest using for...of loops to iterate over the cards, but before we can do that, there is an important point with the dealOneCardToPlayer() function: tempCard = deck.cards.splice(0, 1); Note that Array.splice() returns "An array containing the deleted elements."1 and thus the name tempCard is misleading - perhaps a more appropriate name would be ...


3

In the worst case (the repeated element occupies the second half of the array), the set will accommodate all N non-repeated elements, therefore the space complexity of the solution is \$O(N)\$. Your intuition is correct; the solution doesn't use the important information. It is used to find out how far apart the repeated elements are. If a distance between ...


3

I'm going to take @greybeard's internet points, since he apparently doesn't want them enough to type this ;-). You need to keep in mind that \$O(x)\$ really means \$O(C \times x + ...)\$ for some value C. As long as you keep C a constant, you can do whatever you want. Thus, \$O(n)\$ can really mean \$O(2000 \times n)\$, and \$O(1)\$ can really mean \$O(10^...


3

You could use the python lambda function count_even_digits= lambda x,y:len([i for i in str(x) if int(i)%2==0]) count_even_digits(n,n_digits) This creates a lambda(inline) function that takes two inputs x and y and performs a list comprehension that extracts digits from the input number(x) if they are even and then returns the length of this list which is ...


Only top voted, non community-wiki answers of a minimum length are eligible