我正在尝试打印从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个很棘手
感谢任何帮助或朝着正确的方向
答案 0 :(得分:3)
“可以被4或5整除,但不能被4和5整除”是一个xor操作,因此下面是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]))
答案 1 :(得分:2)
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()
答案 2 :(得分:1)
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)
这会做:)
答案 3 :(得分:0)
numbers = [] # initialise list
for i in range(100, 201):
if not i%(4*5)==0: # numbers divisible by 4 and 5 are divisible by 4*5
if (i%4==0) | (i%5==0):
numbers.append(str(i))
if len(numbers)==10: # if 10 items are found, print, and reinitialise empty list
print(' '.join(numbers))
numbers = []
答案 4 :(得分:0)
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:])