Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .vs/ProjectSettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"CurrentProjectSetting": null
}
6 changes: 6 additions & 0 deletions .vs/VSWorkspaceState.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"ExpandedNodes": [
""
],
"PreviewInSolutionExplorer": false
}
Binary file not shown.
Empty file.
Binary file added .vs/python_intro/v17/.suo
Binary file not shown.
Binary file added .vs/slnx.sqlite
Binary file not shown.
5 changes: 5 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"githubPullRequests.ignoredPullRequestBranches": [
"main"
]
}
160 changes: 160 additions & 0 deletions 151353.ipynb
Original file line number Diff line number Diff line change
@@ -0,0 +1,160 @@
{
"nbformat": 4,
"nbformat_minor": 0,
"metadata": {
"colab": {
"provenance": [],
"authorship_tag": "ABX9TyMUKGk7KxLXnEt/s+lWiczh",
"include_colab_link": true
},
"kernelspec": {
"name": "python3",
"display_name": "Python 3"
},
"language_info": {
"name": "python"
}
},
"cells": [
{
"cell_type": "markdown",
"metadata": {
"id": "view-in-github",
"colab_type": "text"
},
"source": [
"<a href=\"https://colab.research.google.com/github/DavidMoseNyamamba/python_intro/blob/main/151353.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
]
},
{
"cell_type": "code",
"source": [
"!pip install scikit-learn\n",
"!pip install numpy"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "bk_XKdjp0aPe",
"outputId": "1f5c70d2-d0f2-47a0-f76f-deaad4849451"
},
"execution_count": 3,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"Requirement already satisfied: scikit-learn in /usr/local/lib/python3.11/dist-packages (1.6.1)\n",
"Requirement already satisfied: numpy>=1.19.5 in /usr/local/lib/python3.11/dist-packages (from scikit-learn) (1.26.4)\n",
"Requirement already satisfied: scipy>=1.6.0 in /usr/local/lib/python3.11/dist-packages (from scikit-learn) (1.13.1)\n",
"Requirement already satisfied: joblib>=1.2.0 in /usr/local/lib/python3.11/dist-packages (from scikit-learn) (1.4.2)\n",
"Requirement already satisfied: threadpoolctl>=3.1.0 in /usr/local/lib/python3.11/dist-packages (from scikit-learn) (3.5.0)\n",
"Requirement already satisfied: numpy in /usr/local/lib/python3.11/dist-packages (1.26.4)\n"
]
}
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/",
"height": 356
},
"id": "HDfg_e1Nzsux",
"outputId": "782d279c-9431-456a-93a1-32c903693e94"
},
"outputs": [
{
"output_type": "error",
"ename": "UFuncTypeError",
"evalue": "ufunc 'subtract' did not contain a loop with signature matching types (dtype('<U21'), dtype('int64')) -> None",
"traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[0;31mUFuncTypeError\u001b[0m Traceback (most recent call last)",
"\u001b[0;32m<ipython-input-4-a6d104ef3c83>\u001b[0m in \u001b[0;36m<cell line: 0>\u001b[0;34m()\u001b[0m\n\u001b[1;32m 65\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 66\u001b[0m \u001b[0;31m# predict the class of the new data point\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 67\u001b[0;31m \u001b[0mprediction\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mkNearestNeighbor\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mdata\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mnew_data\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mk\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;36m3\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 68\u001b[0m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34mf'The new data point belongs to class: {prediction}'\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 69\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n",
"\u001b[0;32m<ipython-input-4-a6d104ef3c83>\u001b[0m in \u001b[0;36mkNearestNeighbor\u001b[0;34m(data, predict, k)\u001b[0m\n\u001b[1;32m 19\u001b[0m \u001b[0;32mfor\u001b[0m \u001b[0mrow\u001b[0m \u001b[0;32min\u001b[0m \u001b[0mdata\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 20\u001b[0m \u001b[0;31m# calculate the Euclidean distance between the new data point and each data point in the data set\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 21\u001b[0;31m \u001b[0mdistance\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0meuclidean_distance\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mrow\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m-\u001b[0m\u001b[0;36m1\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mpredict\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 22\u001b[0m \u001b[0;31m# append the class label and distance to the predictions list\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 23\u001b[0m \u001b[0mpredictions\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mappend\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mrow\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;34m-\u001b[0m\u001b[0;36m1\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mdistance\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
"\u001b[0;32m<ipython-input-4-a6d104ef3c83>\u001b[0m in \u001b[0;36meuclidean_distance\u001b[0;34m(x1, x2)\u001b[0m\n\u001b[1;32m 3\u001b[0m \u001b[0;34m\"\"\" x1 and x2 are two numpy arrays\"\"\"\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 4\u001b[0m \u001b[0;34m\"\"\" return the Euclidean distance between x1 and x2\"\"\"\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 5\u001b[0;31m \u001b[0;32mreturn\u001b[0m \u001b[0mnp\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0msqrt\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mnp\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0msum\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mx1\u001b[0m \u001b[0;34m-\u001b[0m \u001b[0mx2\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;34m**\u001b[0m \u001b[0;36m2\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 6\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 7\u001b[0m \u001b[0;32mdef\u001b[0m \u001b[0mkNearestNeighbor\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mdata\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mpredict\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mk\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;36m3\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
"\u001b[0;31mUFuncTypeError\u001b[0m: ufunc 'subtract' did not contain a loop with signature matching types (dtype('<U21'), dtype('int64')) -> None"
]
}
],
"source": [
"def euclidean_distance(x1, x2):\n",
" \"\"\" Calculate the Euclidean distance between two points\"\"\"\n",
" \"\"\" x1 and x2 are two numpy arrays\"\"\"\n",
" \"\"\" return the Euclidean distance between x1 and x2\"\"\"\n",
" return np.sqrt(np.sum((x1 - x2) ** 2))\n",
"\n",
"def kNearestNeighbor(data, predict, k=3):\n",
" \"\"\"predict the class of a new data point based on the k nearest neighbors\n",
"\n",
" parameters:\n",
" data(list): a list of lists, where each list is a data point\n",
" predict(list): a list of the new data point\n",
" k(int): the number of neighbors to consider\n",
"\n",
" returns:\n",
" int: the predicted class of the new data point\n",
" \"\"\"\n",
" predictions = []\n",
" for row in data:\n",
" # calculate the Euclidean distance between the new data point and each data point in the data set\n",
" distance = euclidean_distance(row[:-1], predict)\n",
" # append the class label and distance to the predictions list\n",
" predictions.append((row[-1], distance))\n",
"\n",
" # sort the predictions list by distance\n",
" predictions = sorted(predictions, key=lambda x: x[1])\n",
"\n",
" # select the k nearest neighbors\n",
" top_k = predictions[:k]\n",
"\n",
" # count the number of each class in the top k\n",
" result = []\n",
" for item in top_k: # item is a tuple\n",
" result.append(item[0]) # append the class label to the result list\n",
"\n",
" # return the most common class label\n",
" return max(set(result), key=result.count)\n",
"\n",
"data = np.array([\n",
" [1, 4, 'A', 'D', 'Good'],\n",
" [5, 9, 'E', 'I', 'Good'],\n",
" [6, 7, 'F', 'G', 'Good'],\n",
" [1, 1, 'A', 'A', 'Good'],\n",
" [3, 8, 'C', 'H', 'Good'],\n",
" [10, 4, 'J', 'D', 'Bad'],\n",
" [5, 3, 'E', 'C', 'Bad'],\n",
" [2, 3, 'B', 'C', 'Bad'],\n",
" [6, 3, 'F', 'C', 'Bad'],\n",
" [2, 8, 'B', 'H', 'Bad']\n",
"])\n",
"\n",
"# convert categorical data to numerical data\n",
"label_encoders = {}\n",
"for i in range(2, 4):\n",
" le = LabelEncoder()\n",
" data[:, i] = le.fit_transform(data[:, i])\n",
" label_encoders[i] = le\n",
"\n",
"# separate features and labels\n",
"X = data[:, :-1]\n",
"y = data[:, -1]\n",
"\n",
"# new data point to classify\n",
"new_data = np.array([13, 7, 26, 25]) # x1=13, x2=7, x3=Z, x4=Z (Encoded as 26 and 25)\n",
"\n",
"# predict the class of the new data point\n",
"prediction = kNearestNeighbor(data, new_data, k=3)\n",
"print(f'The new data point belongs to class: {prediction}')\n",
"\n",
"# decode the predicted class back to the original label\n",
"predicted_label = label_encoders[3].inverse_transform([prediction])[0]\n",
"print(f'The new data point belongs to class: {predicted_label}')"
]
}
]
}
85 changes: 85 additions & 0 deletions 151353_q1.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
#add new patient to a list
#add_patient function prompts the user for the patient's name, age, and illness.
def add_patient(patients):
name = input("Enter patient name: ")
age = input("Enter patient age: ")
illness = input("Enter patient illness: ")
#create a dictionary to represent the patient and adds it to the patients list.
patient = {
"name": name,
"age": age,
"illness": illness
}
patients.append(patient)
print(f"Patient {name} added successfully.")

# display all patients
#The display_patients function iterates through the patients list
def display_patients(patients):
if not patients:
print("No patients found.")
else:
for patient in patients:
#print the details of each patient.
print(f"Name: {patient['name']},Age: {patient['age']},Illness: {patient['illness']}")


#Define a function to search for a patient by name and display their details if found.
#The search_patient function to prompt the user for the patient's name
#searches through the patients list to find and display the details of the patient if found.

def search_patient(patients):
name = input("Enter patient name to search: ")
found = False
for patient in patients:
# lower case name of patients
if patient['name'].lower() == name.lower():
print(f"Name: {patient['name']}, Age: {patient['age']}, Illness: {patient['illness']}")
found = True
break
if not found:
print(f"Patient {name} not found.")

#Define a function to remove a patient by name
#The remove_patient function to prompt the user for the patient's name
def remove_patient(patients):
name = input("Enter patient name to remove: ")

#search through the patients list to find and remove the patient if found.
for patient in patients:
if patient['name'].lower() == name.lower():
patients.remove(patient)
print(f"Patient {name} removed successfully.")
return
print(f"Patient {name} not found.")

#Use a while loop to keep the program running until the user chooses to exit
# Demonstrating the functionality
def main():
patients = []
while True:
print("\nHospital Patient Management System")
print("1. Add a new patient")
print("2. Display all patients")
print("3. Search for a patient by name")
print("4. Remove a patient by name")
print("5. Exit")

choice = input("Enter your choice: ")

if choice == '1':
add_patient(patients)
elif choice == '2':
display_patients(patients)
elif choice == '3':
search_patient(patients)
elif choice == '4':
remove_patient(patients)
elif choice == '5':
print("Exiting the program.")
break
else:
print("Invalid choice. Please try again.")

if __name__ == "__main__":
main()
112 changes: 112 additions & 0 deletions 151353_q2.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
#Create a Student class with attributes name and grades
# (a dictionary with subjects as keys and grades as values).
class Student:
# __init__(self, name): Initializes a student with a name and an empty dictionary for grades.
def __init__(self, name):
self.name = name
self.grades = {}
# add_grade(self, subject, grade): Adds a grade for a specific subject.
def add_grade(self, subject, grade):
self.grades[subject] = grade

# get_average_grade(self): Calculates and returns the average grade for the student.

def get_average_grade(self):
if not self.grades:
return 0
return sum(self.grades.values()) / len(self.grades)


#__init__(self): Initializes an empty list of students.
class Classroom:
def __init__(self):
self.students = []

#add_student(self, student): Adds a student to the classroom.
def add_student(self, student):
self.students.append(student)
print(f"Student {student.name} added successfully.")

#display_students(self): Displays all students and their grades.
def display_students(self):
if not self.students:
print("No students in the class.")
else:
for student in self.students:
print(f"Name: {student.name}, Grades: {student.grades}")

#get_student_average(self, student_name): Prints the average grade for a specific student by name.
def get_student_average(self, student_name):
for student in self.students:
if student.name.lower() == student_name.lower():
average = student.get_average_grade()
print(f"Average grade for {student.name}: {average:.2f}")
return
print(f"Student {student_name} not found.")
#get_class_average_for_subject(self, subject): Prints the class average for a specific subject.
def get_class_average_for_subject(self, subject):
total = 0
count = 0
for student in self.students:
if subject in student.grades:
total += student.grades[subject]
count += 1
if count == 0:
print(f"No grades recorded for subject: {subject}")
else:
average = total / count
print(f"Class average for {subject}: {average:.2f}")

# Demonstrating the functionality
#using main() function:
#Provides a simple command-line interface for interacting with the Classroom and Student classes.
#Allows adding students,
# adding grades,
# displaying students,
# getting individual student averages,
# and getting class averages for subjects.
def main():
classroom = Classroom()

while True:
print("\nClassroom Management System")
print("1. Add a new student")
print("2. Add grade for a student")
print("3. Display all students")
print("4. Get average grade of a student")
print("5. Get class average for a subject")
print("6. Exit")

choice = input("Enter your choice: ")

if choice == '1':
name = input("Enter student name: ")
student = Student(name)
classroom.add_student(student)
elif choice == '2':
name = input("Enter student name: ")
subject = input("Enter subject: ")
grade = float(input("Enter grade: "))
for student in classroom.students:
if student.name.lower() == name.lower():
student.add_grade(subject, grade)
print(f"Grade {grade} added for {subject} to student {name}.")
break
else:
print(f"Student {name} not found.")
elif choice == '3':
classroom.display_students()
elif choice == '4':
name = input("Enter student name: ")
classroom.get_student_average(name)
elif choice == '5':
subject = input("Enter subject: ")
classroom.get_class_average_for_subject(subject)
elif choice == '6':
print("Exiting the program.")
break
else:
print("Invalid choice. Please try again.")

if __name__ == "__main__":
main()
Loading