claims people take a lot of time to write a simple program like this:
"Write a program that prints the numbers from 1 to 100. But for
multiples of three print "Fizz" instead of the number and for the
multiples of five print "Buzz". For numbers which are multiples of
both three and five print "FizzBuzz".
for i in range(1,101):
if i%3 == 0 and i%5 != 0:
print "Fizz"
elif i%5 == 0 and i%3 != 0:
print "Buzz"
elif i%5 == 0 and i%3 == 0:
print "FizzBuzz"
else:
print i
is there a better way than my solution? is mine ok?
Try doing it using %3 and %5 only once each.
Looks OK to me.
A different version, and I test for multiples of 3 and 5 first:
map(lambda x: (not x%3 and not x%5 and "FizzBuzz") or (not x%3 and "Fizz")
or (not x%5 and "Buzz") or x, xrange(1,101))
--
Kam-Hung Soh <a href="http://kamhungsoh.com/blog">Software Salariman</a>
Define better.
>>> f = ['','','Fizz']*100
>>> b = ['','','','','Buzz']*100
>>> for i in xrange(1,100):
fb = f[i-1]+b[i-1]
if fb=='':
print i
else:
print fb
>> "Write a program that prints the numbers from 1 to 100. But for
>> multiples of three print "Fizz" instead of the number and for the
>> multiples of five print "Buzz". For numbers which are multiples of
>> both three and five print "FizzBuzz".
>>
>> for i in range(1,101):
>> if i%3 == 0 and i%5 != 0:
>> print "Fizz"
>> elif i%5 == 0 and i%3 != 0:
>> print "Buzz"
>> elif i%5 == 0 and i%3 == 0:
>> print "FizzBuzz"
>> else:
>> print i
>>
>>
>> is there a better way than my solution? is mine ok?
>
> Try doing it using %3 and %5 only once each.
for i in xrange(101):
print (("","Fizz")[i%3==0] + ("","Buzz")[i%5==0]) or str(i)
His is better though, since it's more obvious what's intended.
Here's one that's less opaque
for i in xrange(101):
s = ""
if i%3 == 0: s += "Fizz"
if i%5 == 0: s += "Buzz"
if s:
print s
else:
print i
There are dozens of other ways to do it.
--
Grant Edwards grante Yow! ... or were you
at driving the PONTIAC that
visi.com HONKED at me in MIAMI last
Tuesday?
['%s%s' % (not i%3 and 'Fizz' or '', not i%5 and 'Buzz' or '')
or str(i) for i in xrange(1, 101)]
-- Ivan
or, more correctly, if you actually need to "print":
sys.stdout.write('\n'.join('%s%s' %
(not i%3 and 'Fizz' or '', not i%5 aBuzz' or '')
or str(i)
for i in xrange(1, 101)))
-- Ivan
You seem to have an unfortunate fixation on 100. Consider changing the
above instances to 34, 20, and 101.
Ok, I agree with 101, but I wouldn't necessarily
say the others were unfortunate. You might be
surprised at how often such fixations discover
bugs, something that I have a gift for.
Is it correct? Did you get at it in less than 15 minutes? If so, then it's OK.
The original test was not "write the most convoluted algorithm you can think of", nor "write the best program to solve this". It was a *practical* test: if you can't get anything remotely working for such a simple problem in 15 minutes, we're not interested in your services.
(We used this question last year - some people gave a sensible answer in less than 5 minutes, but others did not even know how to start)
--
Gabriel Genellina
As a test, I would leave out the last sentence, and see how many
people (and how fast) figure out than a number can be multiple of
three _and_ five and that the requirement is somehow incomplete ...
Ciao
-----
FB
Let's not forget to generalise the problem and code it OOP-style :)
class FizzBuzzer(object):
def __init__(self, *fizzles):
self.fizzles = fizzles
def translate(self, n):
return ''.join(val for (p, val) in self.fizzles if not n%p) or
n
def range(self, start, stop=None, step=None):
if stop is None:
start, stop = 0, start
if step is None:
step = 1
for n in xrange(start, stop, step):
yield self.translate(n)
def __getitem__(self, obj):
if isinstance(obj, slice):
return self.range(obj.start, obj.stop, obj.step)
else:
return self.translate(obj)
# FizzBuzzer in action:
>>> fizzbuzz = FizzBuzzer((3, 'Fizz'), (5, 'Buzz'))
>>> for val in fizzbuzz[1:21]:
... print val
...
1 21 1
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
16
17
Fizz
19
Buzz
>>> abc = FizzBuzzer((2, 'Ah'), (3, 'Bee'), (5, 'Cee'))
>>> list(abc[25:35])
25 35 1
['Cee', 'Ah', 'Bee', 'Ah', 29, 'AhBeeCee', 31, 'Ah', 'Bee', 'Ah']
>>>
--
Arnaud
> 1
> 2
> Fizz
> 4
> Buzz
> Fizz
> 7
> 8
> Fizz
> Buzz
> 11
> Fizz
> 13
> 14
> FizzBuzz
> 16
> 17
> Fizz
> 19
> Buzz>>> abc = FizzBuzzer((2, 'Ah'), (3, 'Bee'), (5, 'Cee'))
> >>> list(abc[25:35])
>
> 25 35 1
^^^^^^^^^
Same
personally if you're just checking if a modulus result is 0 or not I
would rather do as it looks neat imho.
for i in xrange(1,101):
if not i % 3 and i % 5:
print 'Fizz'
elif i % 3 and not i % 5:
print 'Buzz'
elif not i % 3 and not i % 5:
>>> is there a better way than my solution? is mine ok?
>>
>> ['%s%s' % (not i%3 and 'Fizz' or '', not i%5 and 'Buzz' or '')
>> or str(i) for i in xrange(1, 101)]
>>
>> -- Ivan
>
> or, more correctly, if you actually need to "print":
>
> sys.stdout.write('\n'.join('%s%s' %
> (not i%3 and 'Fizz' or '', not i%5 aBuzz' or '')
> or str(i)
> for i in xrange(1, 101)))
I think the variant I came up with is a bit clearer:
for i in range(1,101):
print '%s%s' % ('' if i%3 else 'Fizz', '' if i%5 else 'Buzz') or i
More than a bit clearer, IMO. How about
print ('' if i%3 else 'Fizz') + ('' if i%5 else 'Buzz') or i
(or perhaps
print (('' if i%3 else 'Fizz') + ('' if i%5 else 'Buzz')) or i
to save looking up the precedence rules) ?
Stuff clarity! How about
for i in xrange(1, 101):
print 'FizzBuzz'[4*(i%3>0):4+4*(i%5<1)] or i
--
Arnaud
> --
> http://mail.python.org/mailman/listinfo/python-list
>
>
With no loop:
i=1
exec"print'FizzBuzz'[4*(i%3>0):4+4*(i%5<1)]or i;i+=1;"*100
max
> Ok, I agree with 101, but I wouldn't necessarily
> say the others were unfortunate. You might be
> surprised at how often such fixations discover
> bugs, something that I have a gift for.
The discovering, the making, or both? ;)
Tim Delaney
print 'Fizz'*(i%3<1)+'Buzz'*(i%5<1) or i
--
Paul Hankin
I like this, I can imagine plenty of use cases...
...in codegolf
--
Arnaud
I just can't believe someone applying for a programmer position cannot
provide a sensible anwser in 5 or less minutes.
> for i in xrange(1, 101):
> print 'Fizz'*(i%3<1)+'Buzz'*(i%5<1) or i
Doh! It never occured to me that 'string' * 0 == ''.
--
Grant Edwards grante Yow! An air of FRENCH FRIES
at permeates my nostrils!!
visi.com
Both, of course. The trick is to catch your errors before
anyone gets to see them. Then you get a reputation for being
clever.
>
> Tim Delaney
| (We used this question last year - some people gave a sensible answer
| in less | than 5 minutes, but others did not even know how to start)
Another approach I do not remember seeing here (under 10 minutes)
fb = ('FizzBuzz', None, None, 'Fizz', None, 'Buzz', 'Fizz',
None, None, 'Fizz', 'Buzz', None, 'Fizz', None, None)
for i in range(1,101): print(fb[i%15] or i) #3.0
> I just can't believe someone applying for a programmer position cannot
> provide a sensible anwser in 5 or less minutes.
You should join the recruitment and interview panel in your organization
to test your faith.
"#3.0" is rather cryptic. AFAIK that will work with *any* version of
Python up to 3.0. The "() after "print" are required in 3.0 and optional
in earlier versions.
Try taking a look at the level of discourse in the Google App Engine
group.
It's pretty clear that some - let's say "developers" rather than
"programmers" - developers are simply interested in acquiring usage
patterns for the particular language they're required to develop in.
Being able to extend existing patterns or create new solutions is
completely outside of their scope of interest or ability. My
'favourite' is the "how do I do x?", "can you show me a working
example?", "can you add your example to my code?" sequence, you see a
lot of that.
I'd honestly expect a lot of the current GAE group posters to fail the
FizzBuzz test, especially given that an amazing number of them seem to
be constantly griping about not being able to run production code on
what is currently only a preview framework.
- alex23
> On 12 mai, 09:00, "Gabriel Genellina" <gagsl-...@yahoo.com.ar> wrote:
>> En Sat, 10 May 2008 22:12:37 -0300, globalrev <skanem...@yahoo.se>
>> escribió:
>>
>> > "Write a program that prints the numbers from 1 to 100. But for
>> > multiples of three print "Fizz" instead of the number and for the
>> > multiples of five print "Buzz". For numbers which are multiples of
>> > both three and five print "FizzBuzz".
>>
>> (We used this question last year - some people gave a sensible answer
>> in less than 5 minutes, but others did not even know how to start)
>
> I just can't believe someone applying for a programmer position cannot
> provide a sensible anwser in 5 or less minutes.
For some people, "program" == "form with buttons", excluding all else.
Maybe it's an education problem - "programming in XXX" courses usually
focus on the XXX language itself, assuming (sometimes wrongly) that the
student has a "general programming" background. Worse, I've seen a book on
VB.net (and I think it's not the only one) that is more focused on "how to
use Visual Studio" than teaching the language itself, so it's not
surprising that some people may consider "what's the shortcut to [do some
visual task]" an important "programming skill".
So I think the FizzBuzz problem is a good test to filter out candidates
based on (lack of) practical programming skills. But I don't like that it
is still slightly math-biased (our version said: if multiple of 7 OR ends
in 7 -> replace with the word "Domingo"). I probably would not reject an
answer like this:
for n in range(1,100):
if multiple_of_7(n) or ends_with_7(n): print "Domingo"
else: print n
even if multiple_of_7 or ends_with_7 are incorrect or have some comment
like "I don't remember how to check this". The overall structure is OK,
the guy has decomposed the problem into two smaller subproblems, now it's
time to ask a domain expert about the details... :)
But the poor guy doesn't know that; he's under a lot of stress, nervous,
only has a few minutes remaining and surely thinks "I *have* to write this
in full else I won't get the job!"
I would like to write a similar problem without this non-programming
distracting issues (that is, a problem simple enough to be answered in a
few minutes, that requires only programming skills to be solved, and
leaving out any domain-specific knowledge).
--
Gabriel Genellina
I've done some recruitment - for a programmer position - in my previous
shop , and none of the guys that we interwieved were *that* bad.
Another reason not to like the FizzBuzz example is that it's quite
closely balanced between two reasonable approaches (whether to just
special-case multiples of 15 and say 'FizzBuzz', or whether to somehow
add the Fizz and the Buzz together in that case). The interviewee might
reasonably guess that this distinction is what's being tested, and get
unnecessarily stressed about it.
-M-
For such a trivial problem, fifteen minutes is more than enough to
present alternative answers. Perhaps the intention is to weed out those
who do become unnecessarily stressed in such circumstances. Employers
like to play tricks to see how interviewees respond e.g. hand over two
pages of a listing of code in language X, announce that there are 10
syntax errors, and ask the interviewee to find and circle all the syntax
errors. Correct answer: 11 circles.
They get away with that?
The one time I was asked to compose a (hardware) test was
because some interviewee threated to sue claiming
discrimination. So I was asked to make an absolutely
trick-free test.
Such as what's the voltage at point A?
+5v
|
220 ohm
|
+-- A
|
330 ohm
|
ground
Would you be surprised at how many applicants couldn't
figure that out because they forgot to bring their
calculator?
Sure, I had a page from a schematic, but only to ask
how one of the shown T-flip-flops worked.
One female interviewee took one glance at the schematic
and said, "Oh, it's a parity generator."
She got hired.
I'm surprised anyone has to resort to tricks.
> As a test, I would leave out the last sentence, and see how many
> people (and how fast) figure out than a number can be multiple of
> three _and_ five and that the requirement is somehow incomplete ...
Actually, if you leave off the last sentence, what the program should
do when it encounters a multiple of 15 is print "Fizz" and print
"Buzz", in some order, because all multiples of 15 are multiples of 3
and 5. The only difference is, if you don't specify to print
"FizzBuzz" for a multiple of 15, it's perfectly legal to print
"BuzzFizz". :-)
On the other hand, asking for clarification regarding multiples of 15
at least shows the applicant is thinking.
> Such as what's the voltage at point A?
>
> +5v
> |
> 220 ohm
> |
> +-- A
> |
> 330 ohm
> |
> ground
>
> Would you be surprised at how many applicants couldn't
> figure that out because they forgot to bring their
> calculator?
<OT>
Just a few hours ago I was helping a high school boy (senior) with some
chemistry homework. He actually had to use a calculator to evaluate
120*1/1 (and didn't even noticed he got the "same" number until I told
him!)
I hope he'll pass his test tomorrow...
</OT>
--
Gabriel Genellina
Your example is comprehensive compared to many other suggestions which
is an advantage IMO. I minimised it further
for i in range(start, stop, step):
if not i%15:
print "FizzBuzz"
elif not i%3:
print "Fizz"
elif not i%5:
print "Buzz"
else:
print i
Best regards
Wolfgang
This one eliminates the modulo operation.
dyn= list( xrange( 1, 101 ) )
for i in xrange( 1, len( dyn ), 3 ):
dyn[ i ]= ''
for i in xrange( 1, len( dyn ), 5 ):
dyn[ i ]= ''
for i in xrange( 1, len( dyn ), 3 ):
dyn[ i ]+= 'Fizz'
for i in xrange( 1, len( dyn ), 5 ):
dyn[ i ]+= 'Buzz'
for d in dyn:
print d
Can we compare?
On Tue, May 20, 2008 at 4:46 PM, Sells, Fred
<fred....@adventistcare.org> wrote:
> or
> for i in range(1,100):
> print ('fizz','','')[i%3] + ('buzz','','','','')[i%5] or i
>
>> >
>> > "Write a program that prints the numbers from 1 to 100. But for
>> > multiples of three print "Fizz" instead of the number and for the
>> > multiples of five print "Buzz". For numbers which are multiples of
>> > both three and five print "FizzBuzz".
>> >
>> > for i in range(1,101):
>> > if i%3 == 0 and i%5 != 0:
>> > print "Fizz"
>> > elif i%5 == 0 and i%3 != 0:
>> > print "Buzz"
>> > elif i%5 == 0 and i%3 == 0:
>> > print "FizzBuzz"
>> > else:
>> > print i
>> >
>> >
>> > is there a better way than my solution? is mine ok?
>>
>>
for i in range(1, 101):
print 'fizz' * (not i % 3) + 'buzz' * (not i % 5) or i
Tobiah
>> for i in range(1,100):
>> print ('fizz','','')[i%3] + ('buzz','','','','')[i%5] or i
>>
>>>> "Write a program that prints the numbers from 1 to 100. But for
>>>> multiples of three print "Fizz" instead of the number and for the
>>>> multiples of five print "Buzz". For numbers which are multiples of
>>>> both three and five print "FizzBuzz".
>>>>
>>>> for i in range(1,101):
>>>> if i%3 == 0 and i%5 != 0:
>>>> print "Fizz"
>>>> elif i%5 == 0 and i%3 != 0:
>>>> print "Buzz"
>>>> elif i%5 == 0 and i%3 == 0:
>>>> print "FizzBuzz"
>>>> else:
>>>> print i
>>>>
>>>>
>>>> is there a better way than my solution? is mine ok?
>>>
>> --
>> http://mail.python.org/mailman/listinfo/python-list
>>
>
>
>
** Posted from http://www.teranews.com **
for i in range(1, 101):
print 'fizz' * (not i % 3) + 'buzz' * (not i % 5) or i
Tobiah