Can you explain the horror? I'm not a python dev but this looks prettyreasonable. Could it be slightly better, sure. But not quite horror levels.
Edit: In my replies are the following... People who think throwaway code from a first year uni class needs to be perfect. People who think every piece of code needs to be a work of art. People who don't understand YAGNI. People who think "I wouldn't have written it that way" is equivalent to horror.
It's fizzbuzz guys. It's not enterprise world class Web 4.0 Scale software now with AI (tm) and it doesn't have to be.
Yeah, like it’s horror in where it’s going. Another case and we need 8 switches, another and we need 16, etc., but wouldn’t technically call it horror yet until it had more cases. In its current state, it makes me wince but not cry.
I’d leave a review comment saying this makes my eyes hurt and rewrite x way if it was in a PR, but wouldn’t consider it horror.
If it was an interview I’d just ask them how they’d approach adding another case, and make sure that they recognize their current pattern isn’t scalable
A problem of this type may, hence why I would ensure they understand the limitation in an interview, and accept their answer if they show that they do.
If this was a code base, it can simply be written cleaner. But, you wouldn’t be PRing FizzBuzz. You’d be PR’ing a problem of this type
So which one do you disagree with, that this is not horror, but could be cleaner if in PR or that this would be acceptable in an interview if candidate was able to identify that this pattern doesn’t scale when I ask?
You say it wouldn't scale well, but it isn't really any worse when adding additional constraints than the traditional if elseif elseif else implementation.
If I were reviewing this I probably wouldn't complain, at worst it would be a nit to name the conditionals or something. With a dict to name the conditions it can scale as far as code realistically should before talking about data-driven implementations or a dedicated class.
Realistically it's a short enough piece of code that it can easily be rewritten later if necessary, and it isn't hairy enough that it would cause a problem to do so.
On your edit, nobody is talking like that lmao. You asked to explain how it could be horror so we did.
Saying I’d probably leave a PR comment (which can be non-blocking to merge depending on specific case)?
Or making sure an intern (only person who I might actually start with FizzBuzz in an interview) can answer a valid follow up question to test their pattern recognition?
You can say you don’t mind the switch case, who cares.😂 It’s ridiculous to get so bent up over the above two statements though
“I asked you to give me horror and you give me nit picks and made up requirements. You say I’m “bent up” but spent your Saturday talking about it.”
Read more carefully. I said it isn’t horror in current state. That if it were extended it would be. That if I were in an interview I would ask them a follow up.
That I would leave:
nit: Can reduce with: insert code
In a PR. On the Saturday thing, that’s a good one, but I’m over here laughing. This was more passive amusement. I still don’t understand what y’all are really disagreeing with. Is this how you act at work if someone leaves a nit in your PR? Yeesh
It's not that strange, it's maybe using features that are overkill for the task, but it's using them how you'd expect to use them if that's what you chose to use.
Clearly they didn't test it but the idea was right. Here's the full one-liner. I think it's cool. Bust this one out at your next whiteboarding interview. for i in range(100): print([i, "Fizz", "Buzz", "FizzBuzz"][(not (i%3))+2*(not(i%5))])
I don't do much python and I don't have a python shell on my phone. I thought it should get the idea across, even if I don't quite remember the correct syntax.
print("\n".join(["FggFgBFggFBgFggiggiguiggiugigg{1}{1}B{0}u{0}z{0}z{0}".format("g"*14,"zggzgzzggzzgzgg")[n%15::15].rstrip("g")or(str(n))for n in range(1, 101)]))
I will explain, the code uses the fact that FizzBuzz repeats in cycles of 15, and anything after the number 15 is just a repeating sequence except the numbers are different, see here:
Note this little piece of the code: "FggFgBFggFBgFggiggiguiggiugigg{1}{1}B{0}u{0}z{0}z".format("g"*14,"zggzgzzggzzgzgg")
If you expand evaluate it and replace every g with a dot, you get: F..F.BF..FB.F..i..i.ui..iu.i..z..z.zz..zz.z..z..z.zz..zz.z..B..............u..............z..............z..............
Which seems like a random string until you add a line break every 15 characters:
If you read it column by column, now it makes a lot more sense, you see things like Fizz...., ........ and FizzBuzz. The pattern also matches the repeating pattern of FizzBuzz (1, 2, Fizz, 4, Buzz...) except FizzBuzz is at the start, and the numbers are just replaced with ........
Now see this piece of the code, here n is a number between 1 and 100: [n%15::15]
Note the ::15, which corresponds to taking every 15th character from the string. In this square of characters you see above, that corresponds to just taking one column, the n%15 part says where to start, ie what column to take from the string, for example, if n is 4, then n%15 is 4, so it takes the fifth column, which is just ........, if n is 5, n%15 is 5, so it takes the sixth column, which is Buzz...., it goes like this for other numbers
Finally, or(str(n)) will replace all the empty strings (like the ones corresponding to 1, 2, 4, etc...) with the number itself. The rest of the code does this for every n between 1 and 100 and prints it out.
With a better naming this should be the canonical implementation.
It directly implements the spec without any extra ambiguity about what is supposed to happen and when via some nested string mutation (aka your usual "solution" to the fizzbuzz). This solution is very readable and is directly relatable to the problem statement. There's no performance hit to maintain this level of clarity and verbosity.
OP, improve the naming, make m a dict, or have it to be two vars, and then submit this into a museum.
The point of fizzbuzz isn't really to test issues of scalability or maintainability. It's just to see if you know how to do basic things like loops and if/else. Apparently a large chunk of interview candidates still can't manage to pass such a basic hurdle.
I would say the downsides are the extra storage - if I have n unique keys, I'll have to store that many key pairs. I think other than that it's a one to one on the logic - I'm just shifting from an explicit switch statement with n items to a loop over n items. As far as dealing with duplicate keys, I think concatenating and storing one string per key makes sense. Final runtime would be O(m*n) where n = # unique keys and m = # of #s checked.
Am I missing anything/what would you be looking for? (I appreciate the response)
That is a sound description. Extra storage is usually almost free and there is not much difference in storing the values in variables vs in a dict. And you have to store them somewhere.
Is there a more efficient data structure that allows the search for a key in a better time than O(n*m)? Or, as you seem to be using python in your example, is there a better way of accessing the values with the same improvement as my previous sentence?
If I was asking this as an interview question and someone immediately structured it to allow FizzBuzzBonkOink, I'd follow up with "Requirements have changed, now print 'Foobar' when its a multiple of 15" :P.
I think its funny that people's immediate reaction to the problem is "Its underspecified, and I know exactly the way that its underspecified and will substitute my own specification"... which might not actually be the way that the problem changes in the future.
Generally all these interview questions are always the most idiotic thing ever. They give you a toy problem and want you to both have a minimal tailored super-fast algorithm that solves it while you should also think about systems design.
Decide what you're asking.
A simple two-way fork should always be solved in the most obvious way. The code is more often read than written, and the interpreter/compiler doesn't care.
The thing about fizzbuzz is that half of computer science graduates can't do it on a whiteboard. It's a really quick and easy way of throwing out people who have managed to get their degree without being able to program. Anything beyond that is a bonus. And if you think it's idiotic, congratulations, you've yet to learn how bad many of your peers are.
I already gave this as a warm-up at the start of the interview, trying to put the person on ease. Implement in a language of choice on the whiteboard 30 minutes later we ended the conversation as the person still didn't have something close to a correct solution. Usually people bast through that in 5 minutes.
If I was doing it for an interview, there are 2 things that I would do differently.
Extract a method, so that the top is something like
for i in range(0, 100):
print(FizzBuzz(i))
Discuss unit testing that extracted method.
But the body of that method can quite possibly use the tuple of 2 bools, with a switch over it, like OP has. It's small and under test so we're good, you can use language features.
If at this point you realized that the problem you're solving has a compounding structure (and not something that also says "when number is prime bonk becomes yonk and goes before buzz"), then it might be a good idea to refactor it a bit. Set boolean flags for each word and compound them separately. Will let you reorder them easily once you realize your users prefer bonkfizz over fizzbonk.
I would have just a single print at the end of the loop body and have the match just assign to a string variable the content to print, but otherwise yeah it looks good.
This is a problem for beginner programmers. The regular implementation is 7 lines and uses basic if statements. This uses more advanced features (match, tuples) and Is also longer. It’s strictly worse, and will confuse beginners
That's not a bad implementation to be honest. The only real thing that tickles me is the unnecessary assignment to m instead of just inlining the expression, but that's by the by
Yeah I would be shocked if a company asked a candidate FizzBuzz in an interview. This is a first day learning coding training problem.
But, it so simple and open ended that you can learn a lot. Ask them to add 2 more cases and watch their implementation explode. Walk them through rewrite. Hell, could even add more cases and use it for learning concurrency. Show how naive implementation has output with inconsistent ordering. Have them synchronize it in follow up, etc.
It’s very simple but showcases a lot with slight modifications
That’s wild to me. I wouldn’t expect to ask this unless it was junior intern, like underclassmen undergrad level. Crazy to hear that you can ask this for legit candidates and get stumps
Hahaha yeah that’s a tough spot. I had an interview once where I was given a very high difficulty sudoku based problem that I had to code in google docs. Hadn’t played sudoku since I was like 10 lol.
Really threw me for a loop and did below standard. Got the job due to other interviews, but had to do really great in them to make up for it.
Even then, I wasn’t mad at anyone but myself. But I feel like that’s a case where someone could understandably struggle and still be a potential candidate. Idk where you’re supposed to go if FizzBuzz blocks the interview
Thank you so much for your responses. I’m still pretty new to hiring and stuff, so this is very valuable to me.
Yeah, I agree. I do think that DSA interviews have long outlived their use. Especially when it became gamified and we generated leagues of devs who can solve any coding problem like it’s nothing, but can’t actually develop anything. I think we’ve all experienced the hire that was incredible in interview, and subpar in practice. Personally I would match rather listen to someone’s approach to design for an actual feature, instead of gauging how much of Crack the Coding Interview they read. I wanna know if they’re gonna write interfaces that make sense or couple garbage together until it works
It might be an interesting problem if you modified it a bit so people had to use some kind of sieve. For example don’t use 3,5 etc but specify that every second prime factor has a word associated with it (hash of the prime) and run the problem for first 1e10 numbers.
If I was being interviewed by you, I would ask, do you want that embedded nicely in an HTML document, or is terminal output fine?
I can do the former with JavaScript, Python, or C#. I can do the latter in all of the above, plus Java and C++, and I can also do it inside the games Creeper World 3 or Creeper World 4 using RPL scripting if you'd like. I would like to learn enough Lua to do FizzBuzz in that as well.
Follow up, would you like my program to include additional prime values (fizzbuzzbangoink) with user input options? And would you like internal test cases?
I can't say I'm a terribly great programmer, but I find I do better with additional goals.
Side note, I will be challenging myself later this week to make a really nicely formatted output for Fizzbuzz in JS embedded in an HTML document, with toggleable checkboxes for fizz, buzz, bang, and oink. Because I feel like it.
Well, even the most complete solution of FizzBuzz is quite short and simple. Unless you want some fancy stuff in it. The person you answered to seems to be used to fancy stuff.
Yes, the original article claims a high percentage of job candidates, even some with computer science degrees, couldn't write FizzBuzz in the interview.
I know people are nervous and and not at their best in an interview, but c'mon.
I'd question the coding part of a computer science degree, or if it's real, if somebody with a computer science degree fails at coding FizzBuzz. Even in a random syntax that was shown for 5 minutes and not in a language this person should be proficient in.
It's a great way to see how people approach problems, because there's a gajillion ways to produce a correct solution. OP, for example, writes incredibly neat and readable code.
If someone submits a code golf type one liner? Then you know his coding ability is really deep, but his work might not be readable or maintainable.
FizzBuzz is at this great level of complexity where it can filter out people who can't really code without being unnecessarily difficult, while having enough nuance to allow deeper/broader interpretation in solutions.
E.g. my preferred solution never adds a third option specifically for FizzBuzz, I'll just use my Fizz and Buzz options sequentially in the call. Why? Because I fucking hate vestigial code.
This is not horror lol, this is really elegant. Basically the most obvious and straightforward way to implement the logic you want, which is what you should do when performance is not relevant.
You should avoid the modulo function, as it is computationally expensive. Here's a much faster version.
N = input("Set a limit: ")
three: int = 3
five: int = 5
# Store options in mutable list
options: list = [None, "Fizz", "Buzz", "FizzBuzz"]
# Loop over all N (+1 because the last is otherwise excluded)
for n in range(1, int(N)+1):
# Replace default value with current number
options[0] = n
selection: int = 0
# Shift one to the right and set next multiple of 3
if (n is three):
selection += 1
three += 3
# Shift two to the right (0 -> "Buzz" or "Fizz" -> "FizzBuzz")
if (n is five):
selection += 2
five += 5
# Print selected element
print(options[selection])
I work mostly in function languages besides Java (wish it was Kotlin) and this looks like a very elegant implementation to me. I wish more languages had pattern matching.
Your implementation has zero scalability. If you add more combinations you have to change every case. Where as with plain if statement you just add another conditional.
Computationally if statements are worse, but you can also probably remove some of the branching. With multiple if statements a compiler might simd the comparators and append without branching.
This is python, so there's no compiler... But if you're writing on python you don't care so much about performance anyway.
It's fine. The entire point of FizzBuzz is to find out if a developer thinks to use modulo. You don't need to check anything beyond that. Hell, I don't even care if it works.
let fizzbuzz n =
let check d s = if n mod d = 0 then s else "" in
match check 3 "Fizz" ^ check 5 "Buzz" with
| "" -> string_of_int n
| s -> s
let () =
Seq.init 100 (fun i -> i + 1)
|> Seq.map fizzbuzz
|> Seq.iter print_endline
178
u/ababcock1 Feb 28 '26 edited Feb 28 '26
Can you explain the horror? I'm not a python dev but this looks prettyreasonable. Could it be slightly better, sure. But not quite horror levels.
Edit: In my replies are the following... People who think throwaway code from a first year uni class needs to be perfect. People who think every piece of code needs to be a work of art. People who don't understand YAGNI. People who think "I wouldn't have written it that way" is equivalent to horror.
It's fizzbuzz guys. It's not enterprise world class Web 4.0 Scale software now with AI (tm) and it doesn't have to be.
920
u/Empty-Rough4379 Feb 28 '26
Seems reasonably elegant
482
u/lonkamikaze Feb 28 '26
print([i, "Fizz", "Buzz", "FizzBuzz"][!(i%3)+2*!(i%5)])330
u/PlebbitDumDum Feb 28 '26
With a better naming this should be the canonical implementation.
It directly implements the spec without any extra ambiguity about what is supposed to happen and when via some nested string mutation (aka your usual "solution" to the fizzbuzz). This solution is very readable and is directly relatable to the problem statement. There's no performance hit to maintain this level of clarity and verbosity.
OP, improve the naming, make
ma dict, or have it to be two vars, and then submit this into a museum./r/lostredditors
27
u/ra_men Feb 28 '26
LGTM lmk when you’re free to take on a few more tickets this sprint
21
u/Glad_Position3592 Feb 28 '26
Actually, yeah I do
16
u/AbdSheikho Feb 28 '26
I see pattern matching, but it needs more Haskell
14
u/Ariquitaun Pronouns:This/Self Feb 28 '26
That's not a bad implementation to be honest. The only real thing that tickles me is the unnecessary assignment to m instead of just inlining the expression, but that's by the by
12
u/spiderpig20 Feb 28 '26
Might be the most elegant fizzbuzz implementation I’ve ever seen tho. Not horror
20
u/Geekureuil Feb 28 '26
I always perfered the concatenation way, but yours is original and elegant.
7
u/SoftwareDoctor Feb 28 '26
I never understood the point of this exercise. I understand the assignment but why?
7
u/Romejanic [ $[ $RANDOM % 6 ] == 0 ] && rm -rf / || echo “You live” Mar 01 '26
Honestly this is probably the cleanest possible FizzBuzz implementation. Pattern matching is awesome I wish more languages supported it
4
u/SideburnsOfDoom Feb 28 '26
Not a horror. I could write very similar in C# using foreach, tuples and switch case. And I would rate it elegant.
4
u/PityUpvote Mar 01 '26
Lose the ==0 and match (0,0), then (0,_) and (_,0).
4
u/kaisadilla_ Mar 01 '26
This is not horror lol, this is really elegant. Basically the most obvious and straightforward way to implement the logic you want, which is what you should do when performance is not relevant.
4
u/Ambitious-Treat404 Mar 02 '26
6
u/ByteArrayInputStream Feb 28 '26
It's almost a good implementation. I'd just change it to
for readability.
I structure a lot of my code like this and once you get used to it, it's really readable.
This pattern can transform some complex expression into a simple truth table.
3
u/PolyPenguinDev Mar 01 '26
it’s honestly probably more efficient
5
u/rylut Feb 28 '26
I have never seen code that puts 2 bools into one variable just like it's done in line 2.
2
u/F14-Tomboy Feb 28 '26
Wait, python has switch/case now?
2
u/just-bair Mar 01 '26
Functional bros hate this one trick
2
u/MegaChubbz Mar 01 '26
Wait I kind of like this lol
2
u/nocturn99x Mar 02 '26
Damn this is an interesting way to do it
5
u/-Wylfen- Feb 28 '26
It's horrible, but somehow it's an interesting horrible
1
u/evbruno Feb 28 '26
I do like.
1
u/AdamGarner89 Feb 28 '26
Is the horror that it's wrong? It doesn't print 1,2,fizz etc it prints 12fizz4buzz etc
1
u/JollyJuniper1993 Feb 28 '26
So what exactly is horror about this?
1
u/GoddammitDontShootMe [ $[ $RANDOM % 6 ] == 0 ] && rm -rf / || echo “You live” Feb 28 '26
I'm not seeing the horror here.
1
u/jsrobson10 Feb 28 '26
this is fine
1
u/Mr_FizzBuzz Feb 28 '26
As an expert in this particular domain, yes. Yes I do.
1
u/wiseguy4519 Feb 28 '26
Why did it take so long to get switch case in Python? We've been held back from glorious code like this for so many years.
1
u/Powerkaninchen Mar 01 '26
The worst part are the Ligmatures where = turns into easily confusable long =
1
u/Dangerous-Mud-399 Mar 01 '26
1
u/djlamar7 Mar 01 '26
Needs more tensorflow
1
u/Pleyotrop Mar 01 '26 edited Mar 01 '26
You should avoid the modulo function, as it is computationally expensive. Here's a much faster version.
1
u/Laeskop Mar 01 '26
You speak the
(True, True)1
u/BlazingThunder30 Mar 01 '26
I work mostly in function languages besides Java (wish it was Kotlin) and this looks like a very elegant implementation to me. I wish more languages had pattern matching.
1
u/inglorious_gentleman Mar 01 '26
Completely fine
1
u/_PM_ME_PANGOLINS_ Mar 01 '26
Would be much nicer if you inlined
m.1
u/Qyriad Mar 01 '26
It's… fine? It's fine. Like, /uj, it's literally fine.
1
u/Horror-Water5502 Mar 01 '26
Perfectly fine
1
u/Zastai Mar 01 '26
Not terrible. But it’s usually 1-100, not 0-99.
1
u/blackasthesky Mar 01 '26
What's basically how you'd do it in many functional languages
1
u/kilkil Mar 01 '26
where is the horror? that looks perfectly fine
1
u/HeavyCaffeinate Pronouns: She/They Mar 02 '26
Actually looks pretty good
1
u/4oby Mar 02 '26
It’s very clear and readable. I usually go with something along the lines of
’’’
func fizzBuzz(num: Int) -> String {
}
’’’
Edit: formatting on the phone is pain
1
u/aaronsb Mar 02 '26
Yes but, have you tried parallel tensors and fourrier analysis? https://github.com/aaronsb/fizzbuzztensor
1
u/Astrodude80 Mar 02 '26
This is… actually really good??
1
u/Logical_Insect8734 Mar 02 '26
why are people upvoting this? literally the wrong sub.
1
u/OlegSentsov Mar 02 '26 edited Mar 02 '26
print(*[("Fizz"*(not i%3)+"Buzz"*(not i%5))or i for i in range(0,100)],sep="\n")1
u/alphapussycat Mar 02 '26
Nah, just if statements is better.
Your implementation has zero scalability. If you add more combinations you have to change every case. Where as with plain if statement you just add another conditional.
Computationally if statements are worse, but you can also probably remove some of the branching. With multiple if statements a compiler might simd the comparators and append without branching.
This is python, so there's no compiler... But if you're writing on python you don't care so much about performance anyway.
1
u/Kindly-Berry5099 Mar 03 '26
Get rid of that dangerous underscore, put False,False and your golden
1
u/qwertty164 Mar 03 '26
I have never seen an emdash equals for comparison.
1
u/axehammer28 Mar 03 '26
You made the same subtle and all-too-familiar mistake I did on a recent interview: iterating starting at 0 instead of 1.
1
u/SimplexFatberg Mar 03 '26
This is a perfectly reasonable implementation. There's no horror here.
1
u/digitaljestin Mar 04 '26
It's fine. The entire point of FizzBuzz is to find out if a developer thinks to use modulo. You don't need to check anything beyond that. Hell, I don't even care if it works.
1
u/moduspwnens9k Mar 04 '26
When did python get a switch statement
1
u/PeachScary413 Mar 04 '26
Why is this programming horror? Is this some kind of meta-joke I'm too functional to understand?
1
u/TomosLeggett Mar 16 '26
Ladies and gentlemen, the OCaml 100% dry way: