Search code examples
pythonfizzbuzz

What is the star (*) doing in this FizzBuzz solution?


Learning programming in Python and I am doing some challenges. I've run into something I haven't learned yet and was curious what this code is doing.

So my challenge is called the "FizzBuzz" challenge. The instructions are simple:

Create a function that takes a number as an argument and returns "Fizz", "Buzz" or "FizzBuzz".

If the number is a multiple of 3 the output should be "Fizz". If the number given is a multiple of 5, the output should be "Buzz". If the number given is a multiple of both 3 and 5, the output should be "FizzBuzz". If the number is not a multiple of either 3 or 5, the number should be output on its own.

I wrote this code to solve it (obviously it can be better):

def fizz_buzz(num):
    if num % 3 == 0 and num % 5 == 0:
        return 'FizzBuzz'
    elif num % 3 == 0:
        return 'Fizz'
    elif num % 5 == 0:
        return 'Buzz'
    else:
        return str(num)

But, once I submitted my solution I was able to see the top solution, which is:

def fizz_buzz(num):
    return "Fizz"*(num%3==0) + "Buzz"*(num%5==0) or str(num)

My question is what is the * doing here? Can someone point me to documentation or resources that addresses what this persons code has done? I don't find it super readable but it is apparently the best solution to the problem.


Solution

  • Firstly, shorter doesn't always mean better. In this case, your solution is fine, and the "top solution" is clever, but needlessly confusing, as you're aware :P

    The star is doing string multiplication, and it's exploiting the fact that False == 0 and True == 1. So if num is divisible by 3, you get 'Fizz' once, and if num is divisible by 5, you get 'Buzz' once. Otherwise you get an empty string, '', and because an empty string is falsy, the or clause means it will be replaced by str(num).