Question

In: Computer Science

IN PYTHON 3 LANGUAGE Define a recursive function named immutify; it is passed any data structure...

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}))

Solutions

Expert Solution

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)


Related Solutions

PYTHON: Write a recursive function named linear_search that searches a list to find a given element....
PYTHON: Write a recursive function named linear_search that searches a list to find a given element. If the element is in the list, the function returns the index of the first instance of the element, otherwise it returns -1000. Sample Output >> linear_search(72, [10, 32, 83, 2, 72, 100, 32]) 4 >> linear_search(32, [10, 32, 83, 2, 72, 100, 32]) 1 >> linear_search(0, [10, 32, 83, 2, 72, 100, 32]) -1000 >> linear_search('a', ['c', 'a', 'l', 'i', 'f', 'o', 'r',...
Language: Python 3 (Please structure answer as basic as possible) Write a function that involves two...
Language: Python 3 (Please structure answer as basic as possible) Write a function that involves two arguments, named changeTheCase(myFile, case), that takes, as arguments, the name of a file, myFile, and the case, which will either be “upper” or “lower”. If case is equal to “upper” the function will open the file, convert all characters on each line to upper case, write each line to a new file, named “upperCase.txt”, and return the string “Converted file to upper case.” If...
In C++ language. void printTreeIO(Tnode *n)(3): recursive function that prints out the data in the tree...
In C++ language. void printTreeIO(Tnode *n)(3): recursive function that prints out the data in the tree in order
Write a Python module that must satisfy the following- Define a function named rinsert. This function...
Write a Python module that must satisfy the following- Define a function named rinsert. This function will accept two arguments, the first a list of items to be sorted and the second an integer value in the range 0 to the length of the list, minus 1. This function shall insert the element corresponding to the second parameter into the presumably sorted list from position 0 to one less than the second parameter’s index.   Define a function named rinsort. This...
(Python) Define a function makeTwoWay that expects a singly linked structure as its argument. The function...
(Python) Define a function makeTwoWay that expects a singly linked structure as its argument. The function builds and returns a doubly linked structure that contains the items in the singly linked structure. (Note: The function should not alter the argument's structure.) node.py source code: """ File: node.py Node classes for one-way linked structures and two-way linked structures. """ class Node(object):     def __init__(self, data, next = None):         """Instantiates a Node with default next of None"""         self.data = data...
Python Problem 3 Write a function named enterNewPassword. This function takes no parameters. It prompts the...
Python Problem 3 Write a function named enterNewPassword. This function takes no parameters. It prompts the user to enter a password until the entered password has 8-15 characters, including at least one digit. Tell the user whenever a password fails one or both of these tests.
Define a Python function named matches that has two parameters. Both parameters will be lists of...
Define a Python function named matches that has two parameters. Both parameters will be lists of ints. Both lists will have the same length. Your function should use the accumulator pattern to return a newly created list. For each index, check if the lists' entries at that index are equivalent. If the entries are equivalent, append the literal True to your accumulator. Otherwise, append the literal False to your accumulator. Hint: Since you must use the same index with each...
Python Language Only! Python Language Only! Python Language Only! Python 3 is used. When doing this...
Python Language Only! Python Language Only! Python Language Only! Python 3 is used. When doing this try to use a level one skill python, like as if you just learned this don't use anything advanced if you can please. If not then do it as you can. Assume you have a file on your disk named floatnumbers.txt containing float numbers. Write a Python code that reads all the numbers in the file and display their average. Your code must handle...
it should be c++ data structure Write a recursive function that draws the following shape. X...
it should be c++ data structure Write a recursive function that draws the following shape. X XXX XXXXX XXXXXXX XXXXXXXXX XXXXXXXXX XXXXXXX XXXXX XXX X The length of the longest row in the shape and the shape's character are function parameters. In above shape the longest row is 9 and the pattern's character is "X”.
1)define variables. 2)define functions. 3)define data structure.
1)define variables. 2)define functions. 3)define data structure.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT