Salta al contenuto
Note per Studenti Introduction to Computer Science Report

Introduction to Computer Science

In questa pagina 10

This note covers the opening lessons of the Foundations of Computer Science course: the key questions (what is computer science, a computer, a program, programming, an algorithm), the historical and theoretical background, and the notion of algorithm with worked examples. The hardware side is in Computer ArchitectureModern computers follow the von Neumann model: a CPU (ALU, control unit, registers, cache) driven by a clock runs a fetch-decode-execute cycle on programs and data stored in the same memory; memory is a hierarchy from fast, small and volatile (registers, cache, RAM) to slow, large and persistent (SSD, disk, tape); CPU, memory and I/O talk through a bus made of data, address and control lines on the motherboard.Computer Architecture →, how programs are translated in Programming FundamentalsThe CPU only executes machine instructions (opcodes) of its own instruction set; assembly languages give them mnemonic names and an assembler translates them one-to-one, but they are CPU specific; high-level languages are CPU independent and are translated by a compiler (executable code is CPU specific) or run by an interpreter; compiled languages are generally more efficient, interpreted languages more portable, and Java aims at both.Programming Fundamentals →, and how data are encoded in Representation of InformationEverything in a computer is a sequence of bits, so each kind of information needs a coding. Natural numbers use positional notation in base 2 (conversion by repeated division by 2); signed integers use two's complement (range from minus 2 to the n minus 1 up to 2 to the n minus 1, minus 1), where negation is invert-all-bits-and-add-1, sums are plain binary sums and overflow is detected on the two top carries; hexadecimal groups bits in fours; fractions use fixed point or IEEE 754 floating point (sign, exponent in excess 127, 23-bit fraction) and are only approximate; characters are unsigned integers in a code table (ASCII, Unicode); images, video and sound are stored as numbers too (pixels, frame differences, samples).Representation of Information →.

1. First questions

The course starts from five questions: what is computer science, a computer, a program, programming, an algorithm. The slides open with a quote: computer science is no more about computers than astronomy is about telescopes. The computer is the tool; the subject is computation, i.e. which problems can be solved by a mechanical procedure and how efficiently.

2. Historical foundations

Hilbert and the decision problem

  • At the end of the 19th century mathematics began to question its own foundations.
  • David Hilbert proposed 23 fundamental mathematical problems to be solved during the 20th century.
  • Among them, the decision problemis there a universally valid method that determines with certainty the truth or falsity of any statement in formal logic.
  • Hilbert was confident: in mathematics there is no ignorabimus ("we will not know").

Turing and Church

  • About 1936 Alan Turing and Alonzo Church showed that such a universal procedure does not exist: "undecidable" propositions exist.
  • In doing so the concept of algorithm was introduced: a sequence of "elementary" operations making up a computational procedure.
  • In 1936 Turing introduced the Turing machine, a theoretical model of computation: an imaginary computer, a universal machine able to solve any computable problem.
  • His ideas laid the foundation for modern computers and artificial intelligence.

The Turing machine

A mathematical model describing how a computer operates. Components:

Component Role
Tape theoretically infinite, divided into cells; holds the input (a string of symbols)
Head reads and writes the symbol in the current cell, and moves right (R) or left (L)
Control unit current state qiq_i, set of states Q={q0,q1,…,qn}Q=\{q_0,q_1,\dots,q_n\}, tape alphabet Γ\Gamma, transition function δ\delta
Final states an accepting state (halt-accept) and a rejecting state (halt-reject)

The machine can read or write a symbol, move right or left (or not move, N), and change state until the computation is complete.

A transition rule has the form δ(qi,X)=(qj,Y,D)\delta(q_i, X) = (q_j, Y, D) where:

  • qiq_i is the current state and XX the symbol read on the tape;
  • qjq_j is the new state and YY the symbol to write;
  • D∈{L,R,N}D \in \{L, R, N\} is the movement direction (blank symbol shown as a square).

Why it matters (slide summary):

  1. It showed that many problems can be solved by following an algorithm (a step-by-step procedure turning an input into an output).
  2. It defined the concept of computability: what is computable (solvable by a machine) and what is not.
  3. It is the foundation of the theory of algorithms and of programming languages: every program is a sequence of elementary instructions, like the operations of a Turing machine.
  4. It is a theoretical model, but the foundation of modern computers: real ones are far more complex, yet reading, writing, memory and control derive from it.

Path shown on the slide: theoretical idea (1936) -> electromechanical machines and early calculators -> electronic circuits and microprocessors -> modern computers and complex software -> Internet, artificial intelligence and future technologies.

3. Theoretical foundations

Problem complexity

Not all problems are the same. Decidable problems are those for which an algorithm exists. Complexity classes group problems by the computational resources (time, space) needed to solve them. Some problems are practically difficult: theoretically solvable, but they need enormous resources.

From easiest to hardest:

Class Meaning Example on the slide
LOGSPACE logarithmic space, very little memory and time: the easiest problems
P polynomial time: efficient problems sorting a list of numbers, finding shortest paths
NP nondeterministic polynomial: verifying a solution is quick and easy, finding it is difficult Traveling Salesman Problem; factoring large integers (cryptography), not known to be in P
EXPTIME time grows exponentially with the input size
EXPSPACE exponential space: enormous time, even longer than the age of the universe universe simulation (EXPSPACE / EXPTIME)

Key characteristics stressed on the slide:

  • recognizing some problems is easy, solving them is not;
  • computational resources grow exponentially with the complexity;
  • some problems are easy to verify but hard to solve (find a solution);
  • some problems are efficiently solvable (polynomial time);
  • some need only logarithmic or relatively low space.

Complexity tells how "expensive" a problem is and helps choose the best approach.

Formal languages

A formal languagea precisely defined language in which the rules, or productions, determine which strings are valid is generated by a grammar, i.e. a set of grammatical productions.

Example over the alphabet Σ={a,b}\Sigma = \{a, b\} with productions

  • S→aSbS \to aSb
  • S→abS \to ab

Applying the first rule repeatedly and then the second gives abab, aabbaabb, aaabbbaaabbb, ... : the grammar represents an infinite set of well-formed strings defined by the rules.

The Chomsky hierarchy

Noam Chomsky classified languages into four categories according to the type of grammar generating them, from the most general to the most specific.

Type Language class Form of productions Example language Automaton
1 Universal (unrestricted) α→β\alpha \to \beta with α,β∈(V∪T)∗\alpha,\beta \in (V \cup T)^*, α\alpha contains at least one non-terminal strings are countably infinite, recognizable by a Turing machine Turing machine
2 Context-sensitive αAβ→αγβ\alpha A \beta \to \alpha \gamma \beta with γ≠ε\gamma \neq \varepsilon L={anbncn∣n≥1}L=\{a^n b^n c^n \mid n \ge 1\} (same number of a, b, c) Linear bounded automaton
3 Context-free A→γA \to \gamma with A∈VA \in V, γ∈(V∪T)∗\gamma \in (V \cup T)^* L={anbn∣n≥1}L=\{a^n b^n \mid n \ge 1\} (same number of a and b) Pushdown automaton
4 Regular A→aBA \to aB, A→aA \to a, A→εA \to \varepsilon with a∈Ta \in T, A,B∈VA,B \in V strings over {a,b}\{a,b\} ending with a Finite automaton

The three notions fit together: grammars define the rules that generate strings, languages consist of valid strings, automata are machines that recognize languages. The classification is used to describe and classify programming languages, compilers and parsers, regular expressions, and calculation and verification models.

Shannon: bits, circuits and information

Claude Shannon (1916-2001) gave the theoretical foundations of digital circuits (bits with values 0 and 1) and of information theory.

  • Logic gates work on bits (0 = FALSE/OFF, 1 = TRUE/ON):
A B AND OR
0 0 0 0
0 1 0 1
1 0 0 1
1 1 1 1

NOT inverts a single bit (0 -> 1, 1 -> 0).

  • Reliable transmission: sender -> encoding -> channel (with noise) -> decoding -> receiver. The objective is to transmit information correctly and efficiently. This leads from information theory to computer networks.

Information and entropy

  • Information is that which, for an observer facing a situation with at least two possible occurrences, overcomes uncertainty and resolves an alternative.
  • In communication with a finite alphabet of symbols, the information associated with a transmitted symbol is the reduction of the a priori uncertainty about it.
  • The information linked to a symbol (the uncertainty of an experiment) is

I=−log⁡2piI = -\log_2 p_i

where pip_i is the probability of that symbol being transmitted.

  • A bit is the amount of uncertainty in an experiment with only two equiprobable outcomes (check: p=1/2p=1/2 gives I=−log⁡2(1/2)=1I=-\log_2(1/2)=1).

The slide quotes Shannon on the name: von Neumann advised calling the uncertainty function "entropy", because it was already known by that name in statistical mechanics and because nobody knows what entropy really is.

4. Computers and programs

  • A computer (from Latin computare, to calculate) is an electronic device that processes data by following a sequence of instructions. It is good at repetitive tasks (calculations, text formatting), complex operations done quickly and accurately (controlling machinery, managing information systems), and realistic images and sounds in games.
  • Its capabilities depend not only on the hardware but also on the software it runs. Software consists of programs: sequences of instructions telling the computer how to perform specific tasks.
  • A computer is a machine that can process data (numbers, words, sounds, ...) and interact with external devices (monitor, keyboard, mouse, network, ...) by running programs.
  • Programs are sequences of instructions the computer can execute and decisions it can make, to perform a certain activity (formatting text pages, complex math, playing chess, ...).

At their core programs are made of simple operations and decisions:

Operations Decisions
read a value from memory if a value is negative, continue execution from a different instruction
add two numbers
output a character to a printer
display a pixel on the screen

Combining these elementary steps, computers perform remarkably complex tasks.

5. Programming

  • A program describes in great detail to the computer the sequence of steps required for a specific task.
  • Programming is the activity of designing, implementing, testing and maintaining a program.
  • Simply using a computer does not require programming (it uses programs written by others: games, web browser, e-mail, messaging, media player, word processing, graphics). A computer professional usually programs, though it is not the only skill needed.
  • Goal of the course: write simple programs, initially in Python and later in Java.

Why two languages

Python Java
Style highly interactive: write and run code immediately; ideal for experimentation and rapid prototyping needs more setup: the program is written completely, then translated into executable form
Reason it is an interpreted language it is primarily a compiled language
Learning easier to learn and use; hides many implementation details needs a deeper understanding of programming concepts; more explicit and structured
Errors rapid development, but some errors are only detected when the program runs many errors are detected before execution, so large programs are easier to maintain

Learning both shows different programming styles and the trade-offs of software development. An interpreted languagea language whose programs are executed by an interpreter that processes the source code or an intermediate representation at run time and a compiled languagea language whose programs are translated into executable code before execution are explained in Programming FundamentalsThe CPU only executes machine instructions (opcodes) of its own instruction set; assembly languages give them mnemonic names and an assembler translates them one-to-one, but they are CPU specific; high-level languages are CPU independent and are translated by a compiler (executable code is CPU specific) or run by an interpreter; compiled languages are generally more efficient, interpreted languages more portable, and Java aims at both.Programming Fundamentals →.

6. Computational thinking

  • Programming is a way of thinking. First goal: learn to program in Python. Second goal: learn to think like a computer scientist.
  • This way of thinking combines features of three disciplines:
    • mathematics: like mathematicians, computer scientists use formal languages to denote ideas (specifically computations);
    • engineering: they design things, assembling components into systems and evaluating trade-offs among alternatives;
    • natural science: they observe the behavior of complex systems, form hypotheses and test predictions.
  • The course starts from the most basic elements: how Python represents numbers, letters and words, arithmetic operations, and the vocabulary of programming (operator, expression, value, type), needed to follow the course, to communicate with other programmers and to use virtual assistants.

7. Algorithms

What a computer can solve

Two sample problems:

  1. Given a series of landscape photographs, which landscape is the most relaxing?
  2. After depositing 20,000 euros in an account earning 5% interest annually, how many years until the balance doubles?

The first cannot be solved by a computer: it is ambiguous for humans and computers alike, and cannot be rigorously solved unless a definition of "relaxing landscape" is given that uniquely compares two landscapes. A computer can only solve problems that could, in principle, also be solved manually: it is simply faster, does not make mistakes and does not get distracted. The second problem can certainly be solved manually, by doing some calculations.

Definition

An algorithm is the description of a method for solving a problem that

  • consists of a finite sequence of executable steps;
  • comes to a conclusion in a finite number of steps.

A computer can only solve problems for which an algorithm is known. The word comes from Al-Khwarizmi, a Persian mathematician of the 9th century AD.

Example: doubling an investment

Problem: deposit b0=20,000b_0 = 20{,}000 at annual interest i=5%i = 5\%; find the number of years nn for the balance to reach double the initial amount. More than one algorithm can solve a problem.

Algorithm 1: enumeration. Write the balance year after year until it reaches double the initial amount. Known data: b0=20000b_0 = 20000, i=5%i = 5\%; the balance of year nn follows from year n−1n-1:

bn=bn−1(1+i)b_n = b_{n-1}(1+i)

The table on the slide goes from 20,000.00 (year 0) to 41,578.56 (year 15); in year 14 the balance is 39,598.63 and in year 15 it is 41,578.56, so the answer is 15 years.

Algorithm 2: mathematical formulation. Cn=(1+i)nC0C_n = (1+i)^n C_0 and we need Cn≥2C0C_n \ge 2C_0:

(1+i)nC0≥2C0  ⇒  (1+i)n≥2  ⇒  n≥log⁡2log⁡(1+i)≈14.21(1+i)^n C_0 \ge 2C_0 \;\Rightarrow\; (1+i)^n \ge 2 \;\Rightarrow\; n \ge \frac{\log 2}{\log(1+i)} \approx 14.21

The enumeration algorithm, split into executable steps:

  • A. Current year n=0n = 0, current balance b0=20,000b_0 = 20{,}000.
  • B. Repeat steps C and D while the balance is less than 40,000, then go to step E (the flow chart below makes the test explicit: "balance < 40000?").
  • C. Add 1 to the current year.
  • D. New balance = current balance multiplied by 1.05 (add 5%).
  • E. The result is the value of the current year.

Properties of the method (what makes it an algorithm):

  • it gives precise instructions on what to do at each step and which step comes next;
  • it is executable: each step can be implemented concretely (if the rate used in step D depended on unknown future economic factors, the method would not be executable);
  • it terminates in finite time: at each step the balance increases by at least 1,000 units, so it finishes in fewer than 20 steps.

Flow charts

Simple algorithms are often shown as flow charts with these symbols:

Symbol Meaning
rounded box algorithm start / end
rectangle algorithm step
diamond binary decision (true / false branches)
arrow oriented arc (flow of control)

The investment algorithm as a flow chart: start -> A (year = 0, balance = 20000) -> B (balance < 40000?) -> if true: C (increment year), D (increment balance), back to B; if false: E (result is the value of the year) -> end.

Example: Sieve of Eratosthenes (276-196 BC)

Problem: list all primes ≤n\le n. A prime is a positive integer greater than 1 that is not the product of two smaller positive integers (it can be divided only by 1 and itself). Primes ≤25\le 25: 2, 3, 5, 7, 11, 13, 17, 19, 23. The RSA cryptography algorithm is based on prime numbers.

Idea: instead of testing each number for primality, eliminate the multiples of known primes.

Algorithm (step form, n>2n > 2):

  • A. Write the integers from 2 to nn in ascending order and set the support variable k=2k = 2.
  • B. Until k2≤nk^2 \le n, repeat steps C and D, then perform step E.
  • C. Remove all multiples of kk greater than kk (2k,3k,…,n2k, 3k, \dots, n) from the sequence.
  • D. Set kk to the next integer in the list that has not been removed.
  • E. End: the primes are the integers not removed.

Worked example with n=11n = 11:

  • A: 2 3 4 5 6 7 8 9 10 11, k=2k = 2.
  • B: k2=4≤nk^2 = 4 \le n. C removes 4, 6, 8, 10 -> 2 3 5 7 9 11. D: k=3k = 3.
  • B: k2=9≤nk^2 = 9 \le n. C removes 9 -> 2 3 5 7 11. D: k=4k = 4 (as shown on the slide).
  • B: k2=16>nk^2 = 16 > n, stop. E: primes are 2, 3, 5, 7, 11.

Flow chart: start -> A (list numbers 2..n, k←2k \leftarrow 2) -> B (k2≤nk^2 \le n?) -> true: C (remove multiples of kk), D (k←k \leftarrow next integer not removed), back to B; false: E (primes are the integers not removed) -> end.

Example: divide and conquer

Problem: find the maximum integer in a non-empty set N\mathcal{N} of integers.

Idea: if the set has one element only, that element is the max. Otherwise split the set into two sets A and B, find the max in A (maxA) and in B (maxB) with the same method, and return max⁡(maxA,maxB)\max(\text{maxA}, \text{maxB}).

Example on the slide with the set 3 7 2 3 8 1 5: it is split into A = (3, 7, 2) and B = (3, 8, 1, 5); halves are split again until single elements remain, and results are combined pairwise: A gives 7, B gives 8 (with 3 and 8 giving 8, and 1 and 5 giving 5), and the final max is 8.

Flow chart: start -> does N have one element only? true -> max -> end; false -> split N into A and B -> find max in A -> find max in B -> max = max(maxA, maxB) -> end. The two "find max" boxes apply the same algorithm again.

8. Advanced problems

Traveling Salesman Problem (NP-complete)

Given a set of cities and the distances between each pair, find the shortest path a traveling salesman must follow to visit all the cities once and return to the starting city. It is a typical case study of theoretical computer science and complexity theory (the slide notes it is not for this class).

Halting problem (undecidable)

Question: can we write a program that determines, for any program P and input I, whether P will eventually stop (halt) or run forever?

Answer: no. Alan Turing proved in 1936 that it is undecidable: no algorithm can solve it in general.

9. What algorithms are for

  • Identifying an algorithm is a prerequisite for solving a problem, with or without a computer.
  • Writing a program usually means translating an algorithm into a programming language.
  • Before writing a program one must identify and describe an algorithm.
  • Defining algorithms and measuring their efficiency are important topics of computer science and of this course.

10. Symbols used in the course slides

Icons used in the slides: common mistakes, productivity tips, quality tips, advanced topics, references to topics explored later, Java/Python syntax rules, news notes.

Versione ripasso

Core idea. Computer science is about problems, algorithms and computation; the computer is only the tool.

  • Decision problem (Hilbert): decision problemis there a universally valid method that determines with certainty the truth or falsity of any statement in formal logic. Turing and Church showed that no such universal procedure exists (about 1936).
  • Algorithm: a finite sequence of executable steps that reaches a conclusion in a finite number of steps. A computer can only solve problems for which an algorithm is known.
  • Turing machine (1936): tape, head (reads and writes, moves L, R or N), control unit with state qiq_i. Transition: δ(qi,X)=(qj,Y,D)\delta(q_i, X) = (q_j, Y, D), with D∈{L,R,N}D \in \{L, R, N\}.
  • Complexity classes, easiest to hardest: LOGSPACE, P (polynomial, efficient), NP (quick to verify, hard to find, e.g. Traveling Salesman), EXPTIME, EXPSPACE.
  • Chomsky hierarchy: type 1 unrestricted (Turing machine), type 2 context-sensitive (linear bounded automaton, anbncna^n b^n c^n), type 3 context-free (pushdown automaton, anbna^n b^n), type 4 regular (finite automaton).
  • Information of a symbol: I=−log⁡2piI = -\log_2 p_i. One bit is the uncertainty of an experiment with two equiprobable outcomes (p=1/2p=1/2 gives I=1I=1).
  • Computer: processes data and interacts with devices by running programs; its capabilities depend on hardware and software.
  • Programming: designing, implementing, testing and maintaining a program. The course uses Python first, then Java.

Worked algorithms.

  • Doubling an investment (20,000 at 5%): enumeration with bn=bn−1(1+i)b_n = b_{n-1}(1+i) gives 15 years; the formula n≥log⁡2log⁡(1+i)≈14.21n \ge \frac{\log 2}{\log(1+i)} \approx 14.21 gives the same answer.
  • Sieve of Eratosthenes: list 2 to nn, set k=2k=2; while k2≤nk^2 \le n remove the multiples of kk and set kk to the next integer not removed. The integers left are the primes (for n=11n=11: 2, 3, 5, 7, 11).
  • Divide and conquer, maximum: one element is the maximum; otherwise split the set, find both maxima and return max⁡(maxA,maxB)\max(\text{maxA}, \text{maxB}).

Not solvable or not feasible in general: the Halting problem (undecidable, Turing 1936); the Traveling Salesman Problem (NP-complete); a "most relaxing landscape" (ambiguous, no definition).

Common mistakes: confusing computer science with computers; calling an NP problem impossible (it is only not known to be in P); treating an undecidable problem as merely hard; running an ambiguous problem without a precise definition.

Teoria collegata