CS1101-Unit07 programming assignment

docx

School

University of the People *

*We aren’t endorsed by this school

Course

1101

Subject

Computer Science

Date

Jan 9, 2024

Type

docx

Pages

4

Uploaded by BaronEmuPerson965

Report
The original dictionary maps student names (these are the keys) to a list containing all of their courses (these lists are the values): { 'Mary': ['CS1101', 'CS2402', 'CS2001'], 'Paul': ['CS2402', 'CS2001', 'CS1102'], 'George': ['CS2001', 'CS1102', 'CS3101'] } The goal is to invert the dictionary such that the individual courses become the keys and each of these is mapped to a list of students who are taking that course. In order to do this, I have defined a function called inverted that takes a dictionary d as its argument. First, it creates a new dictionary with no items via the dict function: inverse = dict() (Downey, 2015, sec. 11.1 A dictionary is a mapping). Using a for loop to iterate through each item in the list of values for each key, the function checks if the value is already a key in the new, inverse dictionary. If not, it is added as a new key with an empty list as its value: for key in d: for val in d[key]: if val not in inverse: inverse[val] = [] Then, using the append() method as described by Downey (2015, sec. 10.6 List methods), the original key is added as an item in the list of values mapped to the new key: inverse[val].append(key) Finally, feedback is provided to the user by printing the original and inverted dictionaries. Here is the completed program in its entirety:
When the original dictionary is defined as described above and then inverted by calling our function, inverted(original) , the resulting output is shown below. The new, inverted dictionary maps each course (these are the keys) to a list of students taking that course (these lists are the new values), as shown here: { 'CS1101': ['Mary'], 'CS2402': ['Mary', 'Paul'], 'CS2001': ['Mary', 'Paul', 'George'], 'CS1102': ['Paul', 'George'], 'CS3101': ['George'] }
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
  • Access to all documents
  • Unlimited textbook solutions
  • 24/7 expert homework help
References Downey, A. B. (2015). Think Python: How to Think Like a Computer Scientist . O’Reilly Media.