patternpythonMinor
"FIZZ BANG BUZZ!" 3,7,11 efficiency
Viewed 0 times
buzzfizzefficiencybang
Problem
I wrote a fizz buzz variation method in Python which prints "fizz", "bang", and "buzz" for 3, 7, and 11 respectively.
What can I do to increase the speed of this program? I know the modulus is quite expensive. Also maybe concatenating strings might not be needed as well.
def FizzBang():
string = ''
for n in range(1,101):
msg = ""
if not n % 3:
msg += "Fizz"
if not n % 7:
msg += "Bang"
if not n % 11:
msg += "Buzz"
print msg or str(n)What can I do to increase the speed of this program? I know the modulus is quite expensive. Also maybe concatenating strings might not be needed as well.
Solution
Indeed, addition is faster than modulo. This implementation runs about 33% faster than the original when counting up to 100. However, I expect that it wouldn't scale as well to larger limits due to its O(n) memory usage.
Also, according to PEP 8 conventions,
def fizz_bang(limit=100):
limit += 1
strings = [''] * limit
fbb = ((3, 'Fizz'), (7, 'Bang'), (11, 'Buzz'))
for stride, noise in fbb:
for n in range(0, limit, stride):
strings[n] += noise
for n in range(1, limit):
print strings[n] or nAlso, according to PEP 8 conventions,
FizzBang should be named fizz_bang instead.Code Snippets
def fizz_bang(limit=100):
limit += 1
strings = [''] * limit
fbb = ((3, 'Fizz'), (7, 'Bang'), (11, 'Buzz'))
for stride, noise in fbb:
for n in range(0, limit, stride):
strings[n] += noise
for n in range(1, limit):
print strings[n] or nContext
StackExchange Code Review Q#48419, answer score: 6
Revisions (0)
No revisions yet.