0

Fizz Buzz

in the test for module 3 in Python Core, it was proposed to create code that would not display even numbers. I solved this problem by simply inserting the line if not x%2==0:. But in the description it was written that you can use "continue". What prompted me to think that I cheated somewhere. Now it became interesting, what other solutions exist? n = int(input()) for x in range(1, n): if not x%2==0: if x % 3 == 0 and x % 5 == 0: print("SoloLearn") elif x % 3 == 0: print("Solo") elif x % 5 == 0: print("Learn") else: print(x)

13th Nov 2022, 5:27 PM
đčđ░đ▓đÁđ╗ đíđŞđ┤đÁđ╗ĐîđŻđŞđ║đżđ▓
đčđ░đ▓đÁđ╗ đíđŞđ┤đÁđ╗ĐîđŻđŞđ║đżđ▓ - avatar
2 Antworten
+ 2
The rewrite with continue can remove nesting from your if condition. That way the code will skip to the next value of the loop. for x in range(1, n): if x%2==0: continue if x % 3 == 0 and x % 5 == 0: print("SoloLearn") elif x % 3 == 0: print("Solo") elif x % 5 == 0: print("Learn") else: print(x) Another even simpler way would be to use a range with step. So it would only process every second number (leave out the evens) for x in range(1, n, 2):
13th Nov 2022, 5:52 PM
Tibor Santa
Tibor Santa - avatar
+ 1
đčđ░đ▓đÁđ╗ đíđŞđ┤đÁđ╗ĐîđŻđŞđ║đżđ▓ the lowest bit of an integer can indicate whether the number is even or odd. If the bit is 0 then it is even. If it is 1 then it is odd. The Bitwise And (&) operator can mask out the other bits and leave only that bit for testing: if x & 1: #process the odd values This is a much faster method of testing than modulo (%). Still, faster yet is no testing at all by using Tibor Santa's tip of using a step of 2 in the range.
13th Nov 2022, 6:40 PM
Brian
Brian - avatar