AITC Wiki

Practice3 solution

练习 3 参考答案

Practice3 solution

中文版:练习 3 参考答案

Exercise 1: Creating a Basic Structured Array

Problem: Create a structured array to store information about 3 students. Each student should have:

  • A ‘name’ field (string of length 20)

  • An ‘age’ field (integer)

  • A ‘gpa’ field (float)

Add the following students:

  • “Alice Johnson”, 19, 3.7

  • “Bob Smith”, 20, 3.2

  • “Charlie Brown”, 18, 3.9

Then print the entire array and the GPA of the second student.

import numpy as np
 
# Define the data type
student_dtype = np.dtype([
 ('name', 'U20'), # Unicode string of length 20
 ('age', 'i4'), # 4-byte integer
 ('gpa', 'f4') # 4-byte float
])
 
# Create the structured array
students = np.array([
 ('Alice Johnson', 19, 3.7),
 ('Bob Smith', 20, 3.2),
 ('Charlie Brown', 18, 3.9)
], dtype=student_dtype)
 
# Print the entire array
print("All students:")
print(students)
 
# Print the GPA of the second student (index 1)
print("\nBob's GPA:", students[1]['gpa'])

Exercise 2: Sorting and Filtering

Problem: Using the students array from previous exercises:

  • Sort the students by GPA in descending order

  • Find and print all students with GPA > 3.5

  • Calculate the average age of students

# 1. Sort by GPA (descending order)
sorted_by_gpa = np.sort(students, order='gpa')[::-1]
print("Students sorted by GPA (descending):")
print(sorted_by_gpa)
 
# 2. Filter students with GPA > 3.5
high_gpa = students[students['gpa'] > 3.5]
print("\nStudents with GPA > 3.5:")
print(high_gpa)
 
# 3. Calculate average age
avg_age = np.mean(students['age'])
print("\nAverage age of students:", avg_age)

Exercise 3: Record Arrays and Field Access

Problem:

  • Convert the students array from Exercise 1 to a record array

  • Demonstrate accessing fields using dot notation

  • Add a new student using record array syntax

  • Print all students under 20 years old

# 1. Convert to record array
students_rec = students.view(np.recarray)
 
# 2. Access fields with dot notation
print("First student's name:", students_rec[0].name)
print("Average GPA:", np.mean(students_rec.gpa))
 
# 3. Add a new student
new_student = np.rec.array([('Dana Lee', 19, 3.5)], dtype=students_rec.dtype)
students_rec = np.concatenate((students_rec, new_student))
 
# 4. Print students under 20
print("\nStudents under 20:")
print(students_rec[students_rec['age'] < 20])