+ 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
8 Answers
+ 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:
+ 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
+ 4
My solution is shorter but it doesn't mean it's better.. The zen of python gives higher priority to readability so I'd leave it as it was.
however, I identified some conditions you can delete to decrease the complexity of your program, 1 is to check only if the number is divisible by 15 first
my code shows a shorter version of yours using boolean logic and string slicing.. not sure if those are beyond your lesson yet
https://code.sololearn.com/cR6vax0W8v21/?ref=app
+ 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)]
+ 2
Mirielle , this task requires the elimination of even numbers... 😎
+ 2
Solo thanks for informing, the OP didn't mention that extra condition in description and I'm not updated about sololearn courses
+ 1
Solo I'm preoccupied with the use of hexadecimal numbers these days 😁 I use them in every opportunity lmao
But don't you think stepping 2 values forward will omit some fizz buzz and fizzbuzz numbers or is there a linear sequence that makes it safe to do
+ 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.