Home > Software engineering >  Excluding a digit in a for loop
Excluding a digit in a for loop

Time:04-18

Hi I would like to exclude any number that contains a 7 from the range of 1-1000 in my for loop.

This is the code I have so far

sum = 0 
for i in range(1,1001): 
    if #digit contains a 7: 
        continue
    sum = sum   1/i
    return sum 

CodePudding user response:

Here's one way to do it by isolating each of the 3 possible digits in your range:

sum = 0 
for i in range(1,1001): 
    if 7 not in (i-10*(i//10), i//10-10*(i//100), i//100-10*(i//1000)):
        sum = sum   1/i
print(sum)

Output:

6.484924087833117

UPDATE: To generalize for an arbitrary top number other than 1001, you could do this:

sum = 0 
top = 1001
tens, temp = [1], 1001
while temp > 0:
    tens.append(tens[-1] * 10)
    temp //= 10
for i in range(1,top): 
    digits = [i // tens[j] - 10 * (i // tens[j   1]) for j in range(len(tens) - 1)]
    if 7 not in digits:
        sum = sum   1/i
print(sum)

As suggested in comments by @Lukas Schmid, this also works and may be preferable (it's certainly easier to read):

sum = 0 
top = 1001
tens, temp = [1], 1001
while temp > 0:
    tens.append(tens[-1] * 10)
    temp //= 10
for i in range(1,top): 
    digits = [i // tens[j] % 10 for j in range(len(tens) - 1)]
    if 7 not in digits:
        sum = sum   1/i
print(sum)

CodePudding user response:

One of the simplest way to achieve that without using lots of maths, is to treat the number as a string and compare it to the char '7':

sum = 0
for i in range(1, 1000):
    if '7' in str(i):
        continue
    sum  = 1/i
return sum

Also, note that the return statment should be outside the for loop.

  • Related