# Tag Info

42

Arithmetic Project Euler questions are meant to educate you about both mathematics and programming. It would be a good idea to understand what these triangular, pentagonal, and hexagonal numbers actually are, rather than blindly applying the given formulas. One performance improvement would be to find a way to generate successive elements of each sequence ...

18

I would do something like: def sum_of_squares(n): return sum(i ** 2 for i in range(1, n+1)) def square_of_sum(n): return sum(range(1, n+1)) ** 2 def sum_square_difference(n): return sum_of_squares(n) - square_of_sum(n) Notice the use of a generator expression in sum, where I have omitted the square brackets.

18

First, at the top you list all the consonants out. There are two things that can be improved here: Since you only use it to check whether or not something is a consonant, it should be a set. It's much more efficient to to a membership lookup on a set than it is to do one on a list. Just replace the [] with {}. consonants = {'b', 'c', 'd', 'f', 'g', 'h', 'j'...

18

I am going to provide a much more over-the-top strategies to deal with Sudoku rather than outright code snippets so you can try it out on your own. [Also I am avoiding code-refactor, so that you can focus on Algorithm first, and then we will talk about Code Design, and finally implementation] However, if you need more explicit help or I am not clear enough, ...

17

I find myself struggling more to understand and read what is going on This is the key insight. A chunk of code is likely to be read more times than it was written. So write your code to be read. Use comments, docstrings, whitespace, type hints, etc. to make it easier for someone unfamiliar with the code (including your future self) to read and understand ...

16

Overall, I like this. To really nitpick, I don't really like the use of rules[::2]. [::2] conveys that we are picking out every even element of rules as if that was significant. But in this case, it is more like it just happens to be that the first and last rules are what we want to pick out and that happened to match up with choosing all even elements. I ...

14

Your solution is far too complicated. It's also inefficient, because it uses functions .lastIndexOf() and .includes(), both of which analyze the entire str looking for target, whereas an optimal solution should look only starting at a known position at the end of str. Here are two simple solutions: function confirmEnding(str, target) { return str....

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, ...

13

Code limit = 1000000 triangle = [] pentagonal = [] hexagonal = [] triangle_number = [] Global variables do not help readability. What's the difference between triangle and triangle_number? Those names don't help me understand what they represent. class Shape: def __init__(self, term): self.term = term def triangle(self): return ...

13

EDIT: Thanks to @benrg pointing out a bug of the previous algorithm. I have revised the algorithm and moved it to the second part since the explanation is long. While the other answer focuses more on coding style, this answer will focus more on performance. Implementation Improvements I will show some ways to improve the performance of the code in the ...

13

Your code can be simplified using a simple loop, eliminating most of the duplicated code: def game_of_cups(zipcode, rules): total_points = 0 for num, rule in enumerate(rules, 1): rule_passes = rule(zipcode) points = num + 4 if rule_passes else 0 total_points += points print(f"Rule {num} got {points} points, so total ...

13

Overall, it looks good to me. Just a couple observations. They aren't necessarily better or more pythonic, but you may see them in peoples code. Use whichever you find more readable: The first rule turns the digits to ints to compare them, but the ascii for the digits compares the same as the integer digits ('0' < '1' ... < '9'). So the int() isn'...

12

Something I ran into while making my own implementation: After 34 rows, the highest number in the row will be two 1166803110s. Adding these for row 35 exceeds the maximum value for ints, resulting in integer-overflow. You might consider putting the line that does the addition into a checked block, so that an OverflowException is properly thrown: for (int ...

12

As this is a simple text transformation, the regular-expression module re is your friend. Processing letters one at a time is h-a-r-d. It would be simpler to process things one word at a time, as suggested by @Carcigenicate. The re.sub(pattern, repl, text, ...) function is interesting in that it allows you to specify a string or a function for the ...

11

Readability The code needs more spacing. Considering the comments, the indentation and the ifs, it's hard to read without some good old empty lines. Use brackets when using conditions, especially if you have comments above your single line, it gets really confusing. Also, the readability is increased and, the biggest factor, you'll avoid weird bugs. If ...

11

The initial approach is full of redundant if conditions for capturing float numbers and duplicated set of statements (stack.append, for loop, del ...) for all 4 arithmetic operations. The whole idea is achievable with a single traversal facilitated by operator (provides convenient equivalents of mathematical operations) and ast.literal_eval feature (to ...

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] ...

11

Generally speaking your code looks quite good from my point of view. It's nicely structured, readable and documented. Well done! Using LOWERCASE = ascii_lowercase + ascii_lowercase in conjunction with n = n % ALPHABET_LENGTH also seems to be a very clever way to implement the shift. You don't need if n < 0: n = ALPHABET_LENGTH - n because modulo ...

10

An alternative not discussed in the other answers: use numpy. As soon as you want to do anything serious with numbers, it's going to be useful. The downside is that numpy uses fixed-size integers, which can lead to overflow. It also allocates the array, which uses more memory than necessary. import numpy as np def sum_square_difference(n): nums = np....

10

Indeed, the values dictionary looks unnecessary. Using a built-in function ord you could compute the letter score with ord(letter) - ord('a') + 1. One may argue that it is even faster than a dictionary lookup, but in this case the timing difference is rather marginal. With Python you should avoid rolling explicit loops. For example, collecting the word ...

10

On the logic, you should notice that the next state of the i'th house becomes state[i - 1] ^ state[i + 1] (some care at the boundaries to be exercised). Upon the closer inspection you may also notice that if you represent the state of the entire block as an integer composed of bits from each house, then state = (state << 1) ^ (state >> 1) is ...

10

I would warn you from using such an approach - it may lead to buggy and unexpected results.Consider the following situation: names = ['john', 'john', 'tom', 'john'] res1 = username_system(names) print(res1) # ['john', 'john1', 'tom', 'john2'] lst = ['a'] res2 = username_system(names, users=lst) print(res2) # ['a', 'john3', 'john4', 'tom1', 'john5'] ...

10

Magic number ALPHABET_LENGTH = 26 You don't need to hard-code ALPHABET_LENGTH = 26 in your program. Let Python do the work for you, with ALPHABET_LENGTH = len(ascii_lowercase) Avoid String concatenation; use built-in functions String concatenation is very slow. new_str = new_str + encoded_char AlexV's append / join isn't much better. Python comes ...

9

I wouldn't bother with the numRows == 1 special case (it is redundant and just adds code), but you should be checking that numRows >= 0 and throwing an argument exception if it is not (and ideally testing for that as well); currently it treats numRows < 0 as numRows == 1 which makes no sense at all. As always, this would benefit from inline ...

9

Your function f should probably be a proper function, like all the others. There is no reason for it to be a lambda. def fuel(mass): return mass // 3 - 2 Instead of using recursion, you could use iteration in partial_sum: def total_fuel(mass): total_mass = 0 while True: mass = fuel(mass) if mass <= 0: break ...

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 "...

9

This is not a review, but an extended comment. Project Euler problems are about math, not programming. To optimize, you need to do the math homework first: The $n$'th triangular number is $\dfrac{n (n+1)}{2}$. A number of divisors, aka $\sigma_0$, is a multiplicative function. The link to divisor function may also be interesting. $n$ and $n+1$ ...

9

return evensum == oddsum && evensum != 0 && oddsum != 0; Why can't sums be zero? With this array ... {-5, 7, 0, 5 } ... if you remove the 7, then the even elements -5 and 5 would sum to zero, and the odd elements 0 also sum to zero, giving a "balanced" array. Move tests out of loops wherever possible. for (int i = 0; i < arr.length;...

9

Use built-ins alpha = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] This is a very verbose and error-prone way of getting all of the ASCII lowercase letters. from string import ascii_lowercase as alpha will give approximately the same result. It is a string, instead of a ...

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