I saw a certain article and it seemed interesting, so I tried it.
Personally, the special part of the transition in the exception is the continuation of processing? I think that it is to throw away the part of and jump to the place except.
Specifically, it looks like the following.
try:
print(object() + 1)
except TypeError:
print("hai")
# hai
Continuation to ʻobject () + 1in normal processing? I can't skip the
print ()call that is. An exception is thrown if an error occurs. If there is a part to handle the exception (try-except), catch the exception thrown there. Because it is responsible for the mechanism, it is possible to skip the
print ()` call.
Also, it is not StopIteration of iterable object, but it stops when an exception occurs. By making such a specification, it seems that it can be used as a loop end condition.
Fortunately, the usual fizzbuzz is "1 ~ 100". Also, if 100 is a string and its length is taken, len ("100 ")
is 3, so you can throw an exception at the beginning of the 3rd digit. You can do this by creating a list (xs) of length 3 and doing it with xs [len (str (i))]
.
I thought it would be better to write it with some restrictions, but I couldn't come up with a particularly good one. It's uselessly recurring instead of looping.
import sys
xs = ["fizz", "", ""]
def g(i, x, out):
try:
return out((i % 5) or "buzz")
except TypeError:
try:
x = xs[i % 3] or (i % 5) / (i % 5) and i
return out(i, int(x), out)
except ValueError:
try:
x += g(i, x, lambda y: y)
except TypeError:
pass
except ZeroDivisionError:
x = "buzz"
out(i, x, out)
try:
g(1, None, lambda i, x, out: xs[len(str(i))][g(i + 1, sys.stdout.write("{}\n".format(x)), out)])
except IndexError:
pass
After that, it seems that it is okay to make fizzbuzz from the error message of exception handling, but I stopped it.
Recommended Posts