Python Fizzbuzz problems with loop

不羁的心 提交于 2019-12-20 05:34:06

问题


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

回答1:


The first value it looks at is 1. Since 1%x is only 0 for an x of 1, it goes to the else and returns 1. And then it's done, because that's what return 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 those return statements with either append()s to a list (don't forget to return the resulting list) or print() calls.

Also, if you started with something like 3, your code would try to use replace on an integer, which is not something you can do with integers. You would get a traceback.




回答2:


The code is returning 1 because consider this list [1,2,3,4,5,6,7,8,9,10]. All three conditions will get false and the last else will return 1. If you want the answer, append them into list.

Something like this:

def fizzbuzz(intList):
    temp = []
    for n in intList:
        if n % 3 == 0 and n % 5 == 0:
            temp.append("Fizzbuzz")
        elif n % 3 == 0:
            temp.append("Fizz")
        elif n % 5 == 0:
            temp.append("Buzz")
        else:
            temp.append(n)
    return temp


print fizzbuzz(range(1,20))



回答3:


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

#!/usr/bin/python3

for i in range(1,100):
    msg = "Fizz" * bool(i%3==0)
    msg += "Buzz" * bool(i%5==0)
    if not msg:
        msg = i
    print(msg)



回答4:


My skills in python are fairly average but i love using dicitonaries. Here is the Fizz Buzz program using dictionaries.Without an if.

for data in range(1, 101):
    msg = [str((data % 3 == 0)), str((data % 5 == 0))]
    // msg returns a list with ['True' ,'False'] depending on the condition
    conveter = {"True False": "Fizz",
                "False True": "Buzz",
                "True True": "Fizz Buzz",
                "False False": data
            }
    val = conveter[" ".join(msg)]
    print(val)



回答5:


I just implemented FizzBuzz as

for n in range(1, 100):
    if n%15==0: print "FizzBuzz"
    elif n%5==0: print "Buzz"
    elif n%3==0: print "Fizz"
    else: print n

The best thing with it that

  • It works

  • It fits into a tweet, with a margin




回答6:


Years later, based on this...

FizzBuzz: For integers up to and including 100, prints FizzBuzz if the integer is divisible by 3 and 5 (15); Fizz if it's divisible by 3 (and not 5); Buzz if it's divisible by 5 (and not 3); and the integer otherwise.

def FizzBuzz():
    for i in range(1,101):
        print {
            3 : "Fizz",
            5 : "Buzz",
            15 : "FizzBuzz"}.get(15*(not i%15) or
                                 5*(not i%5 ) or
                                 3*(not i%3 ), '{}'.format(i))

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 to False. 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 multiply True 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




回答7:


how a python function should look like if we want to see the next result in the interactive mode of the python interpreter:

>>> fizz(15)
[ 1, 2, 'fizz', 4, 'buzz', 'fizz', 7, 8, 'fizz', 'buzz', 11, 'fizz', 13, 14, 'fizzbuzz' ]


来源:https://stackoverflow.com/questions/34101222/python-fizzbuzz-problems-with-loop

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