Re: A style question
- From: nallen05@xxxxxxxxx
- Date: 28 Feb 2007 09:32:19 -0800
Rob Warnock wrote:
<job-271842874@xxxxxxxxxxxxxx> wrote:
+---------------
| Another friend of mine commenting on the same FizzBuzz thread supplied
| the following Python code. It certainly is concise:
|
| for i in xrange(1,101):
| print(str(i), "Fizz", "Buzz", "FizzBuzz")[(i%3==0)|(i%5==0)<<1]
|
| I thought about retrofitting my Ruby version as an exercise, but alas,
| Ruby doesn't allow shifting truth to the left :)
|
| Forgive my ignorance, but is anything like the boolean bit shifting
| technique used in the Python code above possible in Lisp? No big loss if
| it isn't, just curious.
+---------------
Well, sort of... ;-} ;-}
This one is both efficient -- *no* MOD calls at all! --
*and* so ugly only a parent could love it: ;-} ;-}
(defun fizz-buzz (n)
(loop for i from 1 to n
and three-p in '#3=(nil nil t . #3#)
and five-p in '#5=(nil nil nil nil t . #5#)
do (format t "~a~%" (cond
((and three-p five-p) "FizzBuzz")
(three-p "Fizz")
(five-p "Buzz")
(t i)))))
This is awsome, Rob ;-) But I can make one that's faster AND uglier!
(defmacro def-fizz-buzz ()
(let (l)
(do* ((i 1 (incf i))
(m3p (zerop (mod i 3))
(zerop (mod i 3)))
(m5p (zerop (mod i 5))
(zerop (mod i 5))))
((> i 15))
(setq l
(list* `(print ,(cond ((and m3p m5p) "FizzBuzz")
(m3p "Buzz")
(m5p "Fizz")
(t 'y)))
'(when (> y x) (return))
'(incf y)
l)))
`(defun fizz-buzz (x)
(let ((y 0))
(loop ,@(reverse l))))))
CL-USER> (macroexpand-1 '(def-fizz-buzz))
=>
(DEFUN FIZZ-BUZZ (X)
(LET ((Y 0))
(LOOP (INCF Y)
(WHEN (> Y X) (RETURN))
(PRINT Y)
(INCF Y)
(WHEN (> Y X) (RETURN))
(PRINT Y)
(INCF Y)
(WHEN (> Y X) (RETURN))
(PRINT "Buzz")
(INCF Y)
(WHEN (> Y X) (RETURN))
(PRINT Y)
(INCF Y)
(WHEN (> Y X) (RETURN))
(PRINT "Fizz")
(INCF Y)
(WHEN (> Y X) (RETURN))
(PRINT "Buzz")
(INCF Y)
(WHEN (> Y X) (RETURN))
(PRINT Y)
(INCF Y)
(WHEN (> Y X) (RETURN))
(PRINT Y)
(INCF Y)
(WHEN (> Y X) (RETURN))
(PRINT "Buzz")
(INCF Y)
(WHEN (> Y X) (RETURN))
(PRINT "Fizz")
(INCF Y)
(WHEN (> Y X) (RETURN))
(PRINT Y)
(INCF Y)
(WHEN (> Y X) (RETURN))
(PRINT "Buzz")
(INCF Y)
(WHEN (> Y X) (RETURN))
(PRINT Y)
(INCF Y)
(WHEN (> Y X) (RETURN))
(PRINT Y)
(INCF Y)
(WHEN (> Y X) (RETURN))
(PRINT "FizzBuzz"))))
.
- References:
- A style question
- From: job-271842874
- Re: A style question
- From: job-271842874
- Re: A style question
- From: Rob Warnock
- A style question
- Prev by Date: Re: -2 is not a real number?!?
- Next by Date: Re: A style question
- Previous by thread: Re: A style question
- Next by thread: Re: A style question
- Index(es):