I am trying to generate numbers that are between 12 and 77, excluding 21, 28, 31, 38, 41, 48 etc. I could probably try using % and while loops but is there a quicker, more pythonic way?
Asked
Active
Viewed 76 times
3 Answers
0
Do you mean like:
[n for n in range(12, 78) if repr(n)[-1] not in ('1', '8')]

Arno Maeckelberghe
- 377
- 1
- 7
0
If you want to use generators and endswith() you can do as follows:
def gen(n1, n2, exclude):
for i in range(n1, n2):
if not str(i).endswith(exclude):
yield i
for i in gen(12, 30, exclude=('1', '8')):
print(i)

Omar Cusma Fait
- 313
- 1
- 11
0
You could use a variable increment that will make your number progress exactly to the desired values without generating unnecessary entries that you have to filter out.
n = 12
while n<=77:
print(n)
n += 1 + (n%10 in (0,7)) # or: n += 2 - 0**(n%10%7)
12
13
14
15
16
17
19
20
22
23
24
25
26
27
29
30
32
...
69
70
72
73
74
75
76
77

Alain T.
- 40,517
- 4
- 31
- 51