Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download

Code practices - Unit 7

77 views
ubuntu2204
Kernel: Python 3 (system-wide)

Programming Assignment Unit 7

In Python, dictionaries are a type of mutable collection that allows for efficient key-value pair storage and access (Downey, 2015).

For my assignment, I will invert a dictionary where students are keys and their courses are values.

The goal was to have the courses as keys and the students as values in the inverted dictionary.

Step 1: Create a sample data

First, I set up the sample data:

  1. Data includes some course codes in mixed cases (e.g. cs, CS )

  2. some students with duplicate course enrollments:

students_courses = { 'Stud1': ['CS1101', 'cs2402', 'CS2001', 'CS2402'], 'Stud2': ['cs2402', 'CS2001', 'CS1102', 'CS2001'], 'Stud3': ['cs1101', 'CS3305', 'cs3305', 'CS4405'], 'Stud4': ['CS1103', 'cs3306', 'CS3307', 'cs4406'] } print("Original Dictionary:") print(students_courses)
Original Dictionary: {'Stud1': ['CS1101', 'cs2402', 'CS2001', 'CS2402'], 'Stud2': ['cs2402', 'CS2001', 'CS1102', 'CS2001'], 'Stud3': ['cs1101', 'CS3305', 'cs3305', 'CS4405'], 'Stud4': ['CS1103', 'cs3306', 'CS3307', 'cs4406']}

Step 2: Create "inverting" function

Second, I create a function, invert_dictionary , which takes in the original dictionary as an argument.

def invert_dictionary(students_courses): """Inverts a dictionary of students and their courses, addressing case sensitivity and duplicates.""" inverted = {} # Iterate over the dictionary to get student and their list of courses for student, courses in students_courses.items(): # Using a "set" to remove duplicate courses for a student unique_courses = set(courses) for course in unique_courses: # Convert the course code to uppercase to handle case sensitivity course_upper = course.upper() # For each course, check if it's in the new dictionary if course_upper not in inverted: # If not, create a new list for it inverted[course_upper] = [student] else: # Before appending, check if the student is already listed under the course if student not in inverted[course_upper]: inverted[course_upper].append(student) return inverted

Step 3: Run and test

# Inverting the dictionary result = invert_dictionary(students_courses) print("\nCourse statistics:") print(result)
Course statistics: {'CS2001': ['Stud1', 'Stud2'], 'CS2402': ['Stud1', 'Stud2'], 'CS1101': ['Stud1', 'Stud3'], 'CS1102': ['Stud2'], 'CS4405': ['Stud3'], 'CS3305': ['Stud3'], 'CS4406': ['Stud4'], 'CS3306': ['Stud4'], 'CS3307': ['Stud4'], 'CS1103': ['Stud4']}

The output has courses as keys and lists of students enrolled in each course as values.