简体   繁体   中英

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

I'm trying to print all the numbers from 100 to 200, ten per line, that are divisible by 4 or 5, but not both. The numbers in a printed line are separated by exactly one space. Example of what I'm trying to achieve is:

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 have tried this:

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

I can get it to print all the numbers from 100-200 and not the ones divisible by 4 and 5 but I cant quite get it to print numbers divisible by 4 or 5 but not 4 and 5. also getting them to print 10 per line has been a tricky

Appreciate any help or being put in the right direction

"Divisible by 4 or 5 but not 4 and 5" is an xor operation, so here's an example with python's operator.xor method:

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)

And to print 10 per line, you can do something like:

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)

this will do :)

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:])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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