Python solution for SPOJ problem 'Buying apples