LoginSignup
19
12

More than 5 years have passed since last update.

「FizzBuzzを書いてください」「まずTensorFlowをインポートして・・・」を自分も書いてみた

Last updated at Posted at 2018-03-22

下のツイートとかで有名になったFizzBuzz-TensorFlowネタ。今日もちょっと見かけたので思いつきで書いてみた。

実装はたくさんあって「FizzBuzz TensorFlow」でウェブ検索すればたくさん出てきます。最適化器で機械学習として解くのが多いけれどTensorFlowは「数値微分による最適化可能な実行可能な計算グラフを作成するフレームワーク」であり、かつ論理演算のオペレーションも文字列操作のオペレーションも備えているため素直に実装できます。

「そこらへんのディープラーニングしかできないフレームワークとは違うのだよ!!!」

API調べながら思い出しながら10分位で書けました。素直なバージョンもウェブ検索で結構見つかりますがtf.caseとかtf.control_dependenciesあたりでイロイロ凝ったことできるというのは覚えておいてください。

import tensorflow as tf

a = tf.Variable(0, name='counter')

with tf.control_dependencies([tf.assign_add(a, 1)]):
    b = tf.case({
        tf.equal(tf.mod(a, 15), 0): lambda: tf.constant("FizzBuzz"),
        tf.equal(tf.mod(a, 3), 0): lambda: tf.constant("Fizz"),
        tf.equal(tf.mod(a, 5), 0): lambda: tf.constant("Buzz"),
        }, default=lambda: tf.as_string(a))

sess = tf.Session()
sess.run(tf.global_variables_initializer())

for i in range(100):
    print(sess.run(b).decode())
19
12
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
19
12