6 kyu

Hint a Type

Description:

Task

In Python 3.5 a new module called typing was introduced which provides type hints. In this kata you will need to implement to_type_hint which needs to return (a best match of) such a type hint for some input.

Examples

Numeric Types (int, float, complex):

# Return the type itself:
to_type_hint(2) => int
to_type_hint(1.0) => float
to_type_hint(3+5j) => complex

Some other types:

to_type_hint(None) => None
to_type_hint(True) => bool
to_type_hint(False) => bool
to_type_hint("123") => str

Lists, set, frozensets, deques:

# If the object contains no elements, return its type
to_type(deque()) => deque

# If all elements within have same type:
to_type_hint([1, 2, 3]) => List[int] 
to_type_hint({1, 3, 4}) => Set[int]
to_type_hint(deque([1])) => Deque[int]
to_type_hint(frozenset([3, 5, 7])) => FrozenSet[int]

# Different types of elements within: 
to_type_hint([True, 2, 3.0, 3]) => List[Union[bool, int, float]]
to_type_hint({"1", 2, 3}) => Set[Union[str, int]]
to_type_hint(deque([2, 3.0])) => Deque[Union[int, float]]

Tuples

# Less than four elements, return a Tuple with each type:
to_type_hint(()) => Tuple[()]
to_type_hint((42,)) => Tuple[int,]
to_type_hint((1, 2)) => Tuple[int, int]
to_type_hint((1, "2", 3)) => Tuple[int, str, int]

# With more than three elements, use the literal ellipsis to specify a variable length tuple
to_type_hint((1, 2, 3, 4)) => Tuple[int, ...] # All elements in tuple are same type
to_type_hint((1, "2", 3, 4.0)) => Tuple[Union[int, str, float], ...]

Dictionaries

to_type({}) => dict
to_type_hint({1: 2, 3: 4}) => Dict[int, int]
to_type_hint({"a": 1, "b": 2}) => Dict[str, int]
to_type_hint({"a": 2, "b": 3.0, 2: None}) => Dict[Union[str, int], Union[int, float, None]]

Nested types

# Input types may be nested:
to_type_hint([1, [1, 2], [[1, 2], 3]]) => List[Union[int, List[int], List[Union[List[int], int]]]]
to_type_hint(([1, 2], [])) => Tuple[List[int], list]

Notes:

  • Other types that are not mentioned above, will not be tested (e.g. generator, iterator, function, range, etc.)
  • The order of types in a Union does not matter
Recursion
Algorithms

Stats:

CreatedJun 3, 2020
PublishedJun 6, 2020
Warriors Trained684
Total Skips12
Total Code Submissions622
Total Times Completed56
Python Completions56
Total Stars13
% of votes with a positive feedback rating77% of 24
Total "Very Satisfied" Votes15
Total "Somewhat Satisfied" Votes7
Total "Not Satisfied" Votes2
Total Rank Assessments4
Average Assessed Rank
6 kyu
Highest Assessed Rank
5 kyu
Lowest Assessed Rank
8 kyu
Ad
Contributors
  • Admiraal Avatar
  • FArekkusu Avatar
  • G_kuldeep Avatar
Ad