Guide to High School Computer Science
  • 💻Introduction
    • windows & Python Development
    • macOS & Python Development
    • Visual Studio Code Settings
    • Set up Github
    • Author Page
  • 🧠Prerequisite Skills
    • Keyboard Typing
    • Files & Directories
    • Use of Command Line
    • Git & GitHub
    • Markdown
    • Starting Your Python Project
  • 🐍Python Programming
    • 🍎Python Basics
      • What is Python?
      • Procedural Programming & Programming Paradigms
      • String Formatting
      • Data Types
      • Input & Output to Console
      • Working with Numbers
      • Useful Built-in Functions
      • Math & Random Module
      • Boolean Data Object
      • Comparison, Logical, and Membership Operators
      • If Statements
      • Binary Decisions
      • Multiple Decisions
      • Nested Conditions
      • [EXTRA] Bitwise Operators
      • [EXTRA] Python Style Guide
    • ⏮️Iterations
      • Introduction to While Loops
      • Infinite Loop
      • Controlling Your While Loops
      • Introduction to For Loops
      • For Loops w/ Numeric Sequences
      • For Loops w/ Strings & Lists
      • Iterable Functions w/ For Loops
    • 📦Collections
      • Strings
        • String Basics
        • String Indexing
        • String Slicing
        • String Operators & Functions
        • Basic String Methods
        • String Methods Extended
        • String Methods Document
      • Tuples & Lists
        • Tuples
        • List Basics
        • List are Mutable
        • Adding Items to a List
        • Removing Items from a List
        • Search & Reverse a List
        • List Comprehension
        • List Methods Document
      • Sets
      • Dictionary
      • How to Store Multiple Data Items
    • 💡Defining Functions
      • Functions
      • print() vs return
      • Pre-determined Arguments
      • Nested Functions
      • Map & Filter
      • [Extra] Dynamic Arguments
    • 💾File I/O
      • How to Save Text to an External File
      • Reading CSV in Python
      • Reading JSON in Python
    • 🔨Basic Python Projects
      • Basic Calculator
        • Improving the calculator
        • Exercise Set 1
        • Exercise Set 2
        • 💎Streamlit Application #1
      • Basic Password Generator
        • Exercise Set 3
        • Exercises Related to Math
        • 💎Streamlit Application #2
      • A To-Do Task List
    • ⏳Introduction to Algorithmic Thinking
      • Big-O Notation
      • Basic Algorithms
        • Linear Search
        • Binary Search
        • Basic Sorting Algorithms
      • Recursion
      • Brute Force Algorithms
      • Greedy Algorithm
        • Time on Task (CCC 2013 J4)
        • Dijkstra’s Algorithm
      • Divide and Conquer
        • Merge Sort
      • Dynamic Programming
    • 🤯Object Oriented Programming
      • Class & Objects (Definitions)
      • OOP in Python
      • Encapsulation
      • Polymorphism
      • Inheritance & Overriding
      • Override Magic Methods
      • Case Study: 2D Vectors
      • Case Study: Deck of Cards
      • Exercise
      • Abstract Data Types
      • Case Study: Static 1D Array From Java
    • Competitive Programming
      • Is This Sum Possible?
        • Is the dataset sorted?
        • Searching for a value
        • Determine if the difference between an integer from the array and the target value exists
        • Sorting Algorithms
        • Using Two Pointers
      • Two Sum - LeetCode
        • Generate all possible pairs of values
        • Subtract each value from the target, see if the difference exists in the list
      • Longest Common Prefix - LeetCode
        • Compare all possible prefixes
        • Create the longest common prefix with the direct neighbour
      • Length of Last Word - LeetCode
        • Compare all possible prefixes
      • Where can I go from one point to another?
      • Sample Outline
    • IB Recipe Book
  • 💾Python & Databases
    • Intro to Databases & Data Modeling
      • Common Data Types in SQL
      • Introduction to ERDs
      • Primary Keys and Foreign Keys
      • Database Normalization
    • What is SQL?
      • Getting Started
      • SELECT Queries
        • Selection with Conditions
        • Selection with Fuzziness
        • Selection and Sorting in Order
        • Selection without Duplicates
        • Selection with Limited Number of Outputs
      • AGGREGATE Queries
        • Counting Rows
        • Sum, Average, Min/Max Queries
        • Working with Aggregate Queries
        • Power of using Groups
        • Exercise
      • Interacting with Multiple Table
      • Inserting Data
      • External Resource
  • ☕Java Essentials
    • Basics
      • Starting Java
      • Data & Variables
      • Handling User Inputs & Type Conversion
      • Arithmetic
      • IPO Model
      • Basic Built-in Methods
      • Exercise Questions
    • Conditionals
      • Boolean Operators
      • Compare Strings
      • If Statements
      • If Else Statements
      • Making Multiple Decisions
      • Using Switch
      • Flowchart Symbols
      • Exercise Questions
    • Iterations
      • While Loops
      • For Loop
      • Exercises
    • Java Type Casting
    • Strings
      • Common String Practices
      • String Formatting
      • Java Special Characters
    • Collection
      • Arrays
      • For Each Loop
      • ArrayList
      • Exercise Questions
    • Static Methods
      • (Aside) Clearing your Console
    • Randomness in Java
    • Delayed Output in Java
    • Java Output Formatting
    • Java Style Guide
  • 🛠️JavaScript Programming
    • Our Programming Editor & Workflow
      • Hello, world!
      • Commenting & Variables
      • Data in JavaScript
      • Operators
      • String Formatting
      • Getting User Input
    • JavaScript Exercise Set 1
    • Making Decisions
      • Comparing Values
      • Combining Boolean Comparisons
      • Creating Branches
    • JavaScript Exercise Set 2
    • While Loops
      • Infinite While Loop
      • While Loops and Numbers
      • While Loops and Flags
      • While loops w/ Strings
    • JavaScript Exercise Set 3
    • Subprograms & Functions
      • Creating a Function in JavaScript
      • Function with Input and Assignable Output
    • JavaScript Exercise Set 4
  • 💾Topics in CS
    • Computer Environments & Systems
      • Computer Components
        • In-depth Explanations
      • File Maintenance
      • Computer & Safety
      • Software Development
      • Bits & Binary
    • Careers related to Computer Science
    • Postsecondary Opportunities
Powered by GitBook
On this page
  1. Python Programming
  2. Object Oriented Programming

Case Study: 2D Vectors

PreviousOverride Magic MethodsNextCase Study: Deck of Cards

Last updated 5 months ago

The Code

# OOP Case Study: 2D Vector
from math import sqrt
class Vector:
    # Attributes: x,y Coordinates
    def __init__(self, x, y):
        self._x = x
        self._y = y
    
    @property #x getter
    def x(self):
        return self._x
    
    @property #y getter
    def y(self):
        return self._y

    #Make it representable and printable
    def __str__(self): # __str__() base override
        return f"Vector({self.x}, {self.y})"
    
    def __repr__(self): # __repr__() base override
        return self.__str__()
    
    # Vector Addition → returns a Vector
    # Let p = (x1, y1) and q = (x2, y2), the result of v + u is:
    # A new vector r = (x1+x2, y1+y2)
    
    def __add__(self, other_vector): # This allows Vector + Vector behaviour
        # self is Left operand of + operator
        # other_vector is the Right operand of the + operator
        return Vector(self.x + other_vector.x, self.y + other_vector.y)


    # Scalar Multiplication → returns a Vector
    # Let p = (x1,y1) and k be a scalar multiple, the result of k * Vector(u) is:
    # A new vector q = (k*x1, k*y2)
    def __mul__(self, scalar): # this is the base override of * operator
        return Vector(scalar*self.x , scalar*self.y)


    # Dot Product → returns a scalar numeric value
    # Let p = (x1, y1) and q = (x2, y2), then the dot product (p,q) is:
    # x1*x2 + y1*y2 → produces a scalar answer
    # Applications of dot product: angle b/w vectors, projection, Work & Force in Physics
    def dot_product(self, other_vector):
        return (self.x*other_vector.x) + (self.y*other_vector.y)


    # isOrthogonal → returns Boolean; True if two vectors are Orthogonal to each other
    # Let p = (x1, y1) and q = (x2, y2), then vectors p and q are orthogonal if the dot product of p and q equals 0.
    # Orthogonality of vectors means that the angle between the two vectors is 90 degrees
    def is_orthogonal(self, other_vector):
        return self.dot_product(other_vector) == 0


    # Scalar Distance from one to another → returns a scalar numeric value
    # Let p = (x1, y1) and q = (x2, y2), then the scalar distance from p to q is:
    # square_root( (x1-x2)^2 + (y1-y2)^2 )
    def distance(self, other_vector):
        return sqrt((self.x - other_vector.x)**2 + (self.y - other_vector.y)**2)

    # Magnitude of a Vector → returns a scalar numeric value
    # Let p = (x1, y1) then the magnitude of a vector |p| = the scalar distance from the origin (0,0) to the vector p
    def magnitude(self):
        return self.distance(Vector(0,0))
# end of Vector class

v1 = Vector(1,2)
v2 = Vector(5,10)
print(v1)
print(v2)

print(f"Distance from {v1} to {v2}: {v1.distance(v2)}")
print(f"Magnitude of {v2} is: {v2.magnitude()}")

dp = v1.dot_product(v2)
print(f"{v1} dot_product with {v2}: {dp}")

ortho = v1.is_orthogonal(v2)
print(f"Is {v1} orthongonal to {v2}?: {ortho}")

v3 = v1 + v2
print(f"{v1} + {v2} = {v3}")

v4 = v1*3
print(f"{v1}*3 = {v4}")
🐍
🤯