Artur
Artur

Reputation: 13

the sum of all numbers below N that contain the digit 7

Can you please help me to find the issue in my code? The exercise is; Write a program to input number N in range of [1-1000] and print the sum of all numbers below N that contain the digit 7. Print an error message if the user inserts an out of range number and ask to insert again.

var = 1
while var == 1:
    n=int(input("Enter the Number in range [1,1000]:"))
    while n in range(0,1001):
        k = 0
        i=0
        m=0
        s=0
        e=0
        f=0
        g=0
        if n in range(100,1001):
            for c in range(100,n+1):
                if c%10 == 7:
                    i += c
                if (c//10)%10 == 7:
                    c%10 != 7
                    s += c
                if c//100 == 7:
                    (c//10)%10 != 7
                    c%10 != 7
                    e += c
            print(1188 + i + s + e)
        if n in range(0,100):
            for b in range(1,n+1):
                if b%10 == 7:
                    f += b
                if b//10 == 7:
                    g += b
            if b >= 77:
               g=g-77
            print(f+g)
        break
    else:
        print("n is not in the range")       

It counts the sum in range (170,180) by adding always 170 and not only in this range.

Upvotes: 1

Views: 458

Answers (2)

Dominux
Dominux

Reputation: 239

We can convert our number to a str() and then to a list(). After that we from, for example, 456 get ['4', '5', '6']. And now we can easily check if 7 is in our number. PROFIT!

Then we take our list with numbers which contain 7 to *args in sum() and get final result! Uhhuuuu! Yeah

N = int(input("Write number: "))

while (N < 1) or (N > 1000):
    N = int(input("Write number again: "))

all_numbers_with_seven = [n for n in range(1, N) if '7' in list(str(n))]

print(sum(all_numbers_with_seven))

Upvotes: 1

Mert K&#246;kl&#252;
Mert K&#246;kl&#252;

Reputation: 2231

In while block, we are testing if n is valid or not. After while block there is a list comprehension.

contains_seven = [x for x in range(0,n+1) if '7' in str(x)]

We are taking every number in range 0 to n+1 which has '7' in it. After that, we are summing them via sum() function and print it. Full implementation is:

while True:
    n = int(input("input n: "))
    if (n>0 and n<=1000):
        break    
    print("n is not in the range")

contains_seven = [x for x in range(0,n+1) if '7' in str(x)]
a = sum(contains_seven)
print(a)

Upvotes: 3

Related Questions