3 ms·
I agree that I hate this solution. However, are you saying that this is a bad FizzBuzz solution to you? (Python) nums = list(range(100)) def fizzbuzz(n)
by jacksnipe 5y ago
I agree that I hate this solution. However, are you saying that this is a bad FizzBuzz solution to you? (Python)
nums = list(range(100))
def fizzbuzz(n):
if n % 15 == 0:
return "FizzBuzz"
elif n % 3 == 0:
return "Fizz"
elif n % 5 == 0:
return "Buzz"
else:
return str(n)
print(" ".join(map(fizzbuzz, nums)))
I think it's far better than:
nums = list(range(100))
for num in nums:
if num % 3 == 0:
print("Fizz", end="")
if num % 5 == 0:
print("Buzz", end="")
if num % 3 != 0 and num % 5 != 0:
print(num, end="")
print(" ")
EDIT: Formatting, typo
- IanCal 5y agoAt the risk of the classic "no here's the fizzbuzz code" while then getting it wrong, the typical case you're trying to draw out is like the second but: Not printing in the middle, return a string and afterwards print it. Each step adds to the string, and if it's still empty by the end you just put the number in. The next stages are often to add another number, then something more complex (if it's a prime number). As you do this, the concatenation version grows slowly while the first approach explodes in combinations.
- dan-robertson 5y agoI don’t want to argue in favour of the Beads solution but I think the right way to describe the logic is as follows: input is n | 3 divides n | 5 divides n | result | |—————————————|—————————————|————————————| | Yes | Yes | “FizzBuzz” | | Yes | No | “Fizz” | | No | Yes | “Buzz” | | No | No | n.toString | print result The key points are: 1. The logic is declarative: the order of the rows in the table doesn’t matter. 2. It tests for divisibility in words rather than a potentially confusing idiom (how does % behave for negative numbers? Is it defined for floats in this language?) 3. The structure allows you (or a compiler) to check that no case is missed. 4. It should be easier to convince oneself that modifications to the code do what they are supposed to. The funny thing is that looking things up in tables is much more common in excel.
- jacksnipe 5y agoI agree, I think that's close to isomorphic to my first solution! There's a "mapping" from numbers to strings, and this is the mapping.