I've searched for the answer for about an hour, and it seems most people have coded fizzbuzz a different way than myself.
However, having tried everything to figure out why this simple code will not work I'm getting extremely frustrated.
Can anyone point out the simple problem I'm sure I'm having? The code runs but it just returns the value 1.
def fizzbuzz(intList):
for n in intList:
if n % 3 == 0 and n % 5 == 0:
return n.replace(str(n),"Fizzbuzz")
elif n % 3 == 0:
return n.replace(str(n),"Fizz")
elif n % 5 == 0:
return n.replace(str(n),"Buzz")
else:
return n
Perhaps if you take a look at this code you will better understand yours. Although this is a completely different implementation of fizzbuzz in Python3
I just implemented FizzBuzz as
The best thing with it that
It works
It fits into a tweet, with a margin
The code is returning
1
because consider this list[1,2,3,4,5,6,7,8,9,10]
. All three conditions will getfalse
and the lastelse
will return1
. If you want the answer, append them into list.Something like this:
The first value it looks at is
1
. Since1%x
is only0
for anx
of1
, it goes to theelse
and returns1
. And then it's done, because that's whatreturn
does.That leads to the bigger problem, which is that you are starting a loop and then guaranteeing that you will leave that loop after only one iteration, because there's a
return
in every branch. You'll need to replace thosereturn
statements with eitherappend()
s to alist
(don't forget toreturn
the resultinglist
) orprint()
calls.Also, if you started with something like
3
, your code would try to usereplace
on an integer, which is not something you can do with integers. You would get a traceback.Years later, based on this...
The
.get()
method works wonders here.Operates as follows
For all integers from 1 to 100 (101 is NOT included),
print the value of the dictionary key that we call via get according to these rules.
"Get the first non-False item in the
get
call, or return the integer as a string."When checking for a
True
value, thus a value we can lookup, Python evaluates 0 toFalse
. If i mod 15 = 0, that's False, we would go to the next one.Therefore we
NOT
each of the 'mods' (aka remainder), so that if the mod == 0, which == False, we get a True statement. We multiplyTrue
by the dictionary key which returns the dictionary key (i.e.3*True == 3
)When the integer it not divisible by 3, 5 or 15, then we fall to the default clause of printing the int
'{}'.format(i)
just inserts i into that string - as a string.Some of the output
Fizz
79
Buzz
Fizz
82
83
Fizz
Buzz
86
Fizz
88
89
FizzBuzz
91
92
Fizz
94
Buzz
Fizz
97
98
Fizz
Buzz
My skills in python are fairly average but i love using dicitonaries. Here is the Fizz Buzz program using dictionaries.Without an if.