






















Studia grazie alle numerose risorse presenti su Docsity
Guadagna punti aiutando altri studenti oppure acquistali con un piano Premium
Questa pagina non è visibile nell’anteprima
Non perderti parti importanti!























Lesson 1 – 21/09/ Computer memory We know that there are many memory cell: each cell is called is called bit (which means binary digit) and it can contain either 0 or 1. These cells are grouped into sorted sets called bytes. byte is composed by 8 bit. Computer memory is an indexed collection of bytes. Every memory location (byte) contains 8 bits, each memory location is associated with a progressive address. The number of memory locations N is called memory capacity. Computer memory is composed by a very large number of byte, we use prefix to describe memory capacity. There are different types of memory: the main memory (RAM, Random Access Memory) which is volatile (the content is lost after power off), extremely fast, moderate capacity (tens of Gigabytes) and the external memory such as hard disks, usb keys and SSD which is prescience (content is preserved when powered down), very slow and large capability (several Terabytes). Information Computing is basically retrieving the content of memory cells, changing the bit values according with given logical rules and storing back the processed bit into (other) memory cells. Bits can represent different kind of information, such as number, text, image and audio and multimedia content. For example, it is possible to represent numbers: For example, it is possible to represent text: Text can be seen as a sequence of alphabetic characters representing single letters [a-z, A-Z], numerical digits [0-9] and punctuation symbols. Using one byte we can store 256 different patterns of bit (ranging from 00000000 up to 11111111). We can associate different patterns of bits to alphabetic characters.
Unicode Some languages (Arab or Chinese) are not based on an alphabetic set. Unicode is an information technology standard for the consistent encoding, representation and handling of text expressed in most of the world’s writing systems. It uses two or more bytes to encode each writing symbol. Image representation It is the most popular representation for images is based on a raster (or bitmap) format. Image is described by a matrix (𝑛 × 𝑚) of pixels where: n and m represent the vertical and horizontal resolutions and the (𝑛 × 𝑚) the overall image resolution. For example, a 48MP image is an image composed of 48 millions of pixels. We need to describe the color of each pixel. For black and white images, we can associate one bit to each pixel, for gray scale images we can use a gray palette and for each pixel we need to describe its amount of darkness. Humans can distinguish among about 10,000 gray levels. We need two bytes for each pixel to describe its gray level. All colors can be obtaining as a mixture of primary colors; in computer science the most popular representation is based on adding Red, Green and Blue (RGB). Using one byte for each of the three primary colors we can describe 224 ≈ 16 millions of colors. Audio What is a sound? It is a vibration (i.e., sound pressure) that propagates as an acoustic wave. In any given point we can measure this vibration as a function of time 𝑓(𝑡). To describe any sound, we need to describe the temporal behavior of 𝑓(𝑡). The number of sampling rate and the number of bits used to encode each sample determine the quality of audio digitalization. Spectrum theories based on frequency analysis state that humans cannot hear more than about 40,000 samples per seconds encoded with 16 bits. Audio best bit rate: 40 , 000 × 16 = 640 𝐾𝑏𝑖𝑡 𝑠 =^80 𝐾𝑏𝑦/𝑠. Top quality audio is encoded at 160Kbyte/s. Compression To reduce the amount of memory cells required to store any piece of information (and to achieve better steaming quality of service) the contents are usually compressed. Compression is based on rule that reduce the number of bytes require to store a given content. There are two large families of compression techniques:
Basic tools for Computational Thinking Abstraction is the ability to filter out information that is not strictly necessary to solve a certain type of problem and generalize the information that is necessary. It is the art of taking the details out of a problem so that you can make a solution work for many different things. In the previous example, it does not matter that we want to sort a set of numbers, what is important is that we are able to compare a pair of items and decide which one is greater. For example, 10 > 1, “zeta” > “alpha”. A generalization is the formulation of general concepts from specific instances by abstracting common properties. When we are facing a problem, in most of the cases the problem is just one of the many we need to solve. Instead of sorting this set of numbers {1, 3, 2} we want to devise a method for sorting an arbitrary set of numbers Even better, we want to sort a set of comparable items. For example:
Name <- data, Year <- 2022. Semantic : allocate a memory area (referred as “year”) suited for storing the integer value 2022. Syntax : variable name, any sequence of character (must begin with alphabetical letter). Ex: b <- a + 1 Get the content of variable a, sum one and store the result on a variable named a. All variables used in the expression have to be previously defined. C <- 10 E <- c + d In this case variable d is undefined. Very often “=” is used as “<- “, a=10 instead of a<-10. Variable names must start with an alphabetic letter: Error: 1year=10. It must be year=10. Variable names can’t contain spaces: Error: my name = “Daniele”. Variable name is sensitive. myName and myname are two distinct variables. Best practice rule: use self-descriptive name. Es: year=2022 is correct, while x=2022 is incorrect because it’s not easy to understand the role of variable x. name = expression can be any computable expression evaluated according to arithmetic precedence rules. a + b * c - > must add the value of a to the product bc*. The nature of the information stored on a variable, usually named as data type , determines which operations can be executed and how to compute their results. Es: 5/2 =? Integer data type: 2 Floating point data type: 2. Basic data types are numeric , string , Boolean. Numeric data type Numeric data types are used to store numbers (both integers and real values). Ex: A = 5, B =2.
Boolean expression Boolean expression is a combination of Boolean operations/operators (x >= 10) and (x <= 20). The evaluation of Boolean expression is terminated as soon as we are sure about the results. E.g., assuming x=5 will prevent the evaluation of the second operand (Why?) Boolean expression can be very complex! Every computer program can be described as a Boolean expression… Collection is a grouping of some data items (possibly zero) that have some shared significance to the problem being solved and need to be operated upon together in some controlled fashion. Es: a list (or set) of numbers to be processed. X = [1, 2, 3], X refers to the whole set, X[index] refers to individual item of the set. Index ranges between 0 up to (numberOfItems - 1 ). Algorithm description Pseudocode is a plain language description of the steps of an algorithm. Pseudocode often uses structural conventions (semantic building blocks) of a normal programming language but is intended for human reading rather than machine reading. It’s more flexible than coding and programming languages. It typically omits details that are essential for machine understanding of the algorithm (programming language specific directives). A flow chart is a type of diagram that represents a workflow or process. A flowchart can also be defined as a diagrammatic representation of an algorithm, a step-by-step approach to solving a task. An execution statement is a simply indivisible execution step. We do all the action related to the single execution statement. Examples:
One is a conditional statement and another one is an executional statement. If the condition is false, we skip the executional statements. Statement K is executed anyway, independently from the result of the evaluation. Two alternative conditional statements: If the condition is false, we execute the statement 3. At the end we are going to execute statement 4 anyway. So, we reach the same result independently by the evaluation of the previous statements. The idea is making it easier to understand by humans. Iteration primitive Repeating the execution until a condition is true. Another common semantic structure is the repeated execution of a statement or sequence of statements as long as some condition remains true. Repeating the evaluation is very easy for computers because they are very fast. while (special keyword to identify the start of an iteration) condition: statement 1 statement 2 statement 3 if the condition Is still true, we keep this process until we find a condition false. Then we exit and we go to statement three. on the iteration primitive statement, after executing the statement I go back to evaluate the condition. We do that as many times as the condition remains true. We pass to the next statement 3 only whent the condition becomes false.
Scope refers to the visibility of variables. In other words, which parts of your algorithm/program can see or use it. Scope of variables:
A program coded with a high-level programming language is named source code. This source code is from a computer point of view a file of text. We need a special program that translated source code in order to execute it on the computer. Some special programs take care of translating source code to a set of machine executable instructions. There are two ways in which the computer can execute the code: Compiled languages , a special program ( complier ) translates the source code into a specific machine language. The output of the compiler is an executable program that can be executed. Interpreted languages , a special program ( interpreter ) reads and processes one by one each source code instruction. For each instruction, the interpreter executes all the actions associated with that instruction before moving on the following instruction. Programming paradigms In science and philosophy, a paradigm is a distinct set of concepts or thought patterns, including theories, research methods, postulates, and standards for what constitutes legitimate contributions to a field.
Sometimes we need to pick up only a few elements inside a given range letters [startPos:lastElement:distanceBetweenElements] srartPos: the position of the first selected element. lastElement: last element to be considered. The slice operator selects a subset of elements, that is, of element positions How these positions are computed? nextPosition = currentPosition + distanceBetweenElements Example: letters = [ ’a’, ‘b’, ‘c’, ‘d’ ,’e’, ‘f’, ‘g’] letters[1:6:2] Methods Methods are functions applied to given data structures (ref: O.O. paradigm) Syntax: name. methodName (
The conditional statement The if word tells the interpreter that there is a condition with a Boolean result. if condition: statement 1 ….. statement n statement n+ Sequential search PROBLEM: we want to check if a given element is present on a given list mylist = [ 3, 1, 2]
Computational thinking requires to identify a procedure to solve the problem Let try to “fool” our intuition mylist=[1, 7, 10, 4, 5, 78, 41, 0, 12, 17, 32, 28, 19, 7, 15, 24, 45, 3, 55, 2, 20] Is 2 present in the list? There is an index that refers to a certain number inside the list and checks if the number is present or not in the list. We need to have a placeholder to analyze each element of the list. Then we consider the current element and we compare it with the target value- if it is equal, we can provide the answer. Otherwise, we move to the following element. When. We reach the end of the list we can provide the answer. mylist = [ 3, 1, 2] x= n=len(mylist) i= found=False while not found and (i < n): if mylist[i]==x: found=True else: i += 1 if found:
Lesson 4 – 07/10/ Data type
If we want to substitute an element in a list, it is possible because lists are not only data types but also data structures so it is possible for us to change an element inside a list. The append method is a method written like this my_list.append means adding a new element to the list. The insert method allows to have a new character inside the list, not at the end of the list like the append method. In the append we didn’t put the square one in front of 4, because it is an integer. The pop method is useful for deleting an element from the list. There are 4 types of data types that we need to know: dicit, tuples, sets.
an error has been made in this case and is an arbitrary error, which is the 0. This algorithm works only with positive numbers and not with negative numbers. The 0 as maxValue is an arbitrary choice that has some implications. The initial value must be one of the list values. The output is 0! If we are using an empty list we should use none. Another example: mylist = [ - 1, - 4, - 2, - 7, - 12, - 4 ] maxValue = mylist[0] for i in range(1, len(mylist)): if mylist[i] > maxValue: maxValue = mylist[i] print('The largest value is:',maxValue) here we are not considering the element with index 0. The right one to use should be this one: mylist = [ - 1, - 4, - 2, - 7, - 12, - 4 ] maxValue = mylist[0] for x in mylist: if x > maxValue: maxValue = x print('The largest value is:',maxValue) Program unit (Python function) A function is a block of organized, reusable code that is used to perform a single, related action. It allows us to define new reusable abstract tool.
This variable can be referred only inside the function mean. Because they are created only during the execution. After you exitv from the function with the return statement, terminate the execution of the function and provide this value as result. After we terminate the execution, all boxes are destroyed. Scope is the portion of code in which we can refer to a variable. The scope of the variable sum is just after its definition at the end of the function. Formal paramete r is the placeholder used in the definition of the function: this parameter doesn’t even exist when we define the function. It is def mean(mylist) When I am calling the function, we have the real information that is called actual parameter. During the execution there is the binding between formal parameter and actual parameter. It is print( mean(mydata) ) Functions can have kore than one parameter. For example, function that sums three values: def sum(a, b, c): return(a+b+c) print(sum(1, 2, 3)) form - > actual parameters from left to right. a=1, b=2, c=3. This is called positional assignment. Function parameters can have default values, that is, a value to be assigned if the corresponding actual parameter is missing def sum(a, b, c=0): return(a+b+c) print(sum(1, 2, 3)) print(sun(10,20)) Since actual value of formal parameter c is unspecified it will be set to its default value (in this case it is equal to zero). Packages Once our functions are coded, we want to put our functions in collections called packages. Functions are usually collected in a library, named package. Packages can be imported in your Python environment to add abstract tools (i.e., already coded functions). For example, mathematical functions (e.g., trigonometric ones) are coded in a package name math) Before using any function provided by a package we must add (i.e., import) the package to our programming environment The Ptyhon statement to add package is: import packageName packagename.function(…) Packages can also define constants (i.e., special variables with immutable values) packagename.constantName Import import math print(math.pi) print(math.sin(math.pi/2)) import random print(random.randint(1,6)) print(random.randint(1,6)) print(random.randint(1,6))