Docsity
Docsity

Prepara i tuoi esami
Prepara i tuoi esami

Studia grazie alle numerose risorse presenti su Docsity


Ottieni i punti per scaricare
Ottieni i punti per scaricare

Guadagna punti aiutando altri studenti oppure acquistali con un piano Premium


Guide e consigli
Guide e consigli


Computational thinking primo parziale, Appunti di Programmazione e Tecnologie Web

Appunti su concetti base computational thinking e pseudocode

Tipologia: Appunti

2019/2020

Caricato il 26/12/2020

matildecoppoli
matildecoppoli 🇮🇹

4.4

(53)

21 documenti

1 / 31

Toggle sidebar

Questa pagina non è visibile nell’anteprima

Non perderti parti importanti!

bg1
30/09/20
COMPUTATIONAL THINKING
CT is the though process involved in formulating a problem and expressing its solution(s) in such a way
that a computer - human or machine - can effectively carry out. It is the mental activity for abstracting
problems and formulating solutions that can be automated. The process of recognising aspects of
computation in the world that surrounds us, and applying tools and techniques from Computer Science to
understand and reason about both natural and artificial systems and processes.
You have to formulate a problem so that a computer can carry out the solution. Both problems and
solutions need to be automated.
ALGORITHMIC THINKING
Algorithms are sequences of basic steps a non-intelligent being can blindly follow to solve a problem.
They need to be basic because they must been followed by a non-intelligente being. Computers are non-
intelligent beings. Basically a computer is as intelligent as the person who has programmed it.
Algorithms need to follow a protocol. We must assure that our algorithms is solid to exceptions. The
evaluation is fundamental to understand if our solution is correct.
PATT ERN M ATCH IN G
Often problems are essentially the same as something you have seen in a different situation. So we might
have a solution that works for a variety of similar problems. This is called generalization. If you apply
pattern matching and generalization you can realize that some letters are more common than others, so
we might order the letters on a frequency basis. You have to go for the worst case.
FOUR PILLARS OF CT
Decomposition
Pattern matching
Abstraction
Algorithm
6/10/20
LOGICAL AND ALGORITHMIC THINKING
Critical and logical thinking are at the basis of computer science. Applying logic is a way of developing
and testing an hypothesis.
Humans have an innate understanding of both logic and algorithms, but they are both mathematical
concepts in nature. Hence, they have their own set of rules, procedures and definitions.
LOGICAL THINKING
Logic is a system to distinguish between correct and incorrect arguments. Logic includes a set of principles
that, when applied to arguments, allow us to demonstrate what is true.
EX:
1. Socrates is a man
2. All men are mortal
3. Therefore, Socrates is mortal
Applying logic is a way of developing and testing an hypothesis.
1
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f

Anteprima parziale del testo

Scarica Computational thinking primo parziale e più Appunti in PDF di Programmazione e Tecnologie Web solo su Docsity!

COMPUTATIONAL THINKING

CT is the though process involved in formulating a problem and expressing its solution (s) in such a way

that a computer - human or machine - can effectively carry out. It is the mental activity for abstracting

problems and formulating solutions that can be automated. The process of recognising aspects of

computation in the world that surrounds us, and applying tools and techniques from Computer Science to

understand and reason about both natural and artificial systems and processes.

You have to formulate a problem so that a computer can carry out the solution. Both problems and

solutions need to be automated.

ALGORITHMIC THINKING

Algorithms are sequences of basic steps a non-intelligent being can blindly follow to solve a problem.

They need to be basic because they must been followed by a non-intelligente being. Computers are non-

intelligent beings. Basically a computer is as intelligent as the person who has programmed it.

Algorithms need to follow a protocol. We must assure that our algorithms is solid to exceptions. The

evaluation is fundamental to understand if our solution is correct.

PATTERN MATCHING

Often problems are essentially the same as something you have seen in a different situation. So we might

have a solution that works for a variety of similar problems. This is called generalization. If you apply

pattern matching and generalization you can realize that some letters are more common than others, so

we might order the letters on a frequency basis. You have to go for the worst case.

FOUR PILLARS OF CT

**- Decomposition

  • Pattern matching
  • Abstraction**
  • Algorithm

LOGICAL AND ALGORITHMIC THINKING

Critical and logical thinking are at the basis of computer science. Applying logic is a way of developing

and testing an hypothesis.

Humans have an innate understanding of both logic and algorithms, but they are both mathematical

concepts in nature. Hence, they have their own set of rules, procedures and definitions.

LOGICAL THINKING

Logic is a system to distinguish between correct and incorrect arguments. Logic includes a set of principles

that, when applied to arguments, allow us to demonstrate what is true.

EX :

  1. Socrates is a man
  2. All men are mortal
  3. Therefore, Socrates is mortal

Applying logic is a way of developing and testing an hypothesis.

DEDUCTIVE ARGUMENT

So one way to do this is the deductive argument that is the strongest form of reasoning because its

conclusion necessarily follows from its premises. They need strong premises. So you can express the form

of an argument by substituting symbols for objects: ex: A is B; All Bs are C; therefore, A is C.

The problem is when you substitute something true for symbols, because the reality is so different so you

don’t have guarantee that one method can always be applied, so you generalize. So we have to be very

careful when we abstract. So when you use deductive argument you have to be sure that your premises

are always true.

INDUCTIVE ARGUMENT

It’s used most of the time in mathematics. The premises of an inductive argument are not unquestionably

true , rather we have some level of confidence in them. When you have an inductive argument probability

is involved.

We have to figure out a problem, abstract it, think about a solution, find general steps and translate those

steps in another language. But if you abstract the problem and the solution in a wrong way the program

couldn’t work.

EX:

  1. A bag contains 99 red balls and 1 black ball
  2. 100 people each draw 1 ball from the bag
  3. Sarah is one of those 100 people
  4. Therefore, Sarah probably drew a red ball

COMPUTERS AND REASONING

The answer a computer gives is only as valid as its reasoning. So when you get an answer from a

computer that you or somebody else did the computer is only automating your reasoning, thus make sure

that:

  • The reasoning is valid
  • You give the computer reliable input
  • You know how to interpret the output

BOOLEAN LOGIC

Computers are binary in nature and deal well with black and white issues. Hence, we need a logic that

maps well onto this way of thinking. So when you have a complex problem you have to narrow it down to

basic steps. In this way they can be expressed in a boolean way (true or false). Statements in Boolean

logic are called propositions.

  • Propositions can have one value at any one time: they cannot be either true and false : they must be

true or false

  • Propositions must have clear and unambiguous meaning
  • It is possibile to combine individual propositions into a single more complex one: to do that you use

logical operators

AND

The first logical operator is the conjunctive operator (AND): symbol ^

A and B = true only if both A and B are true at the same time

They need to be all true, otherwise is one is false also the others are false

OR

Disjunctive operator , symbol: v

A or B = true if A or B or both are true

PROGRAM VS ALGORITHM

A program is an algorithm that has been customized to solve a specific task under a specific set of

circumstances using a specific language. Algorithm is general, whereas programs are specific.

EXAMPLE OF AN ALGORITHM

If you want to automate the game of tic tac toe:

1. Game is started 2. Begin loop: 1. Prompt player to choose a square 2. If chosen square is not occupied, then put player’s symbol in that square 3. Check board to see if a row has been achieved 4. If a row is been achieve then game is won (exit condition) 5. If a row has not been achieved and no squares are available then game is drawn (exit condition) 6. Switch to other player (you go back to line 1 and you restart the loop) 3. Exit loop if game is won or game is drawn 4. Display message “game over”

All the operations in the loop are on the right and this is called invention. This algorithm is executed in

sequence one instruction at the time.

In the first line you have a variable that it is initialized (game). In the second line you have the starting

point of a loop (iteration). The indentation shows what’s inside the loop.

LOGICAL THINKING, PUZZLES, LOGIC AND PATTERNS

One game similar to sudoku is “Cut hives” that consists of a block of hexagons, with different areas

marked out using thicker lines. There are two rules that must hold of a completed block.

You have 2 riles:

- Each area must contain the numbers from 1 up to the number of hexagons in the area - No number can be next to the same number in any direction, along a shared edge

The first thing to do to right an algorithm is to understand the rules. First rule to solve the game is looking

for single hexagons (starting from the smaller ones). To solve the game we have been using deduction

where we work from known facts and the rules of the puzzle to give us new facts.

As you do more puzzle, you get experienced so you start to solve the puzzles in a different way.

You apply:

- Pattern matching : against situations you have seen before - Generalisation : widening the situations you pattern match against

RULES

We can start define new rules for “Cut hives”

  1. If an area has only 1 hexagon, THEN that hexagon holds the number 1

If we have an area of size two, with one hexagon filled with a 2 then the other hexagon must be 1 and

vice versa

  1. If an hexagon in an area of size two holds a 1 or a 2 THEN the other hexagon holds the other number

We can further generalise this rule by using symbols :

We use x ̅

in the diagram to mean the other number that the x isn’t this time. So if x is 1 then x ̅

is 2, and if

x is 2 then x ̅

is 1.

  1. If a hexagon is surrounded by an area of size four, with only three of the four hexagons touching it THEN

the fourth hexagon holds the same number as the surrounded hexagon.

FROM PUZZLES TO ALGORITHMS

Most people who do puzzles don’t bother to write down the rules they derive and use. They just

remember something that worked in the past and apply it when the chance arises without much thought.

Computer Scientists like to write things like that down though. Why is it a good idea?

Well, for one thing you can use them to teach other people how to do the puzzles without them having

to work it all out for themselves. It is easy to have a false recollection of a rule that worked in the past,

or for someone who has learnt it to misunderstand the detail. Writing a precise version down helps avoid

this kind of faulty reasoning.

Here we aren’t just using logical thinking as we become better and better at doing puzzles. We pattern

match the rules against the current situation to know which to apply.

Generalisation goes hand in hand with abstraction: we are hiding detail about other parts of the puzzle to

make things easier to think about and to make the rules as general as possible.

If you focus too much on the instance you can come out with a solution that is valid only for that instance

and this is one of the main problem when you write an algorithm. Critical thinking means question

yourself.

THE PILLARS OF CT

1. DECOMPOSITION

Decomposition is the process of taking a complex problem and breaking it into more manageable sub-

problems. By solving each potentially simpler sub-problem, we can put the solutions together to arrive at

a solution to the original complex problem.

Decomposition is related to the so called divide and conquer strategy that is used many times outside

computing. Divide and conquer implies decomposition even if decomposition doesn’t imply divide and

conquer because there are other strategies. Market segmentation is a real example of divide and conquer.

EXAMPLE: take a photo of central park from the empire state building

Probably you have a sequence of steps to solve this problem. You can narrow the task into basic tasks.

When you divide a problem into sub-problems you must end up with an hierarchy of tasks and this

hierarchy is a tree that has only one parent. Then you start solve problems from the bottom: so it’s a

bottom-up solution. The tree is an important structure that is useful for computational thinking.

Solving sub-problem means putting together all the sub-problems solutions in order to solve the bigger

problem.

  • Divide phase : with decomposition you end up with a number of subproblems that it turn can be divided

into other subproblems until you can solve them

  • Conquer phase : the individual solutions of the subproblems are put together to get the final solution

RECURSION

It’s a technique used to simplify a problem. It’s a technique to identify a strategy. It defines a solution to

a large, complex problem in terms of smaller, smaller problems of the same form as the original problem.

It’s not a simple subproblem that can have a differente form from the original problem. A function that

calls itself several times to solve a problem is an example of recursion.

REPRESENTATION AND ABSTRACTION

It means figuring out what characteristics of the problem are important and using these to create a

representation of the problem to be solved. When you abstract you create a representation of that

abstraction. Unimportant characteristics can be filtered out and ignored.

PATTERN MATCHING/RECOGNITION

It entails finding similarities or shared characteristics within or between problems. It allows us to use

the same solution for each occurrence of the pattern. When you find similarities the abstraction is the

same so you can use the same solution. An example is data compression : it’s the same of when you create

an archive.

ALGORITHM

An example of an algorithm is how to make tea.

You have a start point that is represented by a circle , then you have a narrow that indicates the other

passages until the end point also represented by a circle. When you develop an algorithm and you find a

solution fort that algorithm the solution is only valid for the context that you are considering.

Inputs and outputs are specified with parallelograms. You use the diamond when you have to take a

decision that is binary : you use boolean logic. The variable is written with another font in order to

specify it.

FLOWCHART

A Flowchart is a diagram that represents instructions and sequence of execution.

ALGORITHMS AND FLOWCHARTS

FINDING THE LARGEST VALUE

The first problem is finding the largest value that means a series of numbers not sorted (in ordine

crescente) and we have to return the largest value. To solve the problem you might skim through numbers

by selecting the largest digit on the left. Then compare only the numbers with the largest digit and pick

up the largest number overall. This is simple when you have a small series of number, otherwise it’s simple

to use an algorithm. So to provide a solution with a computer we need to use binary operations , such as

comparisons , for ex (23 > 12 true/false?). then we have to take an action in answer this problem. So how

do we solve this problem computationally?

Firstable we need to have 2 variables: we define one in red and one in green. The red one is the current

max and the green one is the current value we are comparing to the max. The current max is the first

element in the list. So we start scamming from the first element.

Ex

The current max is 52

The value we are comparing is 34

Is 34>52? No, so we keep 52 as the max

Then you continue and you compare 52 with 78

Is 78 > 52? Yes so you update the current max that becomes 78

Now you compare 78 with 12

Is 12 > 78? No, so we don’t update the max

Then you go on:

Is 24 > 78? No, so you don’t update the max

Is 90>78? Yes, so in this case you update the number of max and now the max is 90

Is 87 > 90? No, so we don’t update the max

Is 99>90? Yes, so you update the max with 99

Is 45 > 99? No, so the largest number is 99

So the steps of this algorithm are:

  1. We define a variable as current max and we set it to the first item in the list
  2. We iterate over the sequence: this is called a loop : a loop is defined by a variable moving from a

certain starting point to an end point. With a loop you decide the starting point, the ending point and

the spec.

  1. For each iteration we compare the current max with the current value
  2. If the current value is larger than the current max then
    1. We update the current max with the current value
  3. We stop when we reach the end of the sequence: exit loop
  4. Return current max

The exit loop is within the loop because the instruction is within the loop.

FLOWCHART

With a flow chart

  • Oval : starting point
  • Parallelogram : input (list L of values)
  • Diamond : question (is L empty?) if yes the output is none so we stop

Is the answer is no we set 2 values: set current and max to the first element (rettangolo blu)

FLOWCHART: FINDING THE SMALLEST VALUE

The flowchart is similar to the previous one. You change the name of the variable: instead of calling it

max you call it min. Then the question is “is current < min?” Then we update min with current and then

it’s the same. Basically we change the question in the diamond. This is a straightforward application of

the largest to the smallest.

LINEAR SEARCH

We need to check if the number 90 is present in the given sequence.

You might skim through the numbers by looking for a match. The human eye is accustomed to find

patterns. Nevertheless, a computer can’t solve a problem like that. We need to provide a solution using

binary operations , such as comparisons (23 == 12? true / false). As we have done for finding the largest

value.

Find 90

How do we solve this problem computationally?

  1. We store the input x=
  2. We define a variable current value and we set it to the first item in the list
  3. We iterate over the sequence ← loop
  1. For each iteration we compare current value with x
  2. If the current value is equal to x then
    1. exit the loop and return true
  3. else update current value to the next item in the list (if any)
  4. Return false

FLOWCHART

The worst case is when the element isn’t there. Linear search is a very general algorithm that works for

every tipe of problems.

ANALYSIS OF COMPLEXITY

The complexity of an algorithm can be expressed as the number of steps it takes to solve the problem.

Complexity is usually expressed in terms of the size of the input. For instance, if an input sequence has n

items, we express the complexity of the linear search algorithm in terms of n.

If we want to be general we never think about the actual instance.

COMPLEXITY OF LINEAR SEARCH

For instance, how many basics steps does it take to find 90 in the following sequence?

BINARY SEARCH FLOWCHART

EX:

Length of the list: 17

Search x = 44

min = 1

max = len(L) = 17

mid= ⌊(max+min)/2⌋ = ⌊(17+1)/2⌋= 9

L(mid) = 37

is (37<44)?

true→

min = mid+1 = 10

mid =⌊(max+min)/2⌋=⌊(17+10)/2⌋= 13

is (79<44)?

false→

max = mid-1 = 12

mid = ⌊max+min)/2⌋= ⌊10+12/2⌋ = 11

is (56<44)?

false→

max = mid-1 = 10

mid = ⌊(max+min)/2⌋=⌊10+10/2⌋=

is (44 = 44)? Yes, so you stop

Linear search: 10 comparisons

Binary search: 4 comparisons

WORST-CASE

T

he worst case is that the sought element is not in the list.

COMPLEXITY OF BINARY SEARCH

Binary search has logarithmic running time → log

( n)

LINEAR SEARCH PSEUDOCODE

Input: list L of values; target value x

Output: true/false

for each item in L do

if item == x then

return true

return false

  • Constructs are underlined
  • Variables are not underlined

The key constructs are:

  • For each: loop
  • If then else: conditional
  • Return: exit loop and return output

BASIC OPERATIONS

VARIABLES AND COSTANTS

Variables can contain any type of value and can be updated during the execution of the algorithm.

When you decide a name for a variable you declare a variable, when you decide a value for a variable you

initialize it, if you change the value you update the variable.

Declare the variable (name of the variable) = initialize the variable (value of the variable)

Ex: sum = 0

Variable assignment

You can use left narrow or equal

x = 1 this means that the variable with name x is initialized with the name 1. If we set the variable to 1

we say that the variable has a type.

Variable type

  • (Numeri interi) integer : to - infinite to + infinite: x = 1 (variable assignment)
  • (Numeri a virgola mobile - decimali) float: x = 4,
  • String (token of text): x = “hippo”
  • Char (single character): x =‘a’
  • Boolean (true/false values): x = True (you must use capitol T or capitol F)

Constants are assigned as the variables but they never change during the execution of an algorithm.

Usually you use capitol letter to indicate constants

ARITHMETIC OPERATIONS

ARITHMETIC ASSIGNMENT OPERATIONS

This is called shortcuts

INCREMENTING/DECREMENTING A VARIABLE

THE POSTFIX INCREMENT

After the execution of this pseudocode

oldest = 32

age = oldest++

We have the following values assigned to the variables

oldest = 33

age = 32

Action Common symbol Example

Addition + 2+2 = 4

Subtraction - 2-3 = -

Multiplication (^) * 2*3= 6

Division / 4/2 = 2

Modulus (associated with

integers)

You use it to understand if the

number is even or odd (pari o

dispari)

mod

Power ** 4**2 = 16 (4^2)

Arithmetic assignment examples: Equivalent code:

age += 14 age = age + 14 (age = 1)

age -= 14 age = age - 14

age *= 14 age = age * 14

age /= 14 age = age / 14

age %= 14 age = age % 14

Examples Equivalent code

i++ i = i + 1

i— i = i - 1

i +=1 i = i + 1

i -=1 i = i - 1

G

iven a list L, L[i] returns the element stored in position (index) i of the list.

  • In pseudocode indexes go from 1 to n
  • In Python indexes go from 0 to n-

L = [10, 12, 15, 19, 2]

MANIPULATING LIST IN PHYTON

The first thing you can do is updating an element.

When you have “:” you access a range of number. For example: L[1:3]. This means that you’re accessing

the elements in position 1 and 2 because the last element is not considered if you don’t specify it.

To insert a number in a list you can use the method insert:

L.insert(1,3) where 1 is the position where you want to add the number and 3 is the number you want to

add.

CONDITIONALS

We can alter the flow of control (the order in which statements are executed) using either conditionals.

The conditional statements if, if-else and if-elif-else allow us to choose which statement will be executed

next. Each choice or decision is based on the value of a boolean expression (also called the condition).

So you have a boolean condition and if this condition is true then you do something. Else you do something

else.

THE IF STATEMENT

If we have a code that we sometimes want to execute and sometimes we want to skip we can use if

statement.

The form of the if statement is:

if (boolean_expression) so if this is true then do the statement

statement

  • If boolean_expression returns evaluates to true , then statement is executed.
  • If boolean_expression evaluates to false , then statement is skipped

IF STATEMENT

EXAMPLE IN PSEUDOCODE

Input : age (integer)

Output : string

if (age>17) then (You can also write it without “then”)

print(“you can rent a car”)

THE IF-ELSE STATEMENT

If we want to choose between 2 alternative we use the if-else statement.

The form of the statement is:

if (boolean_expression)

statement

else

statement

If boolean_expression evaluates to true , then statement1 is executed, else statement2 is executed.

It is represented by a diamond.

IF-ELSE STATEMENT