FizzBuzz – Most programmers cant solve this (or so I am told…).

Write a program that prints the numbers from 1 to 100. But for multiples of three print “Fizz” instead of the number and for the multiples of five print “Buzz”. For numbers which are multiples of both three and five print “FizzBuzz”.

Tim Akinbo posted this on his website today and threw down a challenge. Here’s my humble attempt at solving the problem. It took a little under 20 minutes.

The challenge statement:

This is the fabled Fizzbuzz problem, which is said that most programmers cant solve in longhand. Its a common question asked in programming interviews.

Write a program that prints the numbers from 1 to 100. But for multiples of three print “Fizz” instead of the number and for the multiples of five print “Buzz”. For numbers which are multiples of both three and five print “FizzBuzz”.

My suggestion

This is a program written in python, we loop through the values from 1 to 100. Test for multiples of 15, then multiples of 5 and multiples of 3. Others will be printed as is.

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

Need to use an ImageField in Django with a limit on filesize while still allowing empty entries?

Here’s a class that subclasses the ImageField and allows you to set a limit on filesize while still allowing empty entries.


class ImageField50KB(forms.ImageField):
    def __init__(self, *args, **kwargs):
        super(ImageField50KB, self).__init__(*args, **kwargs)

        self.label = (u'Passport (Max 50kB)')

        self.helptext = (u'Attach a current passport photograph')

    def clean(self, data, initial):
        if not data and initial:
            return initial
        f = super(ImageField50KB, self).clean(data)

        if not (f.size <= 50000):
             raise forms.ValidationError((u'Image is too large, Maximum filesize allowed is 50kB' ))
        return f

To use this in your form, copy the code into forms.py and add the following to the form definition:


	image= ImageField50KB(
		widget=forms.FileInput,
		initial=BLANK_IMAGE,
	 )

where BLANK_IMAGE has been declared already to point to a file that will be used as default image in case the field is empty.