-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathfizzbuzz.py
More file actions
47 lines (39 loc) · 1.59 KB
/
fizzbuzz.py
File metadata and controls
47 lines (39 loc) · 1.59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#!/usr/bin/env python
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
class FizzBuzz():
"""FizzBuzz"""
def __init__(self, length=30, name=None):
self.length = length
with tf.name_scope(name):
self.array = tf.Variable([str(i) for i in range(1, length+1)], dtype=tf.string, trainable=False)
self.graph = tf.while_loop(self.cond, self.body, [1, self.array],
shape_invariants=[tf.TensorShape([]), tf.TensorShape(self.length)],
back_prop=False)
def run(self):
with tf.Session() as sess:
tf.global_variables_initializer().run()
return sess.run(self.graph)
def cond(self, i, _):
return (tf.less(i, self.length+1))
def body(self, i, _):
flow = tf.cond(
tf.logical_and( # tf.equal(tf.mod(i, 15), 0)
tf.equal(tf.mod(i, 3), 0),
tf.equal(tf.mod(i, 5), 0)),
lambda: tf.assign(self.array[i - 1], 'FizzBuzz'),
lambda: tf.cond(tf.equal(tf.mod(i, 3), 0),
lambda: tf.assign(self.array[i - 1], 'Fizz'),
lambda: tf.cond(tf.equal(tf.mod(i, 5), 0),
lambda: tf.assign(self.array[i - 1], 'Buzz'),
lambda: self.array
)
)
)
return (tf.add(i, 1), flow)
if __name__ == '__main__':
fizzbuzz = FizzBuzz(length=50)
ix, array = fizzbuzz.run()
print(array)