1
\$\begingroup\$

I am reading 4. Built-in Types — Python 3.6.3 documentation

I summarized a dict and a list of builtin_types as follows:

builtin_types_list = ['bytearray', 'bytes', 'classmethod', 'complex', 'dict',
'enumerate', 'filter', 'float', 'frozenset', 'int', 'bool', 'list', 'map',
'memoryview', 'property', 'range', 'reversed', 'set', 'slice',
'staticmethod', 'str', 'super', 'tuple', 'type', 'zip']

structured_builtin_types = {
'primitive': { 'text sequence':{'str'},
             'binary sequeces':{'bytes', 'bytearray', 'memoryview'},
                    'numerics':{'int', 'float', 'complex'},
                   'constants':{'bool':{'True', 'False'}},
                        '        null':{'None'}},
'container': {'sequence':{'sequences':{'tuple', 'list','zip', 'range', 'enumerate', 'reversed'},
                          'iterator' :{'generator', 'map', 'filter'}},
            'collection':{'mapping'  :{'dict'},
                          'sets'     :{'set', 'frozenset'}}},
   'method': {'instance':{'property', 'staticmethod', 'classmethod'},
                 'class':{'super'}}
}

I intend to check all the elements in builtin_types_list are positioned appropriately into structured_builtin_types without items left.

My solution is firstly converting them to sets then checking if issubset is True.

Since there's nested dicts in the structured_builtin_types, I wrote a recursive function to extract sets from structured_builtin_types

Pseudocode for the logic:

declare myset = set()
loop key and value in items view of structured_builtin_types,
check if value's type is a set, update myset,
check if value's type is a dict, recursively call the function.

My code:

myset =set()
def get_sets(mydict):
    for k, v in mydict.items():
        if isinstance(v, set):
            myset.update(v)
        if isinstance(v, dict):
            get_sets(v)

Run and output:

In [91]: get_sets(structured_builtin_types)
In [93]: print(myset)
{'True', 'dict', 'False', 'frozenset', 'staticmethod', 'generator', 'zip', 'str', 'enumerate', 'None', 'reversed', 'tuple', 'bytes', 'set', 'map', 'complex', 'float', 'classmethod', 'property', 'int', 'bytearray', 'filter', 'memoryview', 'list', 'super', 'range'}
# check if issubset
In [94]: set( builtin_types_list).issubset(myset)
Out[94]: False
#get the difference
In [95]: set(builtin_types_list) - myset
Out[95]: {'bool', 'slice', 'type'}

I ask for an alternative way to solve the problem. Also, complicated but advanced solutions are highly appreciated.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.