-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path0412_fizz_buzz.py
More file actions
96 lines (77 loc) · 2.07 KB
/
0412_fizz_buzz.py
File metadata and controls
96 lines (77 loc) · 2.07 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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
#------------------------------------------------------------------------------
# Question:
#------------------------------------------------------------------------------
# tags:
'''
Write a program that outputs the string representation of numbers from 1 to n.
But for multiples of three it should output “Fizz” instead of the number and
for the multiples of five output “Buzz”. For numbers which are multiples of
both three and five output “FizzBuzz”.
Example:
n = 15,
Return:
[
"1",
"2",
"Fizz",
"4",
"Buzz",
"Fizz",
"7",
"8",
"Fizz",
"Buzz",
"11",
"Fizz",
"13",
"14",
"FizzBuzz"
]
'''
#------------------------------------------------------------------------------
# Solutions
#------------------------------------------------------------------------------
from typing import *
class Solution:
'''
Time:
Space:
'''
def fizzBuzz(self, n: int) -> List[str]:
def getfizzBuzz(x):
result = ""
if x % 3 == 0:
result += "Fizz"
if x % 5 == 0:
result += "Buzz"
return result
return [
getfizzBuzz(x) if x % 3 == 0 or x % 5 == 0 else str(x)
for x in range(1, n + 1)
]
class Solution2:
'''
Time:
Space:
'''
def fizzBuzz(self, n: int) -> List[str]:
return [
"Fizz" * (not i % 3) + "Buzz" * (not i % 5) or str(i)
for i in range(1, n + 1)
]
#------------------------------------------------------------------------------
# Tests
#------------------------------------------------------------------------------
import unittest
class TestSolution(unittest.TestCase):
def test_simple(self):
result = [
"1", "2", "Fizz", "4", "Buzz", "Fizz", "7", "8", "Fizz", "Buzz",
"11", "Fizz", "13", "14", "FizzBuzz"
]
n = 15
s = Solution()
self.assertEqual(s.fizzBuzz(n), result)
s = Solution2()
self.assertEqual(s.fizzBuzz(n), result)
unittest.main(verbosity=2)