14

Unnecessary Import numpy is not required for this challenge. You are using none of its special capabilities. The following: arry = np.array([[0]*5 for i in range(5)]) could easily and simply be replaced with arry = [[0] * 5 for _ in range(5)] Notice the throw-away _ variable being used for the unused loop comprehension variable. If you don't use it, ...


11

After getting user input, you check it by doing decision == "Yes". This is pretty exact text to expect from the user. I'd at least upper-case their input, and unless you really needed them to be specific, only keep the first letter: decision = input("You guessed wrong, do you want to continue? Yes or No ") std_decision = decision[:1].upper() # [:1] ...


9

Nice use of """docstrings""". This code is useless: else: "Value out of bounds" If the else clause is reached, the string statement is executed, with no effect. Just like executing a docstring statement has no effect. You want: else: raise ValueError("Value of out bounds") The function convert_to_word() returns strange values like "...


8

These are all relatively minor notes: You can use typing.List to provide a better type definition for the parameter (List[str]), precisely defining what it's a list of. I always try to avoid giving variables names that are just a variation on the Python type to tell me what its type is (that's the type annotation's job); the problem description calls this ...


6

I suggest that you extract the similar evaluations in methods. private static long countFirst(int k, long countOther, int i) { return countOther * (k - i) % MOD; } private static long countNext(int k, long countOne, long countOther) { return (countOne % MOD + countFirst(k, countOther, 2)) % MOD; } //[...] long countOne = ...


6

"Impossible" check Per task description, k >= 2 and n >= 3. But nevertheless you're performing this "impossible" check: if (n < 3 || k < 2) return 0; Redundant check I don't understand why you're checking cases n == 3 separately. You could remove these 2 checks and have this case handled in your for loop quite easily as below (please note ...


6

We can use doctest instead of the asserts: import doctest def find_vowel_square(strs: list): """Return the top left grid ref of any 2x2 sq composed of vowels only. >>> find_vowel_square(strs=["aqree", "ukaei", "ffooo"]) '3-0' >>> find_vowel_square(["aqrst", "ukaei", "ffooo"]) '2-1' >>> find_vowel_square(...


6

Toby & Sam both make excellent points; I won't repeat them. I would like the add the following: Use sets with in You are repeatedly testing whether a letter is in the string VOWELS. This requires a linear search through the string, checking each substring to see if it matches. If instead, you declared VOWELS as a set: VOWELS = set("aeiouAEIOU") ...


5

calcpath should be calc_path as per PEP8. This seems like it's a name decided on by the challenge, but I thought I'd mention it. _map = {"d": 1, "u": -1, "l": -1, "r": 1} This should have a better name. "map" indicates that it's a mapping between things, but doesn't give any more information than that. I'd change it to something like: ...


5

Let's see what is the Big O of your code. In new versions of Java substring creates a new String and performs in \$O(n)\$ (In older versions this is \$O(1)\$) uniqueRepeats.contains(character) results in \$O(m)\$ where \$m\$ is count of unique characters. restOfString.indexOf(character) != -1 - this is again \$O(n)\$ uniqueRepeats += character Depending on ...


5

For reference, what I think is the most straightforward solution, that is not fast enough since it does all combinations of three. from itertools import combinations class Solution: def threeSum(self, nums: List[int]) -> List[List[int]]: return set(tuple(c) for c in combinations(sorted(nums), 3) if sum(c) == 0) And a longer, but valid ...


4

Please don't have white space at the end of lines. There is never a need for anything other than a new line at the end of a line. You don't need to use enumerate(nums) to build vals - i is never used. You can use collections.defaultdict(int) to remove the need for the if in the for when you make vals. You can use collections.Counter to create vals. You can ...


4

There's a few general code hygiene things that I'll look at first, and then I'll comment on the algorithm design. First, const should mean constant. I know that in Javascript you don't get in trouble for changing the contents of a const array but it's still confusing to use it with a variable whose job is to change. const arr I like but const resultArray I ...


4

I'd greatly appreciate all sorts of tips for improving not only the solution itself but also the style to be more Go-ish. For a real-world code review, code should be correct, maintainable, reasonably efficient, and, most importantly, readable. Writing code is a process of stepwise refinement. Go was designed for simplicity, readability, and performance....


4

It was a tough one but I managed to solve it and pass all the test cases. Below are main points. Build a full directed graph first Save the queries because there can be up to 100,000 of them and it's more efficient to build a full graph first and then run all the queries on it. Find all strongly connected components Find all strongly connected components ...


4

Can I do it in a better way? From the time complexity or space complexity your solution is good enough. Your store all your string frequencies beforehand so that to retrieve a frequency by any given string in O(1) time later. Also, it passes all the test cases so it's a good sign too. Below are a couple of concerns regarding other aspects of your code. ...


4

Like bhathiya-perera and yourself suggested this can be better implemented using a HashMap and simply count the characters. However in my opinion your attempt isn't that bad. The problem is you are using the wrong methods and data structures and you are coping/creating strings too much. First you don't need to create charArray which is an unnecessary copy ...


4

I have no C/C++ compiler at the moment, but the algorithm only needs one loop, the while+flag being a tiny bit too unreadable. There are two counters: Finding the maximum length: maxLength Sequences with next value >= prior value. Counting the maximum length: maxCount. length > maxLength reset maxCount to 1 length == maxLength increment maxCount So (in ...


4

The code Before switching to a better algorithm, let's polish the code first. Almost every line of your code can be improved. Get rid of #define ll long long int. This is a standard way to lower the quality of your code. If you mean long long, use long long. Qualify names from the std namespace with std::. Make the parameter temp a const reference (const ...


3

On Windows, you'd rather use the console API directly instead of stdio.h. This should increase performance somewhat, since these functions are what getchar etc will end up calling anyhow. Other issues: All functions should be declared to take void as parameters, rather than to accept any parameter. If they are properly inlined this should hopefully not ...


3

I have some suggestions for your code. 1) Since we know the size of the output, I suggest that you initialize the java.util.HashMap with the size + 1, since the default capacity of a Map is 16; this will prevent the map to do a rehashing if you have more than 16 values. If you want more information about the rehashing / load factor, you can read the java....


3

You are checking conditions multiple times, increasing the complexity of the code. For example: if (n == 3 && x == 1) { return k - 1; } if (n == 3) { return k - 2; } checks n == 3 twice. A nested if statement would be simpler & clearer: if (n == 3) { if (x == 1) { return k - 1; }...


3

Needless for loop usage for loops in Python are heavy. Using for loops needlessly leads to performance loss. For instance, rather than doing this: for j in range(m): if mat[i[0]-1][j]=="0" and mat[i[1]-1][j]=="0": You could just count the number of ones using int(), bin() and | as below: orResult = int(mat[i[0] - 1], 2) | int(mat[j[0] - 1], 2) ...


3

Clarify your code's structure As pacmaninbw already mentioned, adding blank lines and moving bits into their own functions would help make the structure of your code more clear. Avoid using std::endl Just use '\n'; std::endl is equivalent to '\n' plus a flush of the output, which is usually not needed and will only decrease the performance of your program....


3

Nice code overall, doesnt feel like beginner. A few points: case for single argument in your normalizeArgs switch can be covered by default branch I don't like your main game loop conditions. Basically first half compares number of remaining tries, that effectively means asking if game is lost. Second half asks if game is won. Then can change to checking ...


3

You can get an immediate speed-up by ditching the defaultdict(int), and using a bytearray(blockCount+1) instead. Both have roughly \$O(1)\$ lookup time, but the latter has a much smaller constant factor. In the former, each key must be hashed, then binned, then a linear search through the bin is required to find the correct key entry, if it exists, and ...


3

Don't use #define ll long long int and don't use long long int either. Use auto for values and size_t for indices and cardinalities. Your method should take iterators as parameters. It will still work with vectors, but also with linked lists and other containers. Have a well defined behaviour for corner cases, such as empty lists. This behaviour should be ...


2

User input shouldn't require the full case-sensitive text. If there isn't already one in a library somewhere, write a function that compares two strings to see if one is a valid truncation of the other. Then use that function rather than != for comparing the response to the flip. E.g. any of these should match "True": "t", "tr", "tru", and "true", ...


2

Towards optimization and restructuring One of downsides of the initial revrot approach is that all nested functions test, reverse and rotate will be redundantly recreated on each revrot call.Instead - define them as top-level functions with meaningful names. Next, the program lacks 2 edge cases: when input string contains one single digit and size of ...


2

I really liked @JollyJoker's answer but it was not written in Pythonic enough format for my taste. I added some changes that take his core logic and improve upon it: from itertools import combinations class Solution: def threeSum(self, nums: List[int]) -> List[List[int]]: positive = sorted(n for n in nums if n > 0) posSet = set(...


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