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.
2 Answers
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])
4 Comments
laimer platz
The answer for
True and 1.2 is also str, unless you're looking for the least number of conversions you need?laimer platz
I edited my answer, perhaps this is what you're asking for.
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()
1 Comment
Community
As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.
Trueand1.2, we can convert it tofloat"? Do you mean you can convertTrueto a float?str, butfloatis less thanstr, that's why the answer isfloat