In: Computer Science
IN PYTHON 3 LANGUAGE
Define a recursive function named immutify; it is passed any data structure that contains int, str, tuple, list, set, frozenset, and dict values (including nested versions of any of these data structures as an argument). It returns an immutable equivalent data structure (one that could be used for values in a set or keys in a dict). The types int, str, and frozenset are already immutable. Convert a set to a frozenset; convert all the values in a tuple to be their immutable equivalents, in the same order); convert a list to a tuple (with immutable equivalents of its values, in the same order); convert a dict to tuple of 2-tuples (see the association tuple in question 2) but here with the 2-tuples sorted by the dict’s keys. If immutify ever encounters a value of another type (e.g., float) it should raise a TypeError exception.
The following call (with many mutable data structures)
Example 1:
immutify( {'b' : [1,2], 'a' : {'ab': {1,2}, 'aa' : (1,2)}} )
returns the immutable data structure
(('a', (('aa', (1, 2)), ('ab', frozenset({1, 2})))), ('b', (1, 2)))
Example 2:
immutify( [{1,2}, {3,frozenset([4,5])}, {6,7}])
Returns
(frozenset({1, 2}), frozenset({3, frozenset({4, 5})}),
frozenset({6, 7}))
import operator
def make_tuple(value):
return tuple(value)
def immutify(value):
# check if type is in our policy list or
not
allowedTypes=[int, str, dict, frozenset, tuple, set, list]
if type(value) not in allowedTypes:
raise TypeError() # raise if type of value is not in
our policy list
elif type(value) == dict:
sorted_value = sorted(value.items(), key=operator.itemgetter(0))
# sort dict by keys
# output of sorting gives us tuple so we have to
iterate through this tuple
my_list=[] # created because some items of tuple will
be lost so we have to store in this list
for x,y in sorted_value:
my_list.append((x,immutify(y)))
return tuple(my_list) # convert to tuple
elif type(value) == list:
my_list=[
for i in value:
my_list.append(immutify(i))
return tuple(my_list)
elif type(value) == set:
my_list=[]
for i in value:
my_list.append(immutify(i)) #set may contain other
mutable type
return frozenset(my_list) # convert to
frozenset
else:
return value
try:
print(immutify( [{1,2}, {3,frozenset([4,5])}, {6,7}]))
# call immutify
except TypeError:
print('Type error') # will catch
TypeError
Another reason to create my_list named list is that tuple or set may contain other mutable type. So, we have to iterate through that to call that function again which is recursion (calling that function again from with in that function) and then we will store that immutable values in list and convert that list to immutable type (Here frozenset or tuple)