0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Python3 で FizzBuzz (sqllite3利用)

Last updated at Posted at 2019-01-19

なんか、急に「FizzBuzzを書け」という電波を受信したので。

python で書いてみました(ヲイ。

FizzBuzz01.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sqlite3


sql = '''
    SELECT
        CASE
            WHEN n % 3 = 0 AND n % 5 = 0
                THEN 'FizzBuzz'
            WHEN n % 3 = 0
                THEN 'Fizz'
            WHEN n % 5 = 0
                THEN 'Buzz'
            ELSE
                CAST(n AS TEXT)
        END
    FROM
        (
            SELECT
                    N1.column1*10 + N2.column1 + 1 AS n
                    -- ROW_NUMBER() OVER (ORDER BY column1) AS n
                FROM
                    (VALUES(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) N1
                    , (VALUES(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) N2
        ) N
;
'''

def main():
    with sqlite3.connect(':memory:') as conn:
        lines = conn.execute(sql)
    
    [print(l[0]) for l in lines]

if __name__ == '__main__':
    main()

ちなみに、動作テストは Python3.7.0 で行いました。
sqlite3.sqlite_version は '3.21.0' ですので
sqlite3 の version 3.25.0 から使える、ROW_NUMBER() 等の Window関数は使えませんでした。

追記:
Python に甘えて堕落していました。

FizzBuzz02.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sqlite3


sql = '''
    SELECT
        GROUP_CONCAT(
            CASE
                WHEN n % 3 = 0 AND n % 5 = 0
                    THEN 'FizzBuzz'
                WHEN n % 3 = 0
                    THEN 'Fizz'
                WHEN n % 5 = 0
                    THEN 'Buzz'
                ELSE
                    CAST(n AS TEXT)
            END,CHAR(13,10))
    FROM
        (
            SELECT
                    N1.column1*10 + N2.column1 + 1 AS n
                    -- ROW_NUMBER() OVER (ORDER BY column1) AS n
                FROM
                    (VALUES(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) N1
                    , (VALUES(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) N2
        ) N
;
'''

def main():
    with sqlite3.connect(':memory:') as conn:
        print(conn.execute(sql).fetchall()[0][0])

if __name__ == '__main__':
    main()
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?