Tamil Nadu HSE First Year Computer Science cheat sheet
Tamil Nadu HSE First Year Computer Science · Keep the key ideas within reach.
Fundamentals of Computers and Number Systems
A computer is an electronic device that accepts data as input, processes it under stored-program control, and produces information as output; the IPO (Input-Process-Output) cycle plus storage describes any computer system.
Generations: first (vacuum tubes, machine language), second (transistors, assembly/COBOL/FORTRAN), third (integrated circuits, keyboards/monitors, multiprogramming), fourth (microprocessors, VLSI, GUI, networks), fifth (ULSI, AI, parallel processing, natural language).
Memory units are powers of 1024: 1 KB = 2^10 bytes, 1 MB = 2^20 bytes, 1 GB = 2^30 bytes, 1 TB = 2^40 bytes.
Decimal to binary: repeatedly divide by 2 and read remainders bottom-up; e.g. 25 = 11001. Decimal fraction to binary: repeatedly multiply the fraction by 2 and read integer parts top-down.
Binary to octal: group bits in threes from the radix point; binary to hexadecimal: group in fours. Pad with leading or trailing zeros as needed (e.g. 11010110 = 326 octal = D6 hex).
Two's complement of an n-bit number: invert all bits and add 1. Range of signed n-bit values is -2^(n-1) to 2^(n-1) - 1; an 8-bit signed byte spans -128 to +127.
BCD encodes each decimal digit separately in 4 bits, so 59 = 0101 1001; unlike pure binary it wastes the codes 1010-1111.
ASCII uses 7 bits (128 characters); ISCII is the Indian standard for Devanagari and other Indic scripts; Unicode assigns a unique code point to every character across languages.
Boolean Algebra and Logic Gates
Basic gates: AND (Y = A·B, output 1 only when all inputs are 1), OR (Y = A + B, output 1 when any input is 1), NOT (Y = A', the complement).
Universal gates are NAND and NOR: each alone can implement AND, OR and NOT, so any Boolean function is realisable from either one.
XOR: Y = A'B + AB' = A ⊕ B, output 1 for an odd number of 1 inputs; XNOR is its complement and equals 1 for even parity.
Boolean identities: A + 0 = A, A·1 = A, A + 1 = 1, A·0 = 0, A + A = A, A·A = A, A + A' = 1, A·A' = 0, (A')' = A.
Laws: commutative (A+B = B+A), associative, distributive (A(B+C) = AB + AC), absorption (A + AB = A), De Morgan: (A+B)' = A'·B' and (AB)' = A' + B'.
A half adder has inputs A, B and outputs Sum = A ⊕ B and Carry = A·B; a full adder adds a carry-in and gives Sum = A ⊕ B ⊕ Cin, Cout = AB + Cin(A ⊕ B).
NAND is called a universal gate because NAND(A,A) = A' (NOT), NAND followed by NOT gives AND, and NOT of NAND(A,B) gives OR.
A Karnaugh map groups 1s in blocks of 1, 2, 4 or 8 adjacent cells (including wrap-around edges) to obtain a minimal sum-of-products expression; larger groups eliminate more variables.
Introduction to Programming and Python Basics
An algorithm is a finite, unambiguous sequence of steps; a flowchart uses standard symbols - oval for start/stop, parallelogram for input/output, rectangle for process, diamond for decision.
Python is interpreted (byte-compiled then executed by the PVM), dynamically typed, case-sensitive, and uses indentation instead of braces to delimit blocks.
Keywords are reserved words (e.g. if, else, for, while, def, class, import, return, True, False, None) and cannot be used as identifiers; identifiers may contain letters, digits and underscore but cannot start with a digit.
Immutable core types: int, float, complex, bool, str, tuple. Mutable: list, dict, set. type(x) reports the class; int('12') and str(12) perform conversions.
Operators: // is floor division (7 // 2 = 3, -7 // 2 = -4), % is remainder, ** is exponentiation, / always yields a float. Python has no ++ or -- operator.
input() always returns a string, so numeric input needs int(input()) or float(input()); print() separates arguments by a space and ends with a newline by default.
Comments begin with # and run to end of line; triple-quoted strings serve as multi-line docstrings, accessible through function.doc.
Numeric literal forms: 0b1010 (binary), 0o17 (octal), 0x1F (hex), 1_000_000 (underscore separators), 1.5e3 (float), 2+3j (complex).
Control Structures and Functions
if/elif/else tests conditions top-down and executes only the first true branch; indentation, not parentheses, defines the block body.
while loops test the condition before each iteration and may run zero times; for loops iterate over any iterable (range, string, list, tuple, dict, file).
range(stop) yields 0..stop-1; range(start, stop) starts at start; range(start, stop, step) increments by step and counts down when step is negative.
break exits the innermost loop immediately; continue skips to the next iteration; the optional else clause of a loop runs only if the loop finished without break.
def name(parameters): defines a function; a bare return or no return yields None. Positional arguments bind by order, keyword arguments by name; defaults must follow non-default parameters.
A function's local names live in its own namespace and vanish on return; global variables are read freely but need the global statement to be rebound inside a function.
Recursion is a function calling itself; it needs a base case to terminate, e.g. factorial(n) = 1 if n <= 1 else n * factorial(n-1).
lambda x: x*2 creates an anonymous one-expression function; map, filter and sorted(key=...) commonly accept such callables.
Strings, Lists, Tuples and Dictionaries
Strings are immutable sequences of Unicode characters; indexing s[i] and slicing s[start:stop:step] return new strings, and negative indices count from the end (-1 is the last character).
String methods return new objects: upper(), lower(), strip(), split(sep), join(iterable), replace(old, new), find(sub) (returns -1 if absent), count(sub), startswith(), endswith().
Lists are mutable, ordered sequences: append adds one item, extend adds items from an iterable, insert(i, x) places before index i, pop(i) removes and returns, remove(x) deletes the first equal value.
List slicing can assign or delete: nums[1:3] = [9] replaces two elements with one; del nums[0] removes the first; sorted(list) returns a new list, list.sort() sorts in place.
Tuples are immutable and written with parentheses (a single item needs a trailing comma: (5,)); they can hold heterogeneous data and are unpacked as a, b = (1, 2).
Dictionaries map unique, hashable keys to values: d[key] raises KeyError if absent, whereas d.get(key, default) returns the default; keys must be immutable, so lists cannot be keys.
Dict methods: keys(), values(), items() return views for looping; del d[k] or d.pop(k) removes an entry; in tests key membership.
A list comprehension [expr for x in iterable if cond] builds a list in one expression; a generator expression uses parentheses and yields items lazily.
Computer Organization and Architecture
Von Neumann architecture stores instructions and data in the same memory and fetches them sequentially; the fetch-decode-execute cycle is driven by the program counter and instruction register.
CPU components: ALU performs arithmetic and logic, the control unit decodes instructions and issues signals, and registers (PC, IR, MAR, MBR, accumulator) hold intermediate state.
The system bus carries three groups: address lines select a memory location, data lines move contents, and control lines carry read/write and clock signals.
Memory hierarchy by speed and cost: registers, cache (L1/L2/L3), main memory (RAM), then secondary storage (SSD, magnetic disk, optical); RAM is volatile, ROM is non-volatile.
Cache exploits locality of reference (temporal and spatial); a cache hit is faster than a miss, and miss penalty is filled from lower levels.
Addressing modes include immediate (operand in instruction), direct (operand address given), indirect (address stored in memory) and register (operand in a register).
Instruction cycle stages: fetch the instruction at PC, increment PC, decode opcode, fetch operands, execute, and store the result.
RISC favours many simple fixed-length instructions and heavy pipelining; CISC favours complex variable-length instructions that may take multiple cycles.
Operating Systems and Data Communication
An operating system manages processes, memory, files and devices, and offers the user interface; it acts as an intermediary between programs and hardware.
Process states: new, ready, running, waiting (blocked) and terminated; the scheduler moves a process from ready to running, and an interrupt returns it to ready.
Scheduling algorithms: FCFS (simple, convoy effect), SJF (minimum average waiting time but needs burst prediction), round robin (time quantum, preemptive), priority.
Memory management uses paging (fixed-size frames) and segmentation (variable logical units); virtual memory maps logical addresses to physical frames via page tables.
Deadlock needs four simultaneous conditions: mutual exclusion, hold and wait, no preemption, circular wait; prevention breaks at least one condition.
Data communication modes: simplex (one direction only), half duplex (both directions but not at once), full duplex (both simultaneously).
Network topologies: bus, star (central hub, single point of failure), ring, mesh (redundant, costly); LAN is local, WAN spans large distances.
Transmission media: twisted pair and coaxial cable (guided); radio, microwave and satellite (unguided). Bandwidth is capacity in Hz or bps; a protocol defines syntax, semantics and timing.
Ethics, Cyber Security and Emerging Technologies
Computer ethics covers honesty in data, respect for privacy, avoidance of plagiarism and software piracy, and responsible use of shared resources.
Cybercrime categories include hacking, phishing, identity theft, cyberstalking, ransomware and denial-of-service attacks; phishing deceives users into revealing credentials.
Malware types: virus (attaches to host files), worm (self-replicating over networks), trojan (disguised as legitimate), spyware (secretly collects data), ransomware (encrypts and demands payment).
Security defences: strong unique passwords with multi-factor authentication, firewalls, antivirus updates, encryption (symmetric and public-key), digital signatures and regular backups.
A digital signature uses the sender's private key to sign and the public key to verify, giving authentication and integrity; encryption alone gives confidentiality.
The IT Act 2000 (India) legally recognises electronic records, digital signatures and cyber offences; CERT-In coordinates national incident response.
Emerging technologies: cloud computing (IaaS, PaaS, SaaS), IoT (networked sensors), AI and machine learning, blockchain (distributed immutable ledger), big data and 5G.
AI ethics concerns bias in training data, transparency of decisions, accountability, and the impact of automation on employment and privacy.
Problem Solving and Algorithmic Thinking
Problem-solving steps: understand the problem, identify inputs and outputs, design the algorithm, code it, test with normal, boundary and invalid data, then document.
Pseudocode uses plain-language control words (READ, PRINT, IF…THEN…ELSE, WHILE…ENDWHILE) and is independent of any programming language syntax.
A flowchart decision symbol (diamond) has one entry and two exits (Yes/No); process boxes have one entry and one exit, so they cannot branch.
Tracing an algorithm means manually recording variable values line by line; it is the standard way to verify loops terminate and produce correct output.
Searching: linear search examines each element in turn (works on unsorted data, O(n)); binary search halves a sorted list each step (O(log n)) and needs the data sorted.
Sorting: bubble sort repeatedly swaps adjacent out-of-order pairs; selection sort repeatedly selects the minimum of the unsorted part; both are O(n^2).
Swapping two variables without a temporary uses a, b = b, a in Python; with a temporary use t = a; a = b; b = t.
Test data classes: valid (normal expected input), boundary (first, last, empty, maximum) and invalid (wrong type or out-of-range) to confirm error handling.
Python Data Handling and File Operations
File modes: 'r' read (default, error if missing), 'w' write (truncates or creates), 'a' append, 'r+' read and write, and adding 'b' gives binary mode.
open() returns a file object; use read(), readline(), readlines() or iterate the object line by line, and always close() or use a with block to flush and release it.
The csv module reads and writes comma-separated records; csv.reader yields lists of fields, csv.writer writes rows, and the delimiter can be changed.
The pickle module serialises Python objects to bytes (pickle.dump/load) and restores them exactly, unlike text formats that store only characters.
The struct module packs Python values into fixed binary formats (e.g. 'i' for a 4-byte integer) and unpacks them back, useful for binary file records.
Exceptions are handled with try/except/else/finally; except catches a named error type, else runs when no exception occurred, and finally always runs for cleanup.
Common exceptions: ZeroDivisionError, ValueError (right type, bad value), TypeError (wrong type), IndexError, KeyError, FileNotFoundError, NameError.
raise re-raises or creates an exception; a custom exception subclasses Exception, e.g. class MyError(Exception): pass.
Python Modules, Packages and Standard Library
import math loads a module; from math import sqrt binds a name directly; import numpy as np creates an alias; import math as m renames the module locally.
math functions: math.sqrt(x), math.pow(x, y) (float), math.fabs(x), math.ceil(x), math.floor(x), math.pi, math.e; math.gcd(a, b) gives the greatest common divisor.
The random module: random.random() gives [0.0, 1.0), randint(a, b) includes both ends, randrange(start, stop, step) excludes stop, choice(seq) picks one item, shuffle(lst) permutes in place.
The statistics module provides mean(), median(), mode(), and stdev() for sample standard deviation.
A package is a directory of modules containing an init.py file; dotted names such as package.module reach nested modules.
The standard library covers os (files, paths, environment), sys (argv, exit, version), datetime (date, time, timedelta), and json (dumps/loads for text interchange).
The dir(module) function lists a module's names; help(obj) shows documentation; a module's name equals 'main' when run directly, which guards test code.
Installing third-party packages uses pip install name; they are imported exactly like standard-library modules once installed.
Python OOP and Advanced Constructs
class Name: defines a class; init(self, ...) initialises a new instance, and self is the implicit reference to that instance in every method.
Instance attributes belong to one object (self.x); class attributes are shared by all instances and are read through the class or any instance.
Inheritance: class Child(Parent) reuses parent methods; the child can override a method, and super().init(...) calls the parent constructor.
Encapsulation hides state behind methods; Python marks non-public names with a leading underscore by convention, and name mangling uses a double underscore.
Polymorphism lets different classes answer the same method call differently; it works through overriding and duck typing rather than declared interfaces.
Special (dunder) methods customise behaviour: str for print, len for len(), repr for debugging, eq for ==.
A generator uses yield to produce values lazily and keeps its state between calls; it is exhausted after one full pass.
Decorators wrap a function to add behaviour without editing it; @staticmethod and @property are built-in decorators used inside classes.
Python Strings in Depth
String literals: single or double quotes are equivalent; triple quotes span lines; a raw string r'\d' keeps backslashes literal; f'{x}' inserts expressions.
Escape sequences: \n newline, \t tab, \ backslash, ' quote, and \uXXXX a Unicode code point.
s[i] indexes one character; s[a:b] slices from a up to but not including b; s[::-1] reverses a string; s[::2] takes every second character.
Membership and comparison: 'a' in s tests a substring; == compares content, is compares identity; strings compare lexicographically by character code.
Formatting: '{} and {}'.format(a, b), '{0}{1}'.format(x, y) with positional indexes, and f-strings, which evaluate expressions at run time.
The join method is the efficient concatenator: ', '.join(['a', 'b']) gives 'a, b'; repeated + in a loop creates many intermediate strings.
Case and test methods: isalpha(), isdigit(), isalnum(), isspace(), isupper(), islower() return booleans; title() and capitalize() change case.
Strings are immutable, so s[0] = 'X' raises TypeError; build a new string with slicing and concatenation instead.
Python Lists, Tuples, Sets and Dictionaries
List operations: len(lst), max/min on comparable items, sum of numbers, lst.count(x), lst.index(x) (raises ValueError if absent), and lst.reverse() in place.
Concatenation and repetition: [1, 2] + [3] gives [1, 2, 3]; [0] * 3 gives [0, 0, 0]; nested lists need care because repetition copies references.
Copying: b = a aliases the same list; b = a[:] or b = list(a) makes a shallow copy; copy.deepcopy(a) copies nested structures fully.
A set is an unordered collection of unique hashable items: {1, 2}, set(); operations include union (|), intersection (&), difference (-) and symmetric difference (^).
Dictionary iteration: for k in d loops keys; for k, v in d.items() unpacks pairs; d.update(other) merges; dict comprehensions build maps as {k: v for ...}.
Nested structures: a list of dictionaries is the usual record table; access one field as records[i]['name'].
Tuple uses: returning multiple values, fixed records, and dictionary keys, since tuples are hashable when all their items are.
The in operator tests membership in lists, tuples, sets and dict keys in O(1) for sets and dicts but O(n) for lists.
Number Systems: Conversions and Arithmetic
Positional value: in base b, the digit at position i (from the right, starting at 0) is worth digit × b^i; 1011 in binary equals 1×8 + 0×4 + 1×2 + 1×1 = 11.
Any base to decimal: multiply each digit by its place value and add; e.g. 2F hex = 2×16 + 15 = 47.
Decimal to any base: divide repeatedly by the target base and read remainders from last to first; 47 in hex is 2F.
Binary addition rules: 0+0=0, 0+1=1, 1+1=10 (write 0, carry 1), 1+1+1=11 (write 1, carry 1).
Subtraction by two's complement: take the two's complement of the subtrahend and add; discard the final carry out of the most significant bit.
Octal to binary and back: each octal digit maps to exactly three bits; hexadecimal maps to exactly four bits, so conversion passes through binary.
A binary number with n bits represents 2^n distinct values; unsigned range is 0 to 2^n - 1, signed two's complement is -2^(n-1) to 2^(n-1) - 1.
Character codes: ASCII 65 = 'A', 97 = 'a', 48 = '0'; Unicode extends this with code points for all scripts, including Tamil.
Logic Circuits and Combinational Design
Truth tables list every input combination (2^n rows for n inputs) with the corresponding output, fully defining a combinational circuit.
Sum-of-products (SOP) form ORs together AND terms for each row where the output is 1; product-of-sums ANDs OR terms for rows where the output is 0.
De Morgan converts NAND to negative-OR and NOR to negative-AND: (AB)' = A' + B' and (A+B)' = A'B'.
An encoder converts 2^n input lines into an n-bit code; a decoder does the reverse, activating one of 2^n outputs from an n-bit input.
A multiplexer selects one of several data inputs using select lines; a demultiplexer routes one input to one of several outputs.
A flip-flop is a bistable memory element: the SR latch holds a bit, the D flip-flop stores the input on a clock edge, and the JK flip-flop toggles when J = K = 1.
A sequential circuit's output depends on present inputs and stored state, unlike a combinational circuit, whose output depends only on present inputs.
Parity: an even-parity bit makes the total count of 1s even; XOR of all data bits gives even parity, XNOR gives odd parity.
Python Control Flow Patterns
Nested loops: the inner loop completes fully for each outer iteration; total iterations equal the product of the two counts.
Accumulator pattern: initialise total = 0 before the loop and add inside it; counting uses count += 1; product uses result = 1.
Sentinel-controlled loop: read input, test it against a stop value, and process only while it differs, e.g. while n != -1.
A for loop over a string yields characters; over a dict it yields keys; over enumerate(seq) it yields (index, item) pairs.
zip(a, b) pairs elements position by position and stops at the shorter sequence; it is the standard way to walk two lists together.
Nested conditions can often be replaced by elif chains or by combining tests with and/or, which short-circuits: False and x never evaluates x.
Any non-zero number and any non-empty container is truthy; 0, 0.0, '', [], {}, None and False are falsy.
Loop counters must be updated inside while loops; forgetting the update causes an infinite loop, which break or a bounded for loop avoids.
Computer Networks and Internet Basics
The OSI model has seven layers: physical, data link, network, transport, session, presentation, application; TCP/IP condenses these into four.
IP addresses identify hosts; IPv4 uses 32 bits in dotted decimal (e.g. 192.168.0.1) and IPv6 uses 128 bits.
TCP is connection-oriented and reliable, with acknowledgements and retransmission; UDP is connectionless and faster but unreliable.
HTTP transfers web pages, HTTPS adds TLS encryption, FTP moves files, SMTP sends mail, and DNS resolves domain names to IP addresses.
A URL has the form scheme://host/path?query; the domain name is resolved by DNS before the browser connects to the server.
Bandwidth is the maximum data rate of a channel; latency is delay; a protocol is an agreed set of rules for format and order of messages.
LANs cover a room or building; WANs span countries; the internet is a network of networks joined by routers that forward packets by IP address.
Switching: circuit switching reserves a path for the whole call; packet switching splits data into packets routed independently, which is how the internet works.
Cyber Safety Practices and Digital Citizenship
Password hygiene: long unique passphrases, no reuse across sites, a password manager, and multi-factor authentication wherever offered.
Phishing indicators: mismatched sender domains, urgency, unexpected attachments, and links whose visible text differs from the real URL.
Safe browsing: check for HTTPS and the padlock, avoid pirated software, keep the OS and browser patched, and log out of shared machines.
Social media safety: restrict public personal data (address, school, phone), review privacy settings, and never share OTPs or passwords.
Backups follow the 3-2-1 rule: three copies, on two media types, with one off-site; backups are the reliable defence against ransomware.
Digital footprint: posts and metadata persist; the IT Act 2000 and later amendments criminalise identity theft, publishing obscene material and unauthorised access.
Netiquette: no flaming, respect copyright and cite sources, avoid spam and forwarding unverified claims.
Reporting: CERT-In and the National Cyber Crime Reporting Portal handle Indian incidents; preserve logs and evidence before cleaning a compromised system.
Emerging Technologies and Their Applications
Cloud service models: IaaS supplies virtual machines and storage, PaaS supplies a runtime and development tools, SaaS supplies finished applications over the web.
Cloud deployment types: public, private, community and hybrid; elasticity and pay-per-use are defining features.
IoT architecture: sensors and actuators at the edge, connectivity (Wi-Fi, Bluetooth, LoRa), cloud processing, and a user application; examples include smart agriculture and smart meters.
Artificial intelligence: machine learning learns patterns from data; supervised learning uses labelled examples, unsupervised learning finds structure, and reinforcement learning learns from reward.
Blockchain: a distributed ledger of hash-linked blocks, replicated across nodes, with consensus instead of a central authority; used for cryptocurrency and supply-chain tracking.
Big data is characterised by volume, velocity, variety, veracity and value; tools such as Hadoop and Spark process it in parallel.
5G offers high bandwidth and low latency, enabling remote surgery, autonomous vehicles and dense IoT deployments.
Augmented reality overlays digital content on the real world; virtual reality replaces it; both rely on sensors, displays and fast rendering.