Communities

Writing
Writing
Codidact Meta
Codidact Meta
The Great Outdoors
The Great Outdoors
Photography & Video
Photography & Video
Scientific Speculation
Scientific Speculation
Cooking
Cooking
Electrical Engineering
Electrical Engineering
Judaism
Judaism
Languages & Linguistics
Languages & Linguistics
Software Development
Software Development
Mathematics
Mathematics
Christianity
Christianity
Code Golf
Code Golf
Music
Music
Physics
Physics
Linux Systems
Linux Systems
Power Users
Power Users
Tabletop RPGs
Tabletop RPGs
Community Proposals
Community Proposals
tag:snake search within a tag
answers:0 unanswered questions
user:xxxx search by author id
score:0.5 posts with 0.5+ score
"snake oil" exact phrase
votes:4 posts with 4+ votes
created:<1w created < 1 week ago
post_type:xxxx type of post
Search help
Notifications
Mark all as read See all your notifications »
Q&A

Welcome to Software Development on Codidact!

Will you help us build our independent community of developers helping developers? We're small and trying to grow. We welcome questions about all aspects of software development, from design to code to QA and more. Got questions? Got answers? Got code you'd like someone to review? Please join us.

Post History

66%
+4 −1
Q&A Create a list of Niven numbers in Python

Think of what your for loop is doing, specifically at iterations 11 and 12. for i in range(1,n+2): while not g(i): i+=1;continue a.append(i) In pseudo instructions: for-loop iterati...

posted 1y ago by Moshi‭

Answer
#1: Initial revision by user avatar Moshi‭ · 2022-08-20T04:28:12Z (over 1 year ago)
Think of what your `for` loop is doing, specifically at iterations 11 and 12.

```python
for i in range(1,n+2):
	while not g(i):
		i+=1;continue
	a.append(i)
```

In pseudo instructions:

- for-loop iteration 11
  - i = 11
  - while-loop:
    - check not g(i) (i = 11, so it's true)
    - i += 1
    - check not g(i) (i = 12, so it's false)
  - append i (appends 12)

- for-loop iteration 12
  - i = 12
  - while-loop:
    - check not g(i) (i = 12, so it's false)
  - append i (appends 12)

That is, the problem is that as it is written, it is "for `i` from `1` to `n + 2`, *get the smallest Niven number greater than `i`*" which is probably not what you want.

One possible fix to this is just to separate the list index counter and the Niven number counter. The implementation is left as an exercise to the reader.