简体   繁体   English

N 以下所有包含数字 7 的数字的总和

[英]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.编写一个程序,输入 [1-1000] 范围内的数字 N,并打印 N 以下所有包含数字 7 的数字的总和。如果用户插入超出范围的数字并要求再次插入,则打印错误消息。

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.它通过始终添加 170 而不仅仅是在此范围内来计算范围 (170,180) 中的总和。

In while block, we are testing if n is valid or not.while块中,我们正在测试n是否有效。 After while block there is a list comprehension.while块之后有一个列表理解。

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.我们取 0 到 n+1 范围内的每个数字,其中包含“7”。 After that, we are summing them via sum() function and print it.之后,我们通过sum() function 对它们求和并打印出来。 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)

We can convert our number to a str() and then to a list() .我们可以将我们的数字转换为str() ,然后转换为list() After that we from, for example, 456 get ['4', '5', '6'] .之后,我们从例如456得到['4', '5', '6'] And now we can easily check if 7 is in our number.现在我们可以轻松地检查7是否在我们的数字中。 PROFIT!利润!

Then we take our list with numbers which contain 7 to *args in sum() and get final result!然后我们在sum()中取出包含 7 到 *args 的数字列表并获得最终结果! 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))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM