Recently I have wanted to take up learning Python (and programming in general) again. As I am currently job hunting, I figured a fun and relatively simple project to start out again would be to solve the reasonably common interview question “FizzBuzz”. Naturally I don’t expect to be asked said question as I am not a developer but it is fun to learn regardless. The question is as follows, and is based on a children’s game.
“Write a program that prints the numbers from 1 to 100. But for multiples of three print “Fizz” instead of the number and for the multiples of five print “Buzz”. For numbers which are multiples of both three and five print “FizzBuzz”.”
The challenge is quite straight forward, but not necessarily easy to do on a white board during an interview, with stress and all that. I have two “solutions” to the problem below, both are quite dirty and quick but they work. I must admit to not solving them entirely by myself, especially not the second one as I learned a new function there. The primary reason for not getting #1 right initially is that the syntax of python changed between version 2.x (which I used previously) and 3.x (Which currently have installed). I could not figure out why it gave me syntax error on Print ‘bleh’ in 3.x. Regardless, below is my initial dirty attempt, it is very simple but reasonably effective. This is how I would solve in, or something along those lines, if I were to work without the help of the internet.
As you can see it uses a simple if/else script and add a count each time it goes through one of the if statements. Inefficient use of space but it works and is a half decent first attempt I guess.
My second attempt is more sophisticated, it uses the range/xrange function of python, and I admittedly more or less… stole/borrowed it off StackExchange. I hadn’t heard of that function previously so already I did learn something new.
Once again, the code is hardly efficient but it is a start and slightly less messy than the first attempt. Python is a rather nice language to learn as it, seems to me, rather straight forward compared to other languages. Time permitting I will attempt to read a novice level of proficiency. It is useful to be able to at least hack together some dirty code when in need. If nothing else it enables me to automate some tasks I otherwise would have to do by hand. I am also keen on learning a bit more SQL, which would be immensely useful going forward.
Not to mention, being proficient at programming is a big boon in today’s job market. I am FAR off being comfortable with python or programming in general but it is a step in the right direction.
Did you find this post interesting, illuminating, controversial or dumb? Leave a comment below or send me a tweet (@Chronoo). You can also subscribe to receive updates about new blog post in the sidebar on the right!