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”.

Thursday, February 9, 2012

Fizz 12 - A Snake, Hiding in the Whitespace (Python)

For this Fizz, I have decided to tackle one of the other preferred languages at Google: Python. Since there is enough to talk about with Python I decided to do a relatively straight port of the first FizzBuzz I posted.

for i in range(1, 101) :
    if i%15 == 0 :
     print "FizzBuzz"
    elif i%5 == 0 :
     print "Buzz"
    elif i%3 == 0 :
     print "Fizz"
    else :
     print i


Like most "scripting" languages there is not a whole lot of overhead and ceremony in this code sample.  Lots of items are implied via their absence.  The namespace has a nice default, the main procedure to call is simply the statements at the root of the parse tree.  And there is a large set of functions available in the default namespace.

Another unique feature of Python that is white space is significant.  Very significant.  There are no opening and closing braces to group the control structures.  You must indent deeper than that parent control structure and maintain that indentation for multiple statements as a part of that structure.  In essence, the "good practice" of indenting nested control structures is hard wired as a requirement into the grammar of the language.

But the most relevant part of Python in relation to the current subject of discussion is how it loops.  The calculations and decisions in this example are merely syntactical variations of what we have seen before.  Python lacks a three expression loop seen in braces-and-semi-colon languages.  Instead it relies on an "iterator" based loop where the decisions about what the next item is and deciding when to stop is encapsulated inside an object called an Iterator.  In this case, the range function returns an iterator that returns the numbers from one to one hundred in order.  Ignore the fact that the second argument in the function is actually greater than one hundred.  Software is rife with off by one errors.

On last point.  The indentations must be consistent within the control structure.  In other words if you start indenting four more spaces than you had before then each statement in the control structure must have the same amount of indentation.  Whether they be tabs or any number of spaces.  And you can even mix tabs and spaces, if you are consistent.  This example mixes tabs and spaces for the print statements.  So, applying the FizzBuzz hypothesis we can conclude that typical programmers can do indentation consistently.  The real question is if they will (and they won't because everyone has seen enough evidence to the contrary).

No comments:

Post a Comment