Reputation: 139
How to write a function on python that accepts two objects in input and gives on output minimal type which both of objects can be presented?
For example, if we have [1, 2, 3]
and 2
we can convert it to str
, if we have "Hi"
and 1.2
we can convert it to str
, if we have True
and 1.2
we can convert it to float
and so on.
Upvotes: 0
Views: 130
Reputation: 139
When compare int
and float
answer is int
but should be float
def type_convertion(first, second):
data_types = [int, float, tuple, list, str]
times = {}
for _type in data_types:
times[_type] = 0
try:
if isinstance(_type(first), _type):
times[_type] += 1
except TypeError:
del times[_type]
continue
try:
if isinstance(_type(second), _type):
times[_type] += 1
except TypeError:
del times[_type]
continue
return times.keys()
Upvotes: 0
Reputation: 66
All objects in Python can be converted to strings, even user defined class instances.
>>> class Test:
pass
>>> t = Test()
>>> str(t)
'<__main__.Test object at 0x0000015315891730>'
>>> str(1)
'1'
>>> str(True)
'True'
>>> str([1, 2, 3])
'[1, 2, 3]'
>>>
This is because they have a __str__
function that is automatically defined even if you don't define it.
Edit: You can do it like this (pardon the ugly code)
def leastConversions(first, second):
type_casts = [str, int, float, tuple, list, dict]
times = {}
for _type in type_casts:
if not isinstance(first, _type):
times[_type] = 0
try:
if not isinstance(first, _type):
temp = _type(first)
times[_type] += 1
except TypeError:
del times[_type]
continue
try:
if not isinstance(second, _type):
temp = _type(second)
times[_type] += 1
except TypeError:
del times[_type]
continue
return min(times, key = lambda k: times[k])
Upvotes: 1