Trying to turn fizzbuzz into a function in python 3

安稳与你 提交于 2021-02-04 20:40:39

问题


I have only just started to learn python as my first language and whilst i worked out the code for fizzbuzz, i cannot for the life of me get it to do the items below. I also want it to print horizontally instead of vertically. Any help would be great (heads spinning). Create a function which does this. For example

fizzbuzz(20) 

would print 1,2,fizz,4,buzz,fizz,7,8,fizz,buzz,11,fizz,13,14,fizzbuzz,16,17,fizz,19,buzz

def fizzbuzz(n):

    for x in range (101):
        if x%3==0 and x%5==0:
            print("fizz buzz")
        elif x%3==0:
            print('fizz')
        elif x%5==0:
            print('buzz')
        else:
            print (x)    

def main():
  print(fizzbuzz(20))

回答1:


Collect the items into a list. Then print the list at the end of function. You can join the items together with a comma in between using ', '.join(...).

def fizzbuzz(n):
    result = []
    for x in range(1, n+1):
        if x % 3 == 0 and x % 5 == 0:
            result.append("fizz buzz")
        elif x % 3 == 0:
            result.append('fizz')
        elif x % 5 == 0:
            result.append('buzz')
        else:
            result.append(str(x))
    return result

def main():
    print(', '.join(fizzbuzz(20)))

main()

It's good to also know that print(..., end=', ') would print "horizontally" with a comma and space at the end, and this would almost solve your problem except that the very last item would also have a comma and space at the end, which is not what you desire.


It's usually a good idea to (1) separate printing from computing, (2) make functions reusable. You often want to compute more frequently than print. In the future you may wish to pass the computation on to some other function before you print. So functions that immediate print are not as useful. So I recommend taking the print statements out of fizzbuzz.

You could return the string ', '.join(result), but how useful would that be? The list result might be (in the future) more useful for further processing, so I chose to return result. The printing I left for the main function.




回答2:


Shorter yet:

for n in range(100):
    print "Fizz"*(not n % 3) + "Buzz"*(not n % 5) or n

Or, if you want to impress your interviewer,

for n in range(100):
    print 'FizzBuzz'[n%-3&4:12&8-(n%-5&4)] or n



回答3:


Slightly more elegant

def fizzbuzz(n):
    for x in range(1,n+1):
        if not x % 15:
            yield 'fizz buzz'
        elif not x % 3:
            yield 'fizz'
        elif not x % 5:
            yield 'buzz'
        else:
            yield x

if __name__ == "__main__":
    print ','.join(fizzbuzz(20))



回答4:


def fizzbuzz(numbers, fizz, buzz):
    x = ['Fizzbuzz' if x % fizz == 0 and x % buzz == 0 else 'Fizz' if x % fizz == 0 else 'Buzz' if x % buzz == 0 else x for x in numbers]
    return x



回答5:


I'm a novice coder so some of the answers I did not understand or it did not seems to directly apply to my problem. This answer incorporates Fizz_Buzz as a variable and the range of x is determined by the user. I looked at the above solutions and came up with this:

def Fizz_Buzz(x): 
     for x in range (0,x):      
        if x % 3 == 0 and x % 5 == 0:           
            print('FizzBuzz')       
        elif x % 3 == 0:            
            print('Fizz')       
        elif x % 5 == 0:            
            print ('Buzz')      
        else:           
            print (x)



回答6:


You can add end=', ' to print in order to print on the same line, with whatever character you want separating the values.

class FizzBuzz:
    @staticmethod
    def fizz_buzz(n):
        if n % 15 == 0:
            return 'FizzBuzz'
        elif n % 3 == 0:
            return 'Fizz'
        elif n % 5 == 0:
            return 'Buzz'
        else:
            return str(n)

    def __str__(self, rng):
        [print(self.fizz_buzz(n), end=', ') for n in range(1, rng + 1)]

But it leaves , at the end. Instead:

    def __str__(self, rng):
        print(', '.join(self.fizz_buzz(n) for n in range(1, rng + 1)))



回答7:


i made a fizzbuzz that works for any number and words, so you can do fizzbuzzfuzz if you wanted. i made it in 6 lines (7 if you count the line that runs through the fizzfuzz)

def f(n:int,m:list,w:list):
    s=''
    for x in m:
        if n%x==0:    s+=w[m.index(x)] 
    if s=='':  s=n
    return s
for i in range(1, 100 +1):  print(f(i,[3,5],['Fizz','Buzz']))



回答8:


def fizzbuzz(num):
    if x % 3 == 0 and x % 5 == 0:
    return "Fizz Buzz"
    elif x % 3 == 0:
        return "Fizz"
    elif x % 5 == 0:
        return "Buzz"
    else:
        return x    

MAXNUM = 100
for x in range (MAXNUM):
    print fizzbuzz(x)



回答9:


I've found the following works well (Python 3):

def fizzbuzz():
for i in range(1,101):
    print("Fizz"*(i%3==0)+"Buzz"*(i%5==0) or i)

print (fizzbuzz())



回答10:


Here's a fun one (obviously not the best for readability, but still kinda fun to think about list comprehensions):

def fizzBuzz():
    print(", ".join(["FizzBuzz" if x%15==0 else "Fizz" if x%3 == 0 else "Buzz" if x%5==0 else str(x) for x in range(1,101)]))

Don't forget, 3 and 5 are coprime! So you can check x % 15 instead of (x % 3 and x % 5) for "FizzBuzz".




回答11:


Yet another one with list comprehension and Python3

def is_mod_zero(num, *div):
    return not [d for d in div if num % d is not 0]

def fizz_buzz(num):
    if is_mod_zero(num, 3, 5):
        return 'FizzBuzz'
    if is_mod_zero(num, 3):
        return 'Fizz'
    if is_mod_zero(num, 5):
        return 'Buzz'
    return num

if __name__ == "__main__":
    for i in range(100):
        print(fizz_buzz(i))



回答12:


one more :) just for fun :)

get_index = lambda i: bool(i%3)+2*bool(i%5) if i !=0 else 3
afb = lambda x: ('fizzbuzz','buzz', 'fizz', str(x))[get_index(x)]
fizzbuzz = lambda inpt: print(','.join([ afb(i) for i in inpt ]))
fizzbuzz(range(101))

'0,1,2,fizz,4,buzz,fizz,7,8,fizz,buzz,11,fizz,13,14,fizzbuzz,16,17,fizz,19,buzz,fizz,22,23,fizz,buzz,26,fizz,28,29,fizzbuzz,31,32,fizz,34,buzz,fizz,37,38,fizz,buzz,41,fizz,43,44,fizzbuzz,46,47,fizz,49,buzz,fizz,52,53,fizz,buzz,56,fizz,58,59,fizzbuzz,61,62,fizz,64,buzz,fizz,67,68,fizz,buzz,71,fizz,73,74,fizzbuzz,76,77,fizz,79,buzz,fizz,82,83,fizz,buzz,86,fizz,88,89,fizzbuzz,91,92,fizz,94,buzz,fizz,97,98,fizz,buzz'



来源:https://stackoverflow.com/questions/18427233/trying-to-turn-fizzbuzz-into-a-function-in-python-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!