FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
python-algorithms/algorithms/strings/fizzbuzz.py at master · plumnx/python-algorithms · GitHub
plumnx
/
python-algorithms
Public
forked from
keon/algorithms
Notifications
You must be signed in to change notification settings
Fork
0
Star
0
Code
Pull requests
0
Actions
Projects
Security and quality
0
Insights
Additional navigation options
Code
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
python-algorithms
/
algorithms
/
strings
/
fizzbuzz.py
Copy path
More file actions
More file actions
Latest commit
History
History
History
55 lines (44 loc) · 1.36 KB
Breadcrumbs
python-algorithms
/
algorithms
/
strings
/
fizzbuzz.py
Copy path
File metadata and controls
55 lines (44 loc) · 1.36 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
"""
Write a function that returns an array containing the numbers from 1 to N,
where N is the parametered value. N will never be less than 1.
Replace certain values however if any of the following conditions are met:
If the value is a multiple of 3: use the value 'Fizz' instead
If the value is a multiple of 5: use the value 'Buzz' instead
If the value is a multiple of 3 & 5: use the value 'FizzBuzz' instead
"""
"""
There is no fancy algorithm to solve fizz buzz.
Iterate from 1 through n
Use the mod operator to determine if the current iteration is divisible by:
3 and 5 -> 'FizzBuzz'
3 -> 'Fizz'
5 -> 'Buzz'
else -> string of current iteration
return the results
Complexity:
Time: O(n)
Space: O(n)
"""
def
fizzbuzz
(
n
):
# Validate the input
if
n
<
1
:
raise
ValueError
(
'n cannot be less than one'
)
if
n
is
None
:
raise
TypeError
(
'n cannot be None'
)
result
=
[]
for
i
in
range
(
1
,
n
+
1
):
if
i
%
3
==
0
and
i
%
5
==
0
:
result
.
append
(
'FizzBuzz'
)
elif
i
%
3
==
0
:
result
.
append
(
'Fizz'
)
elif
i
%
5
==
0
:
result
.
append
(
'Buzz'
)
else
:
result
.
append
(
i
)
return
result
# Alternative solution
def
fizzbuzz_with_helper_func
(
n
):
return
[
fb
(
m
)
for
m
in
range
(
1
,
n
+
1
)]
def
fb
(
m
):
r
=
(
m
%
3
==
0
)
*
"Fizz"
+
(
m
%
5
==
0
)
*
"Buzz"
return
r
if
r
!=
""
else
m
Back
|
FazBrowse Home
|
New Git URL