Skip to content

412 fizz buzz

412. Fizz Buzz

题目: https://leetcode.com/problems/fizz-buzz/

难度: Easy

一行

class Solution(object):
    def fizzBuzz(self, n):
        """
        :type n: int
        :rtype: List[str]
        """
        return [(not i%3)*"Fizz" + (not i%5)*"Buzz" or str(i) for i in range(1, n+1)]

class Solution(object):
    def fizzBuzz(self, n):
        """
        :type n: int
        :rtype: List[str]
        """
        return [str(i) if (i%3!=0 and i%5!=0) else (('Fizz'*(i%3==0)) + ('Buzz'*(i%5==0))) for i in range(1,n+1)]

就是easy,不过可以参见这里,有一些讨论

http://codereview.stackexchange.com/questions/763/two-fizzbuzz-solutions

我觉得这里一个用yield的想法还蛮不错

# the fizbuz logic, returns an iterator object that
# calculates one value at a time, not all ot them at once
def fiz(numbers):
    for i in numbers:
        if i % 15 == 0:
            yield 'fizbuz'
        elif i % 5 == 0:
            yield 'buz'
        elif i % 3 == 0:
            yield 'fiz'
        else:
            yield str(i)

# xrange evaluates lazily, good for big numbers
# matches well with the lazy-eval generator function
numbers = xrange(1,2**20)

# this gets one number, turns that one number into fuz, repeat
print ' '.join(fiz(numbers))

# returns: 1 2 fiz 4 buz fiz [...] fiz 1048573 1048574 fizbuz
  • clearly separates fizbuz logic from concatenation
  • is as plain and readeable as possible
  • generator iterator does not keep all the array in memory
  • so that you can do it on arbitrary numbers (see Euler problem #10)

What I do not like in this solution is the three ifs, whereas the problem can be solved with two.

Answer: because yield is efficient when you do not want to keep big arrays in memory just to iterate through them. But this question is not about big arrays.


我们一直在努力

apachecn/AiLearning

【布客】中文翻译组