I am getting "n" which is int from the outside of the function. I need to first create a list then replace every number that that is divisible by 3 with "fizz" if it's by 5 with "buzz" if both 5 and 3 then "fizzbuzz"
Like so;
given n is 3 => answer = [1, 2, "Fizz"]
given n is 5 => answer = [1, 2, "Fizz", 4, "Buzz"]
You get the idea...
The problem I ran into is when use "if" I can replace the 3 with "Fizz" but it becomes this: answer =[1, 2, "Fizz", 4, 5]
If I use another "if" I get, typeerror: not all arguments converted during string formatting, because "Buzz if" (the if that checks answer[i] % 5 == 0) can't compare a int to string.
So I thought if I can learn the indexes of all fizz, buzz, and fizzbuzz
I can replace them like line 6 to line 8. My pic here
Could I use "if" to learn index?
CodePudding user response:
Usually in the FizzBuzz practice you're given a list, here you're trying to generate a list that goes up to what I assume would be the user's input.
so what you could do is first generate the list of numbers using list compression.
def fizzbuzz(n):
answer = [i for i in range(n)]
After that you can check your conditions using a for loop that iterates through each item in the list and rather than using .append and .pop functions, you can simply reassign the value of the variable.
i.e.
def fizzbuzz(n):
answer = [i for i in range(n)]
for j in answer:
if j % 3 == 0:
j = "Fizz"
and add the rest of the conditions
CodePudding user response:
You can just do this:
def fizzbuzz:
result = []
for i in range(n):
if(n % 15 == 0):
result.append('fizzbuzz')
else if (n % 5 == 0):
result.append('buzz'):
else if (n % 3 == 0):
result.append('fizz'):
else:
result.append(i)
return result
Don't forget about you need check divisible by 15 before you do this by 3 and 5