?

Log in

No account? Create an account

fizzbuzz

« previous entry | next entry »
May. 13th, 2007 | 11:29 pm

かなり出遅れた感があるし、もうすでにありそうだけど。まず Python で。

>>> def fizzbuzz(n):
...     """FizzBuzz test method.
...     >>> fizzbuzz(3)
...     'Fizz'
...     >>> fizzbuzz(4)
...     4
...     >>> fizzbuzz(5)
...     'Buzz'
...     >>> fizzbuzz(15)
...     'FizzBuzz'
...     """
...     return (n%15 == 0 and 'FizzBuzz' or n%3 == 0 and 'Fizz' or n%5 == 0 and 'Buzz' or n)
...
>>> [fizzbuzz(n) for n in range(1,100+1)]
[1, 2, 'Fizz', 4, 'Buzz', 'Fizz', 7, 8, 'Fizz', 'Buzz', 11, 'Fizz', 13, 14, 'FizzBuzz', 16, 17, 'Fizz', 19, 'Buzz', 'Fizz', 22, 23, 'Fizz', 'Buzz', 26, 'Fizz', 28, 29, 'FizzBuzz', 31, 32, 'Fizz', 34, 'Buzz', 'Fizz', 37, 38, 'Fizz', 'Buzz', 41, 'Fizz', 43, 44, 'FizzBuzz', 46, 47, 'Fizz', 49, 'Buzz', 'Fizz', 52, 53, 'Fizz', 'Buzz', 56, 'Fizz', 58, 59, 'FizzBuzz', 61, 62, 'Fizz', 64, 'Buzz', 'Fizz', 67, 68, 'Fizz', 'Buzz', 71, 'Fizz', 73, 74, 'FizzBuzz', 76, 77, 'Fizz', 79, 'Buzz', 'Fizz', 82, 83, 'Fizz', 'Buzz', 86, 'Fizz', 88, 89, 'FizzBuzz', 91, 92, 'Fizz', 94, 'Buzz', 'Fizz', 97, 98, 'Fizz', 'Buzz']
>>>

まだなさそうな XSLT; fizzbuzz.xsl:

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  version="1.0">
  <xsl:output method="text"/>
  <xsl:param name="start" select="1"/>
  <xsl:param name="end" select="100"/>
  <xsl:template match="/">
    <xsl:call-template name="fizzbuzz"/>
  </xsl:template>
  <xsl:template name="fizzbuzz">
    <xsl:param name="n" select="$start"/>
    <xsl:if test="$n &lt; $end + 1">
      <xsl:choose>
        <xsl:when test="($n mod 15) = 0">FizzBuzz </xsl:when>
        <xsl:when test="($n mod 3) = 0">Fizz </xsl:when>
        <xsl:when test="($n mod 5) = 0">Buzz </xsl:when>
        <xsl:otherwise><xsl:value-of select="concat($n, ' ')"/></xsl:otherwise>
      </xsl:choose>
      <xsl:call-template name="fizzbuzz">
        <xsl:with-param name="n" select="$n+1"/>
      </xsl:call-template>
    </xsl:if>
  </xsl:template>
</xsl:stylesheet>
<!-- vim: set sw=2 ts=2 et: -->

テスト:

$ echo '<fizzbuzz/>' > fizzbuzz.xml
$ xsltproc --param start 1 --param end 50 fizzbuzz.xsl fizzbuzz.xml

[追記] こちらも既にあった: Solving FizzBuzz in XSLT 1.0.

Link | Leave a comment |

Comments {0}