+ 2

Are any solutions shorter than mine?

I'm learning Python, I practice lesson 30: FizzBuzz problem in Python Core. I can find the solution but I think my solution is quite long. Does anyone have a shorter solution but limit the knowledge of my lessons. https://code.sololearn.com/cFM3RMfW0I17/?ref=app

29th Jan 2023, 6:06 AM
Mythew
Mythew - avatar
5 Antworten
+ 5
Mythew Consider what would be the result for 60. Your code would print FizzBuzz although it is an even number. This is an error (although not verified by built in tests). To fix it you can move the check of x%2 to the first place in your if branch. Or follow the suggestion of Solo, you can loop only through even numbers like this, then you don't need this branch at all: for x in range(1, n, 2): Also you can simplify the FizzBuzz case if you verify divisible by 15, rather than 3 and 5. if x % 15 == 0:
30th Jan 2023, 2:49 AM
Tibor Santa
Tibor Santa - avatar
+ 6
You can exclude even numbers by setting the loop step to 2, then you don't need to add the condition "and x % 2 != 0", or write at the beginning of the loop - if x % 2 == 0: continue
29th Jan 2023, 7:18 AM
Solo
Solo - avatar
+ 2
Mirielle , interesting solution, but it will be shorter like this 😎: [print("FizzBuzz"[_*_%3*4:8--_**4%5]or _)for _ in range(1,int(input()or 150),2)]
29th Jan 2023, 7:32 AM
Solo
Solo - avatar
+ 2
Mirielle , this task requires the elimination of even numbers... 😎
29th Jan 2023, 7:52 AM
Solo
Solo - avatar
+ 1
Mythew you can add a third argument to range that tells it to step by 2 and thereby skip even numbers without explicitly testing for them. Below was my shortest solution that passed the Code Coach task. Notice that the range() uses a step of 2. It uses conditional expressions to multiply each string either 0 or 1 times to make "Solo"+"" or ""+"Learn". If both conditions are true then it will print "SoloLearn". If both conditions are false, the combined null strings ""+"" evaluate to false, and so it will print the second part of the logical 'or' expression, which is simply the value of x. [print("Solo"*(x%3<1)+"Learn"*(x%5<1)or x)for x in range(1,int(input()),2)] The conditionals test for <1, which is one character shorter than testing ==0.
30th Jan 2023, 7:22 AM
Brian
Brian - avatar