avatar Bite 76. The singledispatch countdown challenge

We are stoked and grateful to have Martin have you practice functools.singledispatch (new in Python 3.4).

PEP 443 defines generic programming / a single-dispatch generic function as:

A generic function is composed of multiple functions implementing the same operation for different types. Which implementation should be used during a call is determined by the dispatch algorithm. When the implementation is chosen based on the type of a single argument, this is known as single dispatch.

Let's write one ... Martin:

Your challenge today is to have count_down print any given input in the following manner:

1234
123
12
1

Your solution should be able to handle any of these data types and still get the same results:

  [int]: 1234
  [str]: '1234'
 [list]: [1, 2, 3, 4] or ['1', '2', '3', '4']
[tuple]: (1, 2, 3, 4) or ('1', '2', '3', '4')
  [set]: {1, 2, 3, 4} or set([1, 2, 3, 4])
 [dict]: {1: 'one', 2: 'two', 3:'three', 4:'four'} or
         {'1': 'one', '2': 'two', '3':'three', '4':'four'}

Don't forget to support a float! Example for 12.34 it should work as:

12.34
12.3
12.
12
1

If a data type is not supported (datetime, itertools.compress or re.compile for example), it should raise a ValueError.

Good luck, and have fun!

Login and get coding
go back Advanced level
Bitecoin 4X

Will you be Pythonista #196 to crack this Bite?
Resolution time: ~60 min. (avg. submissions of 5-240 min.)
Pythonistas rate this Bite 4.67 on a 1-10 difficulty scale.
» Up for a challenge? 💪

Focus on this Bite hiding sidebars, turn on Focus Mode.

Ask for Help