



















Studia grazie alle numerose risorse presenti su Docsity
Guadagna punti aiutando altri studenti oppure acquistali con un piano Premium
Prepara i tuoi esami
Studia grazie alle numerose risorse presenti su Docsity
Prepara i tuoi esami con i documenti condivisi da studenti come te su Docsity
Trova i documenti specifici per gli esami della tua università
Preparati con lezioni e prove svolte basate sui programmi universitari!
Rispondi a reali domande d’esame e scopri la tua preparazione
Riassumi i tuoi documenti, fagli domande, convertili in quiz e mappe concettuali
Studia con prove svolte, tesine e consigli utili
Togliti ogni dubbio leggendo le risposte alle domande fatte da altri studenti come te
Esplora i documenti più scaricati per gli argomenti di studio più popolari
Ottieni i punti per scaricare
Guadagna punti aiutando altri studenti oppure acquistali con un piano Premium
contiene le lezioni frontali e il riassunto del libro
Tipologia: Sintesi del corso
1 / 27
Questa pagina non è visibile nell’anteprima
Non perderti parti importanti!




















= is the thought process involved in formulating a problem and expressing its solution (s) in such way data computer - human or machine - can effectively carry out ● is the mental activity for abstracting problems and formulating solutions that can be automated ● machines understand a problem and find a solution by using an algorithm (automated process) ● (is 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)
ALGORITHM = is a sequence of basic steps that a non-intelligent being can blindly follow to solve a problem ● is the link between problems and solutions ● it provides a method to obtain a solution of a problem ● can be very useful, e.g. for saving lives (pacemakers are based on algorithms) ● needs to follow a PROTOCOL = set of rules commonly shared between the person who wants to communicate and the receiver → both actors need to know how to interpret each sign
→ turning blinks into letters PATTERN MATCHING = often problems are essentially the same as something you've seen in a different situation → you recognise a pattern and you can apply this method in different contexts GENERALIZATION = sometimes you can adapt and generalise a solution to a class of (similar) problems (it depends on the details) PATTERN MATCHING and GENERALIZATION = some letters are more common than others, so we might order the letters on a frequency basis → assign the lowest number of blink to letters that are more frequent (e.g. “e”=1 blink)
always keep in mind the worst case scenario
PROBLEM: it’s too slow → try to estimate the time each letter takes, multiply by the number of letters said ● average-case: for each A there i s a Z, for each B there is a Y and s o on... this leads to 13 blinks per letter. If we multiply by thee number of letter Mr. Qwerty wants to say, we have an estimate of the running time ○ worst case scenario: still 26 blinks ANOTHER SOLUTION: play 20 questions → Answering yes/no is like blink/no blink ( binary approach )
→ there is a bound between logic and algorithmic thinking (humans have an innate understanding of both logic and algorithms) → result of a logical proposition composed by rules, procedures and definitions
→ LOGIC is a system to distinguish between correct and incorrect arguments ● includes a set of principles that, when applied to arguments, allow us to demonstrate if a preposition is true or not (need to evaluate a set of propositions as a group ) deductive approach: the conclusion is the direct implication of the previous assumptions
The role of computers in this process is just to speed things up (are “only” automating your reasoning) ● they make sure that: ○ the reasoning should be valid (in order to make an algorithm work) ○ you give the computer reliable input (same conditions, same rules already established) ○ you know how to interpret the output
A program is an algorithm that has been customized to solve a specific task under a specific set of circumstances by using a specific language algorithm is general, the sequences of steps the program should do in order to achieve the result program is the specific implementation of an algorithm E. g: Tres en ratlla Algorithm
All the algorithms must be finite, so to do that, you have to find a way to exit the loop. The condition of the game, in this case (which is a loop), one would be non spaces = the game must end, and the other, is that one of the two players won.
Since its first appearance in 1991, Python has become one of the most popular programming languages, along with Perl, Ruby, and others. → it’s popular and easy to learn It is often referred to as a scripting language to emphasize that it can be used to quickly write small programs (or scripts). Such "rapid prototyping" ability is one of the difference between Python and "established" programming languages like C/C++ or Java. ● used a lot also in research and companies (used by many figures, not only technicians)
→ 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:
● if the area has size one so must contain the numbers from 1 to 1 ● if the area has size two so must contain the numbers from 1 to 2 ● the area that isn’t next to the 1 must be the 1 because there isn’t anywhere else for it to go In order to solve the puzzle we applied the two rules and some basic facts that were already known: ● From them we repeatedly worked out new facts about our puzzle ● We have been using ‘deduction’ where we work from known facts and the rules of the puzzle to give us new facts
matching patterns, creating rules As you do more puzzles, and get more experience though you start to solve the puzzles in a different way. ● pattern matching: against situations you have seen before ● generalisation: widening the situations you pattern match against
rules
We aren’t just using logical thinking as we become better and better at doing the 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 details about other parts of the puzzle to make things easier to think about and to make the rules as general as possible
→ try to create a simplified model of the problem by leaving out its details → focus only on the critical aspects needed to solve the problem ● express an idea in a specific context while at the same time suppressing details irrelevant in that context → generalization = identify patterns among the sub-problems and simplify them ● always try to solve a simple concrete instance to better understand if the abstraction-idea is correct or not - e.g.:
layers of abstraction CLASS = object-oriented paradigm in which you treat data as similars There are different layers of abstraction → the more you go up, the higher the level of abstraction is and the more you loose details ● e.g. animals: set of living beings that have some properties → the characteristics of objects contained in this class have always the same properties For each level of abstraction there are some properties that can be loose or obtained
representation and abstraction → figuring out what characteristics of the problem are important and using these to create a representation of the problem to be solved → unimportant characteristics can be filtered out and ignored
→ repeated portions of the problem expressed in the same form. When you find the solution of the repeated pattern you also have found the solution for the major problem ● it entails finding similarities or shared characteristics within or between problems ● it allows us to use the s ame solution for each occurrence of the pattern
e.g. data compression:
e.g. create an algorithm that represent with a flow chart how to make tea It’s good to use abstraction but you have to improve the algorithm in order that it can works also with slightly different inputs (e.g. tea) → works with different conditions
If the input is different from herbal tea or black tea the algorithm doesn’t work → solution: make the machine as flexible as possible in order to handle the majority of possible cases that might happen
FLOWCHART = visual diagram ( chart ) in which you can represent the flow of the algorithm ● oval = an algorithm has always a start and a stop ● parallelogram = used for input/out operations ● rectangle = when there is a step, an action that changes the state of the variable (every operation that concerns a process) - no input/output ● rhombus = represent conditions, different decisions, loop conditions
e.g. algorithm flowchart to check whether a number is even
e.g. algorithm flowchart for the list of the N even numbers in the range 1-N
EXERCISE: Assuming the input list is not empty and that x and y are both initially 0, what is the output of this algorithm? → B
EXERCISE: We have a list of daily temperature readings. Will this algorithm find the correct min and max temperature? → D (if the current item is not smaller than the min it doesn’t mean it’s greater than the mac)
→ algorithm we use to find if a number is present in a given sequence (both sorted and unsorted list) We need to check if the number 90 in present in the given sequence: 52, 34, 78, 12, 24, 90, 87, 99, 45 Humans might skim through the number by looking for a match. 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)
This algorithm works, but what if the list is very long? → is effective but not efficient
EXERCISE: A health worker has created an assessment tool that allows respondents to rate their symptoms as not occurring, mild, moderate, or severe. S/He wants to keep track of the number of times the respondent selects severe. The flowchart describes an algorithm that counts the number of occurrences of a target value, but there are some problems with it. Can you spot them?
→
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 ● in worst case scenario: the number of steps correspond to the number of total items = complexity is proportional to the size of input sequence → linear search cannot take more than n when it searches for an element which is not in the list Complexity = is the mathematical functions that express the number of steps; it depends on the size of the input
The more is the input size, the more is the number of operations → we have a linear growth on the size of the input → the complexity is linear In this case we say that the algorithm has a LINEAR RUNNING TIME = linear complexity because the number of operations grew linearly as the number of elements grew The more is the input size, the more is the number of operation
Sometimes there are more complicated problems which have more complicated curve
→ It can be used if we seek an item into a sorted list L of items (≠ complexity for unsorted lists) e.g. We seek item 12 L = 12, 34, 44, 46, 52, 78, 79, 87, 99
VARIABLES can contain any type of value and can be updated during the execution of an algorithm variable assignment: take a value and save it inside a variable by using the assignment operator → = or ← variable type: a value can be: integer number (e.g.1); floating point number (e.g.4.5); string =portion of text delimited by quotes “” (e.g. “pippo”) char = only for one letter and for constants variable = container of values that can change over time and at every time ≠ CONSTANT = once you assign a value it never changes → constants are assigned as the variables but they never change during the execution of an algorithm (e.g. const PI x = 3.14 (=𝜋)
arithmetic assign operators
action Common symbol example addition + 2+2 = 4 subtraction - 2-3 = - multiplication * 23 = 6 division / 4/2 = 2 modulus (associated with integers) % 4%2 = 0 | 4%3 = 1 power ** 4*2 = 16
arithmetic assignment examples ( = update the value of age by adding 14 to the current value of age)
equivalent code
age += 14 age = age + 14 age -= 14 age = age - 14 age *= 14 age = age * 14 age /= 14 age = age / 14 age %= 14 age = age % 14
e.g. age =10 | age += 14 → age = 10 + 14 = 24 age -= 9 → age = age - 9 = 10 - 9 = 1
how to increment/decrement a variable
examples (compact syntax) equivalent code (extended) i++ ( not accepted by Python ) i = i + 1 ( accepted by Python ) i-- ( not accepted by Python ) i = i - 1 ( accepted by Python ) i += 1 ( accepted by Python ) i = i + 1 ( accepted by Python ) i -= 1 ( accepted by Python ) i = i - 1 ( accepted by Python )
postfix increment = the increment of the variable ( oldest++ ) occurs after the value is assigned ( age ) e.g. oldest = 32 age = oldest ++ ( → the increment happens after the assignment)
prefix increment = the increment of the variable ( ++oldest) occurs before the value is assigned ( age ) e.g. oldest = 32 age = ++ oldest ( → the increment happens before the assignment)
relational operators = they support the fact there is a natural order between the elements
operator meaning a == b equality (don’t confuse with the assignment operator, =) a != b not equal a > b greater than a < b less than a >= b greater than or equal to a <= b less than or equal to
compound operators = to express boolean logic expressions (they don’t work with Python because they are pseudocodes)
operator meaning && ( and for Python) logical and ( AND operator in Boolean logic) | | ( or for Python) logical or ( OR operator in Boolean logic) ! ( not for Python) negation ( NOT operator in Boolean logic)
comments = are not executed, but they are used to describe the code to humans → are also called “ invisible elements ” because they are invisible to the machine ● in Python comments are preceded by a # simbol → e.g. # This is a comment print = display a given value to the screen ● the syntax of the command is the following: print(output) ● symbol ( + ) = concatenate (put string together one after the other) ● to print multiple variables at the same time (= as a single print instruction) → use commas ( , ) ● to print a string → use single (‘) or double (“) quotes ○ if you want to print the inverted commas → “”” printing inverted commas: “” “”” or ‘ printing inverted commas: “” ‘
name that represents a value stored in the computer memory
arithmetic operations with strings → you cannot sum an integer and a string. string1 = "test" a = 4 string1 + a (→ this will produce an error because “ string1 ” is a string while “ a ” is a number ) The following works because we convert the integer into a string string1 = "test" a = 4 string1 + str(a) e.g. # declare and initialize two variables of type integer
new variable: z = x + y
some properties of the modulus (= remainder ): modulus (symbol % ) = allows to compute the remainder of the integer division between two numbers → to check whether a number is even or odd ● if x < y then x % y always returns x → e.g. 2 % 10 = 2 ● if x == y then x % y always returns 0 → e.g. 2 % 2 = 0
age = age + 4 is the same as age += 4 → in Python ++age and age++ do not work, so you need to use age += 1 e.g.
relational comparison returns boolean values : True is the comparison is verified, False otherwise. eg.
→ to convert a type of variable into another type ● str() - to convert a number into a string (e.g. for concatenating) → constructs a string from a wide variety of data types, including strings, integer literals and float literals ● float() - convert an integer into a floating number → constructs a float number from an integer literal, a float literal or a string literal (providing the string represents a float or an integer) ● int() - convert a number expressed in different font (float or string literal) into integer → constructs a string from a wide variety of data types, including strings, integer literals and float literals eg. str() float() int()
→ is a way to format strings (the first method is shorter and easier to read and interpret) eg.
f-syntax with operations
f-syntax with placeholders → to cut a float number after n places after the dot eg.
eg. list1[len(list1)-1] → return the last element of list1 (in this case will return 58 )
eg.
errors → a typical error when you try to access elements in a list is the index out of range error eg. if we define a list L with 3 elements L = [2,3,7] → we cannot access the element with index 3 since the indexes go from 0 to 2
slicing → allows to get a portion of a list. To specify a portion you need to use ( : ) symbol → L[start:end]
eg.
→ we can alter the flow of control (= the order in which statements are executed) using either conditionals → conditional statements ( if , if-else , and if- elif-else ) allow us to choose which statement will be executed next (to translate the rhombus condition in a flowchart into a real condition ) ● each choice or decision is based on the value of a boolean expression (also called the condition )
if statement → if we have code that we sometimes want to execute and sometimes we want to skip we can use the if statement The form of the if statement is: if (boolean_expression) statement If boolean_expression evaluates to true , then statement is executed If boolean_expression evaluates to false , then statement is skipped
eg. in pseudocode
if-else statement → if we want to choose between two alternative we use the if-else statement The form of the if statement is: if (boolean_expression) statement else statement If boolean expression evaluates to true , then statement1 is executed If boolean_expression evaluates to false , then statement2 is executed eg. in pseudocode
You can put a condition inside another condition
eg. in pseudocode COMMON ERRORS:
eg. in pseudocode In Python if (age >18 and age>24) then Print (“you can have a discount”) CORRECT
eg. in pseudocode In Python if (age <18 or age>24) then Print (“you cannot have a discount”) CORRECT
if-elif-else statement → when you want to use multiple alternatives eg. determine if a number is zero , positive or negative
if statement → is written by using the if keyword if (boolean_condition) : do something The if statement is defined by the if keyword , a boolean condition and the body of the statement that is executed if the boolean condition is True
eg.
if - else statement → is used to specify what to do when the boolean condition of the if conditional is evaluated to False if (boolean_condition) :