[SOLVED] Conversion of types of objects


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?

Example: we have two objects: 1 and 5.25.We can’t convert them both to int because then we will miss information about 5.25 that will be converted to 5. We can convert them both to float: 1.0 and 5.25 and that is correct answer. Sure we can say that we can convert them both to str: "1", "5.25", but in our interpretation we suppose that int < float < tuple < list < str (of course we can’t compare types of objects, but we suppose that to get an answer) and then float is the minimum available type that both objects can be converted to.

I tried something like:

def type_convertion(first, second):
    data_types = [int, float, tuple, list, str]
    times = {}
    for _type in data_types:
        times[_type] = 0
            if isinstance(_type(first), _type):
                times[_type] += 1
        except TypeError:
            del times[_type]
            if isinstance(_type(second), _type):
                times[_type] += 1
        except TypeError:
            del times[_type]
        return times.keys()

But when I compare int and float the answer is int but should be float and I don’t know how to fix it.


If I well understand your question you want to get the minimum/best type that can match two variables.

I have updated your ranking order as follows int < float < str < tuple < list, but you can still keep your ranking if you prefer. So here is a function that takes several variables as arguments and returns the name of the minimum type that match these variables:

def type_convertion(*variables):
    data_types = {'int': 0, 'float': 1, 'str': 2, 'tuple': 3, 'list': 4} # types and their rankings
    minimum_type = [0, ''] # this list will contain the ranking and the name of the minimum type
    for variable in variables:
        variable_type = type(variable).__name__ # get the name of the variable type
        if variable_type not in data_types:
            # if the type is not reconized we can always convert it in str
            return 'str'
        if data_types[variable_type] > minimum_type[0]:
            # if the variable type is of higher rank from the previous one then change the minimum variable
            minimum_type = [data_types[variable_type], variable_type]
    return minimum_type[1]

The *variables allows you to give the function as much arguments as you want, so you are not limited to 2 variables.

To get the minimum type call the function like this:

>>> type_convertion('a', 10, 0.5)

Answered By – Marin Nagy

Answer Checked By – Cary Denson (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *