fizzbuzz in Ruby, Python, Perl, more

Recently, I ran into couple of articles on codinghorror.com  that covered interviews with programmers/ software engineers.  Many of the commentators answered the programming (fizzbuzz) question using their favorite computer language like VBA, Ruby, Perl, etc.  Since the post was no more allowing any new comments, I thought of posting them here on my blog itself.

fizzbuzz question: For all numbers between 1 and 100, print 'fizz' any number divisible by 3, 'buzz' for number divisible by 5 and 'fizzbuzz' for number divisible by both 3 & 5.

Article 1:  Why Can't Programmers.. Program?
Article 2: The Non-Programming Programmer



I have used 'map' function to solve it and mapping function provide nice way to work through lists. There are few other ways you can solve it as well including the ones already given in the original articles above.

Perl:
sub fb {
   if   ($_ % 15 == 0) { return "fizzbuzz\n" }
   elsif ($_ % 3 == 0) { return "fizz\n" }
   elsif ($_ % 5 == 0) { return "buzz\n" }
   return "$_\n";
}

print map {fb($_)} (1..100)

Ruby:
You can also use select method
(1..100).map { |n| if (n%15 == 0):   puts 'fizzbuzz'
                   elsif (n%5 == 0): puts 'buzz'
                   elsif (n%3 == 0): puts 'fizz'
                   elsif puts n
                   end
             }
puts "----------------------------"

(1..100).select { |n| if (n%15 == 0):   puts 'fizzbuzz'
                      elsif (n%5 == 0): puts 'buzz'
                      elsif (n%3 == 0): puts 'fizz'
                      elsif puts n
                      end
                }

Python:
def fizzbuzz(x):
    if  x%15 == 0: return 'fizzbuzz'
    elif x%3 == 0: return 'fizz'
    elif x%5 == 0: return 'buzz'
    return x

def p(x):
    print x

map(p, map(fizzbuzz, range(1,101)))



SQL (MySQL):
SELECT  n, 
    CASE 
        when n % 3 = 0 AND n % 5 = 0 then 'fizzbuzz' 
        when n % 5 = 0 then 'buzz' 
        when n % 3 = 0 then 'fizz' 
    END 
FROM
    ( SELECT @n := @n + 1 as n   
       FROM some_small_table   -- A table with more than 100 rows
          (SELECT @n := 0) x   -- Set variable to 0 in the begining
       LIMIT 100               -- Limit to 100 
    ) y;


Hope you enjoyed it.
Shiva

No comments:

Post a Comment