Immediately after the function definition, you can put something like '''foo bar buzz'''
in python to describe the function. This is called docstring
. doctest is talking about using this docstring
to test the operation of functions.
I have to write some function. I chose fizzbuzz
because it's too normal like factorial
. There is a binding called ʻone liner` in python, and I tried using the code here.
fizzbuzz.py
def fizzbuzz(n):
"""
This function returns a list whose elements are
converted into fizzbuzz form.
>>> fizzbuzz(10)
[1, 2, 'Fizz', 4, 'Buzz', 'Fizz', 7, 8, 'Fizz', 'Buzz']
>>> len(fizzbuzz(9))
9
>>> fizzbuzz(10) + 1
Traceback (most recent call last):
File "/Users/yourname/python/fizbuzz.py", line 32, in <module>
fizzbuzz(10) + 1
TypeError: can only concatenate list (not "int") to list
"""
for i in range(1,n+1): res.append("FizzBuzz"[(i**2)%3*4:8--(i**4)%5] or i)
return res
if __name__ == '__main__':
import doctest
doctest.testmod()
To explain a little, the character string "FizzBuzz" is cut and printed. The desired string is cut out by adjusting the number on the left and right separated by :
. in short
case(i):
i is[Multiple of 3]And[Multiple of 5]:
"FizzBuzz"[0:8]
i is[Multiple of 3]And[Not a multiple of 5]:
"FizzBuzz"[0:4]
i is[Not a multiple of 3]And[Multiple of 5]:
"FizzBuzz"[4:8]
i is[Not a multiple of 3]And[Not a multiple of 5]:
"FizzBuzz"[4:4] /* Empty String => None */
That is. To achieve this, prepare 0 for multiples of 3, 4
for others, 8 for multiples of 5, and 4
for others. Since it's a one-liner, I'm trying hard with the surplus, but I think it's okay to create a separate function.
By the way, I simulated it when I increased the value to be returned.
**********************************************************************
File "/Users/hiroberry/python/foo.py", line 8, in __main__.fizzbuzz
Failed example:
len(fizzbuzz(9))
Expected:
10
Got:
9
**********************************************************************
1 items had failures:
1 of 3 in __main__.fizzbuzz
***Test Failed*** 1 failures.
[Finished in 0.1s]
It's obvious at a glance. It would be too convenient.
I made a special example that doesn't work and tried it. Traceback The following statements don't seem to have to match exactly. Apparently, I'm only looking at the statement TypeError: can only ...
.
Recommended Posts