I really liked this Javscript FizzBuzz can it be as nice in Python?

Chris Angelico rosuav at gmail.com
Fri Apr 5 03:16:01 EDT 2019


On Fri, Apr 5, 2019 at 5:56 PM Sayth Renshaw <flebber.crue at gmail.com> wrote:
>
> I saw this fizzbuzz in Eloquent Javascript and thought its really nice. Not all the usual if else version, just if.
>
> for (let n = 1; n <= 100; n++) {
>   let output = "";
>   if (n % 3 == 0) output += "Fizz";
>   if (n % 5 == 0) output += "Buzz";
>   console.log(output || n);
> }
>
> I can't quite get a nice version like this out.
>
> This was my attempt to mimick it. I am sure Python can get it cleaner, but I had never thought about not doing if else for Fizzbuzz its just the way I did it.
>
> n = range(100)
> output = ""
> for num in n:
>     if (num % 3 == 0): output += "Fizz"
>     if (num % 5 == 0): output += "Buzz"
>     print(output or num)
>
> Haven't quite got it. But is possible nice and succinct like the javascript version. Maybe lambda will do it, gonna try that.

I'd recommend a more direct transformation, specifically resetting
'output' inside the loop. Otherwise, you basically have the same code.

> Any unique mindlowing style FizzBuzz I would never have considered and can learn off?
>

print(*[[n,"Fizz","Buzz","Fizzbuzz"][int("300102100120100"[n%15])] for
n in range(1,101)], sep="\n")

This is not good code, and if anyone asks, I didn't say you were
allowed to do this in an interview.

ChrisA



More information about the Python-list mailing list