Docsity

Algorithm Thinking and its Application., Study notes of Computer Programming

Partial preview of the text

Download Algorithm Thinking and its Application. and more Study notes Computer Programming in PDF only on Docsity!

ALGORITHMIC THINKING & ITS

APPLICATIONS

ATA โ€” Complete Notes

Prof. Dr. Dip Sankar Banerjee

Weeks 1โ€“ 13

WEEK 1 โ€” Introduction to Algorithmic Thinking

  • Big Problems โ†’ Smaller Steps โ†’ Converted into Computing Programs
  • Everything is a part of an algorithm!
  • Data has many varieties
  • Algorithm = Structured way of breaking down big problems into smaller ones

Key Definitions

  • Problem = Something that has solutions
  • Algorithmic = Step-by-step formalizing, planning or execution (breaking problems into steps)
  • Thinking = Defining a problem (also define constraints) โ†’ Solve problem with formal way

How to Solve a Problem

  • Identify Problems โ†’ Break into Sub-Problems โ†’ Solve those Sub-Problems
  • How to Represent an Algorithm: โ—ฆ Flow Charts (Block Diagram) โ—ฆ Pseudocodes

Flow Chart Symbols

  • Start / End โ†’ Oval/Rounded shape
  • Decision โ†’ Diamond shape
  • Process โ†’ Rectangle
  • Terminating after finite steps โ†’ Parallelogram

Abstraction

  • High Level Abstraction โ†’ Short but Crisp (Gather Ingredients โ†’ Prepare Tea โ†’ Serve Tea)
  • Low Level Abstraction โ†’ Long & Detail (Boil Water โ†’ Add Tea Leaves โ†’ Brew โ†’ Add Milk โ†’ Serve Tea)
  • Abstraction = Focus on Essentials WEEK 2 โ€” Computers, Memory & Pseudocodes
  • Problems โ†’ Solution using Set of Steps โ†’ Flow Chart โ†’ Pseudocode โ†’ Program
  • Abstraction = Simplifying Complexity by giving sub-groups (Higher Abstraction & Lower Abstraction)

Computer Basics

  • Computer = Device which is capable of processing data
  • Program = Set of steps / What to do? (List of Information given to computer)
  • Information Store = Storage of machine โ†’ Binary Data

Number Systems

  • Computer always communicates using Binary Language (made of 0 & 1)
  • Computers are built with Transistors โ†’ combined to form logic devices (Adders, Substractors, Multipliers, Storage Devices, Communication Devices)
  • A Transistor can hold: High State (1) OR Low State (0)
  • George Boole โ†’ Boolean Algebra
  • Number Systems: โ—ฆ Decimal: Base 10 (10 symbols) โ—ฆ Binary: Base 2 (2 symbols) โ—ฆ Octal: Base 8 (8 symbols) โ—ฆ Hexadecimal: Base 16 (16 symbols)

๐Ÿ“ Note: If 'K' symbols then base K number system

  • Hexadecimal: 0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F

Decimal to Binary Conversion

  • Divide by 2 repeatedly and read remainders bottom to top โ—ฆ Example: 56 โ†’ 111000 in binary

Binary to Octal Conversion

  • Step 1: Make groups of 3 bits
  • Step 2: Convert groups into decimal
  • Step 3: Merge it

โ—ฆ Example: (111010) โ‚‚ โ†’ 111|010 โ†’ 7|2 โ†’ (72) โ‚ˆ

Memory Units

  • Fundamental unit of data = Byte (8 bits)
  • 2ยนโฐ bytes = Kilobyte (KB)
  • 2ยนโฐ KB = Megabyte (MB)
  • 2ยนโฐ MB = Gigabyte (GB)

๐Ÿ“ Note: 2ยฒ = 100 (3 bits) and 00000100 (8 bits)

WEEK 4 โ€” Computational Thinking

  • Computational Thinking = Special Thinking Patterns; Process to pose & solve problems
  • Set of skills that help to set up a problem in such a way that a computer can help you solve it

4 Pillars of Computational Thinking

1. Decomposition

  • Breaking Big โ†’ Small
  • Steps in terms of basic math operators (+, - , /, ร—) OR creating simple structures

2. Pattern Recognition

  • This Problem โ†’ This Solution (via recognizing patterns)
  • Reusing Techniques Across Similar Problems
  • Popular Problem โ†’ their Popular Solution

3. Abstraction

  • Removing unnecessary part of problem โ†’ Critical Skillset
  • Modularization โ†’ e.g.: Addition of 10 numbers โ†’ repeat โ†’ Steps ร— Module โ† Functions

4. Algorithm Design

  • Efficiency, Optimization / Simplicity โ†’ Make Faster Program
  • Difference between Correct & Efficient

Example: Solving Sudoku

  • Sudoku = Combinational Problem (multiple configurations can be possible)
  • Step 1: Decomposition โ†’ Working in all parts of Sudoku
  • Step 2: Recognize Pattern
  • Step 3: Abstraction

Problem Understanding Process

  • Before Everything: First thing to do is Understand the Problem
  • Identify Inputs โ†’ Identify Outputs โ†’ Process Information โ†’ Find if there is an extreme case โ†’ Produce Outputs โ†’ Von-Neumann Architecture
  • Solution Design: Define Program Variables (Input) โ†’ Stepwise Refinement (Change) โ†’ Identify Algorithmic Patterns (Similarity)

Hexadecimal to Decimal Conversion

  • Step 1: Map 0โ€“9 as is, A=10, B=11, C=12, D=13, E=14, F=
  • Step 2: From rightmost to leftmost, starting from 16โฐ

โ—ฆ Example: (2F) โ‚โ‚† = 2ร—16ยน + Fร—16โฐ = 32 + 15 = 47

Binary Arithmetic

Binary Addition Rules

1+0=1, 0+1=1, 0+0=0, 1+1=

Binary Subtraction โ€” Using Complements

  • 1's Complement: Reverse the bits (e.g. 0010 โ†’ 1101)
  • 2's Complement: Add 1 to 1's complement (e.g. 0010 โ†’ 1101 + 1 = 1110)

WEEK 6 โ€” Python Basics: Types & Expressions

  • REPL = Repeat Execute Program Loop โ†’ for writing in Windows PowerShell
  • Python: Write code in a file โ†’ save in .py form โ†’ Execute
  • REPL โ†’ for small ideas (calculators)

Expressions & Types

  • Expressions = That can be evaluated โ†’ Always returns a value โ—ฆ e.g.: 2.3, (2ร—7+2)ร—0.
  • Types = A finite set of data and corresponding operations

Python Data Types

    1. Integers โ†’ Whole Numbers
    1. Float โ†’ Real Numbers
    1. String โ†’ Collection of Characters
    1. Boolean โ†’ True/False (0/1)
    1. Doubles โ†’ Larger (64 bit/8 bytes)
    1. Long Ints โ†’ Larger (64 bit/8 bytes)

๐Ÿ“ Note: Floating Point Errors: They are approximately same but not exact, so some

mistakes can happen

Special Python Operators

  • ** โ†’ Exponentiation (exponential power)
  • // โ†’ Floor Division (quotient only)
  • % โ†’ Modulo (remainder)

๐Ÿ“ Note: In String data type, '+' means concatenation

Conversions

  • float(2) โ†’ 2.
  • int(2.5) โ†’ 2
  • Narrow โ†’ Wider: Possible
  • Wider โ†’ Narrow: Possible but BY FORCING
  • Int = 4 bytes, Float = 8 bytes (larger data type)

Assignment Statement

  • Represented with equals sign (=)
  • Takes an expression โ†’ Evaluate it โ†’ Stores value in variable โ—ฆ e.g.: x = 4+1 (x=variable, 4+1=expression)

Operator Precedence

  • Just like BODMAS but Python has a different list

State Diagrams

  • To use same variable for multiple constant values

ML Concepts (Live)

  • Supervised Learning: Where we know target outcome (Labeled Data)
  • Unsupervised Learning: Where we have to find patterns & relationships (Unlabeled Data) WEEK 7 โ€” Procedures & Functions

Procedural Language

  • Level 1 operators: (+), (-), (V-)
  • Level 0 operators: +, - , *, /
  • Procedural Language: Language that follows step-by-step approach with functions & procedures

Function Calls

  • It is like mathematics: x = f(y)
  • Form: name(x, y, ...) โ—ฆ function name + Arguments

Built-in Functions

    1. Type casting: int(), float(), bool()
    1. round()
    1. max()
    1. min()
    1. cos() โ€” needs: import math
    1. sqrt() โ€” needs: import math

Module

  • Module = Provide functions, variables (e.g. temp.py)
  • Script = Behaves like an application (e.g. helloApp.py)

๐Ÿ“ Note: For taking input from user: use input() โ†’ It will always take as a string only

Defining a Function

def function_name(arguments): # Function Header

Body (indented)

return value

  • Keyword = A reserved word in programming languages
  • Parameter: Variable that is listed in function definition
  • Argument: Value to assign when calling function

code (allows adding another condition if previous ones fail)

else:

code

Variable Naming Rules

  • Variables are case sensitive (age, Age, AGE are 3 different variables)
  • R1: Variable name must start with a letter or underscore (_)
  • R2: Variables can contain letters, numbers & underscore (_)
  • R3: Variable name can't be a keyword (def, class, while, True, for, etc.)

๐Ÿ“ Note: Some libraries have function names matching Python's default names. To

remove, use Decorators (@)

Prompting Engineering โ€” ROCCC Framework

  • ROCCC: Role, Objective, Context, Constraints, Check/Criteria
  • AI Tools: ChatGPT, Gemini, Perplexity, Grok, Deep Research
  • Kaggle = A site where many datasets are there WEEK 9 โ€” Conditional Branching & Loops

Conditional Branching

  • There is always a Boolean expression in conditional statements โ†’ to result in True/False value

๐Ÿ“ Note: NULL or 0 is treated as False, everything else is True

Loop Over / Iterate

  • Repetition of some commands/functions

Lists (Vector Data Type)

  • List = Vector Data Type โ—ฆ a = [1, 2, 3, 9, 5.6] โ—ฆ 0 - index from left, - 1 index from right
  • For adding in a list: use list.append()
  • In this situation we use 'for' loop statement

For Loop Syntax:

for x in grades: print(x) # loop variable, loop sequence, Body

Tokens (Live TA)

  • Tokens = Smallest individual unit that makes up source code
  • A compiler breaks this into tokens during analysis before processing the code
  • Lexical Analysis = Breaking down into very small parts

Types of Tokens

    1. Keywords โ†’ Reserved Words
    1. Identifiers โ†’ Names given to entities, variables, functions
    1. Literals โ†’ Fixed values that appear directly in code
    1. Punctuators โ†’ Separators or Delimiters e.g.: [], (), {}, :, ;, ,,.
    1. Operators โ†’ Special symbols that perform operations on variables โ—ฆ Arithmetic: +, - , *, /, //, %, ** (floor division, modulo, power) โ—ฆ Assignment: =, +=, - =, *=, /=, //=, %=, **= โ—ฆ Comparison: ==, !=, >, <, >=, <= โ—ฆ Logical: and, or, not โ—ฆ Bitwise: & =AND, | =OR, ^ =XOR, ~ =NOT, << =Left Shift, >> =Right Shift WEEK 10 โ€” Loops: For & While

Types of Loops

  • Deterministic Loop โ†’ 'For' Loop (when for particular list, start & end point known)
  • Non-Deterministic Loop โ†’ 'While' Loop (we don't know exact no. of repeats)

๐Ÿ“ Note: range(a, b) โ†’ string: a, ....., b- 1

While Loop

  • There is only Loop Invariant
  • As soon as it becomes false, then the output has been returned while (True): # code invariant() break

๐Ÿ“ Note: Only if needs to be executed at least once โ†’ Bottom Check (Important)

Common Algorithms Using Loops

1. Swapping

  • Assigning a temporary variable temp = a a = b b = temp

    OR: a, b = b, a

2. Counting

  • Using a loop and initialize a counter variable to 0
  • Increment counter by 1 for each item

Lists vs Tuples

second = 1 next = first + second count = 2 while count < t: 1st = 2nd 2nd = next

Rounding Output

print(f"{:.2f}".format(number)) print("%.2f" % x) WEEK 12 โ€” Polynomials & Number Systems

Polynomials

  • Linear: P(x) = 2x + 3
  • Quadratic: P(x) = xยฒ - 4x + 7
  • Cubic: P(x) = 4xยณ + 2xยฒ - x + 5
  • Degree = Highest exponent in polynomial
  • Coefficients = Numerical factors of terms

Methods for Polynomial Evaluation

1. Naive Method

  • Order: xโฐ, xยน, xยฒ, xยณ...
  • Evaluate each term separately, then consolidate partial results

2. Horner's Method (Efficient)

  • Order: xโฟ, xโฟโปยน, xยน, xโฐ...
  • Steps for P(x) = 3xยฒ + 2x + 5 + 7: โ—ฆ Start: 3 (coeff of nth degree) โ—ฆ Multiply with x: 3x โ—ฆ Add next coeff: 3x + 2 โ—ฆ Repeat: (3x+2)x + 5 โ—ฆ Repeat: ((3x+2)x + 5)x + 7 โ—ฆ Done: 3xยฒ + 2xยฒ + 5x + 7

3. Using NumPy's polyval()

import numpy as np coeff = [7, - 5, 2, 3] # xโฐ, xยน, xยฒ, xยณ order np.polyval(coeff, x) # Built-in

Number Systems โ€” Summary

  • Decimal: Base 10 โ†’ e.g. 347
  • Binary: Base 2 โ†’ e.g. 1101
  • Octal: Base 8 โ†’ e.g. 173
  • Hexadecimal: Base 16 โ†’ e.g. 2F

๐Ÿ“ Note: Octal = 3 bits (111 = 7), Hexadecimal = 4 bits (1111 = 15)

Python Prefixes for Number Systems

  • Binary โ†’ 0b (e.g. 0b1101)
  • Octal โ†’ 0o (e.g. 0o17)
  • Hexadecimal โ†’ 0x (e.g. 0xFF) WEEK 13 โ€” Characters, Strings & Python Lists

Characters

  • Character = 1 byte entity (e.g. @, $, &, :, ; ... etc.) โ†’ Multiple Types of Symbols
  • Simple scalar part โ†’ Character (e.g. ;, :, (), ...etc.)
  • Vector (collection of scalars) โ†’ String (e.g. '3', 'abc', ...etc.)

๐Ÿ“ Note: Characters are stored as numbers internally

  • ASCII Table / Unicode โ†’ Standard for character encoding โ—ฆ 'A' = 65, '1' = 49, '@' = 64
  • Python: Built-in function to find ASCII number โ†’ ord()
  • In C/C++: similar function is atoi() and ord()

Python Lists

  • Algorithm = A set of rules/steps used to solve a problem
  • Data Structure = A particular way of organizing data in computers
  • List is like 'arrays' we talk about in vectors โ—ฆ List โ†’ [ ] (contiguous memory) โ—ฆ Linked Lists โ†’ []->[]->[ ] (non-contiguous)
  • A list is a kind of collection โ†’ [...]
  • We can just use list inside the list โ†’ Nested Lists
  • Lists are Mutable โ†’ Once created we can change it further

List Operations

  • Strings are Immutable
  • len(x) โ†’ length of list
  • range() โ†’ for range
  • Concatenation is also possible with lists

List Slicing

a[:] # entire list a[3:] # from index 3 to end a[x:y] # from x (included) to y (not included) a[-1] # last element a[-2] # second last element