# Tag Info

4

Your first code snippet has the problem that (in Python 3) input always returns a string, so type(user_in) will always be str, which will never compare equal to int. Your second code snippet solves the problem in the correct way: try to convert the result to an integer, and catch the exception in case that fails. Fixing that code is as simple as adding a ...

1

There are a lot of ways to accomplish this, one of them is to use recursion. Where in you write a "function" which executes your code & when you hit a certain condition, the function calls itself - def myf(): user_in = input('Input an integer value \n') if type(user_in) == int: a = user_in # continue with whatever you need to do ...

1

I suggest some correction and simplification of your update method. Result: def update(self, rate=1, **kwargs): self_dict = asdict(self) self_dict.update(kwargs) for k, v in self_dict.items(): if k != 'sale': v = self.round(v * rate) setattr(self, k, float(v)) Explanation: The rate = kwargs.get('rate', 1) can be replaced to the rate=...

0

Call your sort method natural_sort -- or even better natsorted to comply with Python's sorted. The reason is that among programmers it is widely known under that name, so I recommend sticking with it. Jeff Atwood writes at the linked article: It isn't called "Alphabetical sort"; it's collectively known as natural sort. Furthermore, rather use existing ...

4

The line v = kwargs.get(k) or v means you cannot use the update method to set any of the properties to 0. get can take an additional argument for the default value to return. If you change that line to v = kwargs.get(k, v), then price.update(sale=0) works as expected.

4

Welcome to CodeReview! I'll start by saying thank you for posting a somewhat-complex package of code. At first blush, your code appears to be written in the generally-accepted style and appears well organized and somewhat documented. Functionality Before I actually review the code, I'll point out that I tried to play the game. Here's my experience: Your ...

13

In short: dataclass is the right thing to use as a mutable named tuple. It's basically custom-built to be a great version of that idea. Use decimal.Decimal for any financial numbers. Don't re-implement round. There's a built-in version that behaves in nice, configurable ways with the Decimal object. Not sure what the p.update(**{sale=600}, **dict(rate=0....

3

Style All the other answers are quite good and you should definitely follow their recommendations. They do however gloss over a stylistic point I find particularly striking about your code: blank lines. The way you use them makes them almost obsolete. There would not be a major difference in the readability of your code if you left them out, since there ...

1

Overall your implementation is fine, I would just suggest a few things: Naming - move_rings and helper are not very descriptive. Give them better names, and give them good docstrings (I like NumpyDoc, but personal preference is fine) move_rings shouldn't both do calculations and print to stdout. Instead, move_rings should return the information, and the ...

4

I'd suggest a couple minor stylistic tweaks: Keyword arguments don't typically have spaces around the =, so we'd have sorted(l, key=alphanum_key) instead of sorted(l, key = alphanum_key) You have a couple fairly long lines that could be broken up or reduce a little Don't create a variable in one line if you're just going to return it in the next: just ...

5

Docstrings You should include a docstring at the beginning of every function, class, and module you write. This will allow documentation to identify what your code is supposed to do. This also helps other readers understand how your code works. I see that you already have a couple for your functions, but stay consistent. Parameter Names Parameter names ...

6

First, I like how you have everything spaced out instead of crammed together. I definitely prefer over-spacing to under-spacing. I think though, in a few places it's a little much. For example: if usr_inp[0] not in dict_pos.keys(): return False x = dict_pos[usr_inp[0]] y = int(usr_inp[1]) return x, y - 1 At some point, the spacing begins hurting ...

4

Use functions It's generally a good idea to sort your functionality into functions. Allows you for nice reuse and stuff like that. string.split() So how will we parse? Of course, you can parse every single input like you do, or even upgrade it to a tokenizer engine if you got a lot of spare time and effort. There's really 2 ways to go about there here. ...

4

Not looking bad for as far as I can see. If the example file is accurate for the lengths of the input files, then I don't forsee any real problems, though others may of course disagree. Naming: cmdline is quite a... short name for a function. I'd think cmd_line for snake_case convention. However, what it does is create what's basically a text file in a ...

3

As you mention, some of this is messy and haphazard, which is a side-effect of writing one-off scripts that have a single behavior they need to perform, instead of something extensible. In that case, this review is going to largely focus on how we make this extensible and use our hammer to build a screwdriver (among other things). If we start at how we ...

2

Naming: According to PEP8, you should make all these names snake_case. This is good, but the important bits here are: Do the same thing consistently Have a clear word seperator. Basically, this means you can use snake_case, camelCase, or even TitleCase, but the last one is generally used only for classes. I'm personally partial to camelCase for functions/...

3

Naming I have two problems with your naming: First, you don't use underscores to separate words. Instead of uniquepattern, use unique_pattern. Second, your names don't actually tell me anything! Functions, particularly non-method functions, should include a verb unless the verb is implicitly get or is. And implicit is needs to be used with some caution. ...

2

A few more points: The precision of the decimal context is set at the top-level of the code, while the result of computation is rounded within the two methods. That is not good because in this case the methods actually have no knowledge about how the precision is adjusted based on user input. These two operations should be handled on the same level: either ...

2

Welcome to Python! "Project Euler exists to encourage, challenge, and develop the skills and enjoyment of anyone with an interest in the fascinating world of mathematics." Like you, I went to Project Euler when I was learning Python as yet another language for my toolbox. Unfortunately, Project Euler is primarily a mathematics challenge site, not a ...

13

Convergence testing if pi == piold: break This is not usually done, because float equality has a lot of gotchas. In this case it's possible due to the numbers being Decimal, but if you need to move away from Decimal you're going to encounter issues. Usually, convergence is measured as the absolute error decreasing below a chosen epsilon, a ...

2

I don't quite know what lambda calculus is (I'm assuming it's a mathematical annotation for what we might call "purely functional programming"?), but I'll give this a quick shot. First, I'd love to have env populate itself if not provided. You really shouldn't have mutable default values for functions, though; the typical practice is to define: interp(self,...

6

Disclaimer: I haven't done authentication in Flask before. Tl;dr: Don't do authentication yourself, it's VERY hard to do right (and using a global ain't right); also, separate the user's authentication from their key store: the former you should ONLY be able to verify, not decode, and the latter should be inaccessible to your server without some secret ...

1

Without even doing anything clever regarding the algorithm, this: new_count = count + sum(stones[start:start + k]) merged_count = sum(stones[start:start + k]) can be cleaned up as merged_count = sum(stones[start:start + k]) new_count = merged_count + count

1

Type hints PEP484 type hints, such as ndim: int, will help better-define your interface. Mutability Reading your code, the other members of CandidateArchive only make sense if fidelities are immutable. As such, don't make them a list - make them a tuple. One advantage is that you can safely give a default argument of ('fitness',), whereas you can't safely ...

2

A lot of the code in your while loop can be replaced with a for loop using enumerate() and a toggled boolean. You should be able to replace your code from c = len(lines) (line 21) down through your entire while loop with: skip = False for index, line in enumerate(lines): if line.startswith("`"): skip = not skip else: if not skip: ...

2

Welcome to CodeReview! This isn't great code, but that doesn't mean that this is a bad question. I think that you've come to the right place. Recursion if color == "": print("No skipping!") print(check(input("Enter Name Here>>> "))) This uses recursion when it shouldn't. In other words, check is calling itself needlessly, and ...

1

Coding Style First, I'm not a code reviewer. Your code seems to be OK though. There are some basic coding conventions in writing Python scripts, such as variable naming, commenting, docstring, and such, which I don't go through it, since I'm learning myself, and you can find it here. Implementation There are a few things that hold a basic ANN not to ...

1

The single largest optimization I was able to make was to the logarithms. Once the two terms of a AGM are the same, they will not differ again. Therefore you can be sure you have converged. The argument of oscillating convergence does not apply. I also noticed that, code aside, y=2^x+8; AGM(1, y) converges the fastest out of the numbers. I don't know the ...

13

This is a tip I make a lot, but if you have a collection that's simply tracking "membership", and you don't care about order, you should consider using a Set over a List. I think this is the case for cell.linked_cells. The only thing you ever do with cell.linked_cells is do in membership tests, and add and remove from it. Make the following changes: ...

4

The problem can be solved using math formulas, which will lead to an O(1) solution. But here I show another way to implement it, which is more efficient than a naive loop: def sum_multiples(n): return sum(range(0, n, 3)) + sum(range(0, n, 5)) - sum(range(0, n, 3*5)) Or alternatively, def sum_multiples(n): numbers = range(n) return sum(numbers[:...

5

The keyword sum is a built in function and you shouldn't name variables from within the reserved keywords. Here's a list of the most common used keywords which you shouldn't be naming any of your variables: [False, class, finally, is, return, None, continue, for, lambda, try, True, def, from, nonlocal, while, and, del, global, not, with, as, elif, if or,...

6

Error handling One specific question I have is if it's bad practice to return a print call, as a way to print an error and simultaneously return from the function? I did that so that I could print the error and return None on the same line. That is unconventional to say the least. By catching the exception internally and print it to the console you ...

10

Python already has an exception that denotes that the value you passed is inappropriate somehow. It is ValueError, which is what the built-in int also raises if a wrong string is passed. In addition, defining a nice readable error which you can raise, only to catch it directly within the function and to return None (the output of print) and print to the ...

1

def change_letter(original, new_message, key_number, alpha): docstrings: Python documentation strings (or docstrings) provide a convenient way of associating documentation with Python modules, functions, classes, and methods.It’s specified in source code that is used, like a comment, to document a specific segment of code. You should include a docstring ...

1

Laziness is a programmer virtue. These folks are spending more time on theory than doing it the lazy way would take in practice. The big problem here is you're doing a bunch of unnecessary work, particularly around storage. You're constantly appending to arrays for no apparent reason. You don't need the history of old numbers. Throw them away. ...

0

As 200_success says, you can look at how the numbers are derived to generate the numbers one by one. So rather than creating all the numbers and checking for an intersection, a simple algorithm is to look at a pentagon and hexagon number. If they are equal, you're done. If the pentagon number is larger than the hexagon number, then check whether the next ...

1

Python is a great choice of language for a challenge like this, mainly because of how easy it is to use sets. Basically, any challenge which states "find a number that matches these criteria" can be thought of as a set intersection problem. We want to find $T \cap P \cap H$, the intersection of triangular, pentagonal, and hexagonal numbers. Depending on ...

0

You can easily check that H(n) = T(2n - 1). So all hexagonal numbers are triangular numbers, meaning we can ignore the triangular numbers altogether. To compute pentagonal numbers: Start with p = 1, dp = 4. To get the next pentagonal number, let p = p + dp, dp = dp + 3. To compute hexagonal numbers: Start with h = 1, dh = 5. To get the next hexagonal ...

6

Computation of logsum and logsum1 in gamma() are suboptimal. You do costly operations of raising to power, and recompute factorial on each iteration (the latter invokes the quadratic time complexity BTW). Notice that in the $\sum \dfrac{(-1)^{r-1} k^{r+1}}{(r+1)(r-1)!}$ a consecutive term can be expressed via the previous one, as\\$T_{r+1} = -k\dfrac{r+1}{(...

3

Type hints Presumably all of the argument to calculate_distance, as well as the return value, are float. You should indicate so with PEP484 type hints. List literal unpacking row = [" "] * 40 row[0] = "#" row[-1] = "#" can be row = ['#', *[' ']*38, '#'] Magic numbers Assign 40 to something like GRID_SIZE. Rather than 38, write GRID_SIZE - ...

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

41

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

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

6

The main reason why your code is so slow is because your for loop in main spends most of the time checking for things that are logically impossible to be true. You have one million elements in every number group, every iteration of the for loop you are comparing one value to 2 million other values, when most of them can not be true. for _, terms in ...

0

Why have main() be a single line calling a single function? Either rename main() to get_xkcd() or just call get_xkcd(). Also, maybe use BeautifulSoup instead of lxml.

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

8

I want to include it as a practice of getting used to writing solutions that require classes. No solution "requires" classes, although some situations are better represented with classes than with other techniques. In this particular case, Shape doesn't really need to exist - as you've already identified. Since each of those methods only depends on term, ...

2

Docstrings You should include a docstring at the beginning of every function, class, and module you write. This will allow documentation to determine what your code is supposed to do.7 Variable Naming Here is a list of variables/parameters that I would change. This increases readability, and makes the variables easier to understand. input_str -> ...

3

Constant reuse Store your base URL, "https://www.example.com", in a constant for reuse. HTTP codes Some status codes, such as 200, are common and obvious, while others such as 429 are less so. Fundamentally these are all magic numbers, and requests.codes contains symbols - including too_many_requests. URL construction allposts = [f'https://...

8

Not a problem in terms of functionality (seems to have been covered pretty well already) but in terms of clarity/readability: Misleading name get_penultimate It appears to functionally be get_last (get_ultimate, if you will), so there is a clear mismatch between this name and the implemented functionality. The functionality makes sense, so the name appears ...

Top 50 recent answers are included