Python Interview Question FizzBuzz

preview_player
Показать описание
Рекомендации по теме
Комментарии
Автор

values = {
3:"Fizz",
5:"Buzz"
}

for i in range(1, 100):
string = ""
for k in values:
if i % k == 0:
string += values[k]
if string == "":
string = i
print string




if you require any expansion of modification of the strings/values required, this is much better, and only requires 1 line change and the algorithm itself would never change (except maybe the range if you had to change that) and remains readable after any number of changes to the fizz/buzz requirements

_Aarius_
Автор

very helpful video!
but what if we want to write a function called fb(), put this fb() in a 'fizz.py' file, import this 'fizz.py' in to the interactive mode of the interpreter by import fizz like a module and then call the fb() by fizz.fb(15) so the output that fizz.fb(15) will return will be not a simple for-loop iteration, but a python-list data type like this:
>>> fizz.fb(15)
[1, 2, 'fizz', 4, 'buzz', 'fizz', 7, 8, 'fizz', 'buzz', 11, 'fizz', 13, 14, 'fizzbuzz']

how the fb() function should look like in the 'fizz.py' file?
may be something like:
def fb(n):
n = list(range(1, n + 1))
s = ['fizz' if cm % 3 == 0 else cm for cm in n]
return s

but this will return:
>>> fizz.fb(15)
[1, 2, 'fizz', 4, 5, 'fizz', 7, 8, 'fizz', 10, 11, 'fizz', 13, 14, 'fizz']
and this will be only a part of the solution.

sntw