Trying to turn fizzbuzz into a function in python 3 - python

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))

Shorter yet:
for n in range(100):
print("Fizz"*(not n % 3) + "Buzz"*(not n % 5) or n)
Yes, but why?
To understand this, let's look at the parts separately.
"Fizz"*(not n % 3)
In Python, we can "multiply" strings, so "a"*3 would result in "aaa". You can also multiply a string with a boolean: "a" * True is "a", whereas "a" * False is an empty string, "". That's what's happening to our "Fizz" here. When n % 3 == 0 (ie. n is 3, 6, 9, ...), then not n % 3 will be the same as not 0, which is True. Conversely, when n is 1, 2, 4, 5, 7, ... then n % 3 will be either 1 or 2, and not n % 3 will be false. In Other words, whenever n is divisible by 3, the term "Fizz"*(not n % 3) will multiply the string "Fizz" by True, and when it's not, it will multiply by False, resulting in an empty string.
The same logic applies to the next part, "Buzz"*(not n % 5). It'll give us an empty string when n is not divisible by 5, and the string "Buzz" when it is.
Now we're adding those two things together:
"Fizz"*(not n % 3) + "Buzz"*(not n % 5)
When n is neither divisible by 3 nor 5, this will be adding two empty strings together (ie. "" + ""), which will of course give us another empty string. In that case, the whole print statement reads print("" or n). Since an empty string is False-y, it will print our number n. If n is divisible by 3 (but not 5), this would be print("Fizz" or n), and since "Fizz" is Truthy, it will just print that and omit the number.
Bonus points
Or, if you really want to impress your interviewer,
for n in range(100):
print("FizzBuzz"[n%-3&4:12&8-(n%-5&4)] or n)

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.

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

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))

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)

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)))

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'

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']))

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)

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())

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".

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))

def fizzBuzz(n):
for x in range(1, n + 1):
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)
print(fizzBuzz(50))

Related

I am writing a program for a sample test at hackerRank but my loop is not working or i must say i am receiving only one output

Here is the code
def fizzBuzz(n):
n = list(range(1,n+1))
for numbers in n:
m3 = numbers / 3
m5 = numbers / 5
if type(m3) == int and type(m5) == int:
return "FizzBuzz"
elif type(m3) == int and type(m5) == float:
return "Fizz"
elif type(m3) == float and type(m5) == int:
return "Buzz"
else:
return numbers
challenge = fizzBuzz(5)
print(challenge)
I think the function should iterate over n times but I am getting only one output. Why is it so?
If you want to get all the output according to the list(range(1, n+1)) then use yield instead of return.
def fizzBuzz(n):
n = list(range(1, n+1))
for numbers in n:
m3 = numbers / 3
m5 = numbers / 5
if numbers % 3 == 0 and numbers % 5 == 0:
yield "FizzBuzz"
elif numbers % 3 == 0:
yield "Fizz"
elif numbers % 5 == 0:
yield "Buzz"
else:
yield numbers
challenge = list(fizzBuzz(5))
print(challenge)
Or you can initialize a list and append to the list then return
def fizzBuzz(n):
n = list(range(1, n + 1))
ls = []
for numbers in n:
m3 = numbers / 3
m5 = numbers / 5
if numbers % 3 == 0 and numbers % 5 == 0:
ls.append("FizzBuzz")
elif numbers % 3 == 0:
ls.append("Fizz")
elif numbers % 5 == 0:
ls.append("Buzz")
else:
ls.append(numbers)
return ls
challenge = fizzBuzz(5)
print(challenge)
Change your return statement to print statement or try this solution
def fizzBuzz(n):
for num in range(1, n+1):
if (num%3 == 0):
print('Fizz')
elif (num%5 == 0):
print('Buzz')
elif (num%3 == 0) and (num%5 == 0):
print('FizzBuzz')
else:
print(num)
challenge = fizzBuzz(5)
print(challenge)
When you divide any integer number by the '/' operator you always have the type float, even when division is an int. Test for yourself: type(2/2) returns float.
To check wheter N can be divided by M, it's usually better to test modulo N%M==0.
You can try this:
def fizz_buzz(n):
for i in range(1, n + 1):
if i % 3 == 0 and i % 5 == 0:
print('FizzBuzz')
elif i % 3 == 0:
print('Fizz')
elif i % 5 == 0:
print('Buzz')
else:
print(i)

Create a list of numbers dividable by certain numbers by using the command « filter() »

I’m on Python) I have to use filter() to create a list of all numbers from 1 to 100 (inclusive) that are dividable by 7, 9 and 42. I wrote this code, however, when I start it, it does not give me the right solutions. Do you know where the problem is ?
listnumbers = []
for x in range (1, 101):
x = str(x)
listnumbers.append(x)
print (listnumbers)
def dividable(k):
for t in k:
if int(t) % 7 == 0:
return True
if int(t) % 9 == 0:
return True
if int(t) % 42 == 0:
return True
else:
return False
return dividable
s2u = list(filter(dividable, listnumbers))
for q in s2u:
print(q)
According to your problem statement the number should be divisible by 7 and 9 and 42.
listnumbers = list(range(1,101))
def dividable(k):
if k % 7 == 0 and k % 9 == 0 and k % 42 == 0:
return True
else:
return False
ans = list(filter(dividable, listnumbers))
print(ans)
Just eyeballing your code, I think dividable(k) is not written correctly. Update to :
def dividable(k):
n = int(k)
return n % 7 == 0 or n % 9 == 0 or n % 42 == 0:
Why was there a for look declared in this method? And why was it returning the function at the end if it passed through the rest of the conditions?

Fizzbuzz Challenge in Twilio quest

I recently downloaded Twilio quest and I love it! However, I'm stuck at one of the entry-level Python challenges. It should be fairly easy to solve, but somehow I can not seem to work out the error here. Can anyone look through my code and find the obvious mistake which I clearly cannot?
import sys
inputs = sys.argv
inputs.pop(0)
for i in inputs:
print(i)
n = int(i)
for x in range(1,n+1):
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)
The challenge is to solve the fizzbuzz challenge, with multiple numbers as input. Error yields:
"We passed your script a number that was divisible by both 3 and 5, and expected you to print fizzbuzz, but instead you printed -3000.
So the input was -3000, and should pass by my first test, as it is indeed divisible by both 3 and 5. I can not seem to work out why the input -3000 would jump to the "else"-part of my for-loop.
If the input is just a number, there is no need of the for loop.
The logic is correct.
One fix can be:
import sys
inputs = int(sys.argv[-1])
x=inputs
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)
for a list of int in input:
import sys
inputs = [int(x) for x in sys.argv[1:]]
for x in inputs:
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)
Does the question ask you to iterate over each number from 1 to N for every input or does it ask you to only check for a single Number for an input?
If it's only a single element then I believe the following code will suffice:
import sys
inputs = sys.argv
inputs.pop(0)
for i in inputs:
# print(i)
n = int(i)
if n % 3 == 0 and n % 5 == 0:
print("fizzbuzz")
elif n % 3 == 0:
print("fizz")
elif n % 5 == 0:
print("buzz")
else:
print(n)

Bug with finding the largest number divisible by 3

def solution(l):
for x in (range(len(l))):
sum_l = sum(l)
num = l[x]
y = sum_l%3
l.sort()
if len(l) == 1 and l[0]%3 != 0:
return 0
elif ((num%3) == y and y != 0) :
l.remove(num)
l.sort(reverse=True)
strings = [str(number) for number in l]
l_string = ''.join(strings)
l_int = int(l_string)
return l_int
elif y == 0:
l.sort(reverse=True)
strings = [str(number) for number in l]
l_string = ''.join(strings)
l_int = int(l_string)
return l_int
else:
return 0
Here is the code. Basically, I am asked to find the largest number that can be made by the integers in the list divisible by 3. It passes all the test cases except one (blind case), and I have literally no idea what the issue is. I've tried every possible type of list, meaning, 1 digit, 2 digits, etc. The list can have numbers 0-9, with 1-9 numbers in it. Can I get some help as to what I might be missing?
Here is how you can find the largest number that can be made by the integers in the list divisible by 3:
from itertools import permutations
def solution(l):
p1 = [s for i in range(2,len(l)+1) for s in permutations(l,i)] # List of tuples with all possible combinations of numbers
p2 = [str(t) for t in p1 if not sum(t)%3] # List of tuples with elements adding together divisable by 3
return int(''.join([n for n in max(p2) if n.isdigit()])) # Return greatest tuple converted to number form
print(solution([4,6,9,1,3,3,2,4]))
Output:
9644331
The best way to find whether a number is divisible by 3 with only its digits is by adding up all the digits. If the answer is divisible by three, then so is any number made up of the combination of all the digits.
from itertools import permutations
def solution(l):
if not l:
return 0
if len(l) == 1 and l[0] % 3 == 0:
return l[0]
if len(l) == 1 and l[0] % 3 != 0:
return 0
p1 = [s for i in range(2, len(l) + 1) for s in
permutations(l, i)]
p2 = []
for each in p1:
num = ""
for i in each:
num += str(i)
if int(num) % 3 == 0:
p2.append(int(num))
x = sorted(list(set(p2)))
ans = 0
if len(x) != 0:
ans = max(x)
if ans != 0:
return ans
return 0
def cozum(list):
a=[]
for i in range(1,len(list)):
p = permutations(list,i)
for pe in p:
a.append(pe)
toplamlar=[ tup for tup in a if sum(tup)%3 == 0 ]
if toplamlar:
res = max([ int(''.join(map(str, sayi))) for sayi in toplamlar])
return res
else:
return "No number divisible by 3"

FizzzBuzz Python Work Through

Count up from 1. If the number is a multiple of 7 they say "zap" instead of the number. If the number has a digit of 3 in it they say "buzz" instead of the number, and if both things are true they say "zap buzz".
Devise a function zap_buzz that plays a turn of the game. Given a positive integer parameter it should either return that integer value if neither of the "zap"/"buzz" conditions hold. If some condition holds, it should return the string "zap", the string "buzz", or the string "zap buzz", whichever is appropriate. You are allowed to assume the parameter is less than 1000. As in the earlier exercises, please don't convert the integer to a string to determine its digits.
>>> zap_buzz(8)
8
>>> zap_buzz(14)
'zap'
>>> zap_buzz(13)
'buzz'
>>> zap_buzz(35)
'zap buzz'
^^^^^ is the prompt. I have gotten so far:
def zapbuzz(x):
x =0
if x % 3 == 0 and x % 7 == 0:
return str("ZapBuzz")
elif x % == 3 and x % 7 != 0 :
return str("Zap")
elif x % 3 != 0 and x % 7 == 0:
return str("Buzz")
else /* x % 3 >= 1 or x % 7 >= 1:
return x
****Please don't give me the answer, but a few good tips or maybe a "try thinking about XYZ/etc/whatevertip in a different way would be super awesome. Thank you!
okay I read through the comments, thank you for inspo!
I made the following changes:
n = input()
def ZapBuzz(n):
if n%7 == 0 & n%3 == 0:
return ("ZapBuzz")
elif n%7 == 0 & n%3 != 0:
return ("Zap")
elif n%7 != 0 & n%3 == 0:
return ("Buzz")
else:
return (n)
okay, just talked to a tutor.... I worked out the function, except the issue im having now is that when i input 1 into the function, the terminal spits out 'none'.
def zap_buzz(x):
i = 0
t = False
while i < 3:
if ((x // 10**i)%10) == 3:
t = True
i += 1
if t == True and x % 7 == 0:
return "zap buzz"
if x % 7 == 0:
return "zap"
if t == True:
return "buzz"

Categories