patternpythonModerate
Generating the sequence of the digits that appear in the sequence of natural numbers
Viewed 0 times
thedigitsnumberssequencegeneratingthatnaturalappear
Problem
This is a revisit to a question already asked here about a year and a half ago.
Project Euler's Problem 40 involves generating the sequence of digits that appear in the natural numbers, all concatenated together (
After finishing the solution, I tried this:
My questions:
Performance is not part of the question: pythonism and understandability is the issue.
Project Euler's Problem 40 involves generating the sequence of digits that appear in the natural numbers, all concatenated together (
123456789101112131415161718192021…). As part of the solution, I wrote this:def counting_digits():
for number in count(1):
for digit in str(number):
yield digitAfter finishing the solution, I tried this:
def counting_digits():
return (digit for number in count(1) for digit in str(number))My questions:
- In the face of Python 3, Which solution is more pythonic?
- As someone who just wants to understand the code. Which is easier/clearer to read?
- If you haven't read the statement for Project Euler's Problem 40, Which version lets you better know what the function does?
Performance is not part of the question: pythonism and understandability is the issue.
Solution
The one where you return a generator is easier to read were it the case that there was only one
The top one may be slightly easier to read for some people; it would be MUCH easier to read if there were comments or if the variables were semantically named, and the indented structure allows for comments much better. With semantically-named variables, the first version is easier to read; I'd only use single-letter variable names as the pattern in list comprehensions.
for. Also, as OP pointed out, the associativity of nested for loops is not what you'd expect in Python.The top one may be slightly easier to read for some people; it would be MUCH easier to read if there were comments or if the variables were semantically named, and the indented structure allows for comments much better. With semantically-named variables, the first version is easier to read; I'd only use single-letter variable names as the pattern in list comprehensions.
Context
StackExchange Code Review Q#2553, answer score: 12
Revisions (0)
No revisions yet.