簡體   English   中英

打印范圍內可以被 4 或 5 整除的所有數字,但不能同時被 4 或 5 整除

[英]print all the numbers in a range that are divisible by 4 or 5, but not both

我試圖打印從 100 到 200 的所有數字,每行十個,可以被 4 或 5 整除,但不能同時被整除。 打印行中的數字正好由一個空格分隔。 我試圖實現的示例是:

104 105 108 110 112 115 116 124 125 128 
130 132 135 136 144 145 148 150 152 155 
156 164 165 168 170 172 175 176 184 185 
188 190 192 195 196

我試過這個:

i=100
a=100
while i<=200:
    if ((a%3 and a%5)==0) :
        a=a+1
    elif a/3 ==0 and a/5 != 0:
        print(a)
        a=a+1
    else:
        print(a," ")
        a=a+1
    i=i+1

我可以讓它打印 100-200 之間的所有數字,而不是可被 4 和 5 整除的數字,但我無法打印可被 4 或 5 整除但不能被 4 和 5 整除的數字。也讓它們每行打印 10 個一直很棘手

感謝任何幫助或被置於正確的方向

“可被 4 或 5 整除但不能被 4 和 5 整除”是一個異或運算,所以這里有一個使用 python 的operator.xor方法的例子:

import operator

nums = [i for i in range(100,201) if operator.xor(not i % 4, not i % 5)]

for i in range(0, len(nums), 10):
    print(" ".join(str(x) for x in nums[i:i+10]))
for i in range(100, 201):
    if i % 4 == 0 and i % 5 == 0:
        continue
    if i % 4 != 0 and i % 5 != 0:
        continue
    print(i)

要每行打印 10 個,您可以執行以下操作:

printed = 0
for i in range(100, 201):
    if i % 4 == 0 and i % 5 == 0:
        continue
    if i % 4 != 0 and i % 5 != 0:
        continue
    print(i, end=" ")
    if (printed := printed+1) == 10:
        printed = 0
        print()
lines = ""
count_nums_in_one_line = 0

for i in range(100, 201):
    if count_nums_in_one_line == 10:
        lines += "\n"
        count_nums_in_one_line = 0

    if i % 4 == 0 and i % 5 == 0:
        pass

    elif i % 4 == 0 or i % 5 == 0:
        lines += str(i)
        lines += " "
        count_nums_in_one_line += 1

print(lines)

這會做:)

My 2 cents:

l=[i for i in range(100,201) if (i%4==0)!=(i%5==0)]
for i in range(len(l)//10):
    print(*l[i*10:i*10+10])
print(*l[len(l)//10*10:])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM