Docsity

coding for data science, Dispense di Sistemi Informativi

Anteprima parziale del testo

Scarica coding for data science e più Dispense in PDF di Sistemi Informativi solo su Docsity!

Coding

% > module operator 23 % 2 > output: 1 Module operation > outputs the rest of the division of a number by another. It useful to understand if a number is even or odd. // > integer division 23 // 3 > output: 7 > the result of the division of two number. ** > power operator 4**2 > output: 16

There’s a priority of execution when we have long expression:

  1. Expression in parentheses is evaluated first.
  2. The elevations to the power > if an expression contains several exponents python applies them from right to left.
  3. Multiplications, divisions and modules > if there are several of this operation, python evaluate them from left to right.
  4. Additions and subtractions > if there are several of these operations, python evaluate them from left to right. CONDITIONAL EVALUATION > Condition is an expression of type Boolean that returns value True or False Logical operators > always returns True or False
  • AND > if two or more statement are both true or both false, than the returns is true.
  • OR > only if all of two or more condition are false, I have false. If I have only one of them true, and the others false, it will be returns a true.
  • NOT > negate something. It transforms every true statement in false and vice versa. EVALUATING TRUE OR FALSE EXPRESSION: **- A non-zero value is True. Zero is False
  • Strings with characters are True. Empty strings are False.** Function print(arg*)

Code block > is a set of instructions that are executed only if the condition of the instruction is true. If the condition is false, python passes to the next instruction and continues until the instructions are completed. IF…ELSE > executes certain block of code depending on whether the condition is true or false. First, we assign the value 35 to the variable grade. Then, the program checks the first (if) condition, comparing 35 > 60. This is false because 35 is not greater than 60. Since the if condition is false, the program skips the code inside the if block, so it does not print ‘passed’. Since the if condition was false, the program moves to the else block. The program executes the else block, and prints ‘not passed’. IF…ELIF…ELSE > we use it when we have more than one alternative.

Using the IF…ELIF statement python works in a:

  • Effective way > reaching the result.
  • Efficient way > it does it in the faster way, saving more energy. Python executed the code block, and when it finds the solution (when the condition is true), it skips the other next instructions and prints the result. While, using a chain of IF, python executes all the instructions. In this case, it works in an effective way (reaching the result) but not in an efficient way. Example: The first step is to assign the value 62 to the variable grade. The program checks the first condition comparing 62 >= 90. This i false, because 62 is not greater or equal than 90. So, the program skips the code inside this if block and moves to the next condition (elif). The program checks the second condition comparing 62 >= 80. This is false, so the program skips the elif block and moves to the next condition. The program checks the third condition, comparing 62 >= 70. This i false, so the program skips the elif block and moves to the next condition. The program checks the fourth condition, comparing 62 >= 60. This is true, because 62 is greater than or equal to 60. So, the program enters in the elif block, and executed the code that prints D. At this point the program stops checking further conditions because it founds a true condition and executed the corresponding block. WHILE > this statement repeats one or more actions as long as the condition remains true. A statement of this type is often called a loop.

The for loop iterates over each character in the string ‘Program’. The string is treated as a sequence of characters ['P', 'r', 'o', 'g', 'r', 'a', 'm']. The variable c will take each character from this string in turn. The loop starts with the first character ‘P’. The if condition is checked, and it is false. Since the condition is false, the else block is executed. The program prints P,. The next character is ‘r’. The if condition is checked, and it is false. The else block is executed. The program prints r,. … The next character is ‘m’. The if condition is checked. It is true. Since the condition is true, the if block is executed. It prints m followed by a space (not comma). After the loop has iterated over all the elements in the sequence, it ends automatically. RANGE > this function generates a sequence of numbers, which is often used in loops (especially for) to specify the number of iterations.

it is very useful when you need to iterate over a sequence of numbers, especially when you know, the start, end, and optionally the step between the numbers. Start > the starting number of a sequence (inclusive). The default is 0. Stop > the end number of a sequence (exclusive). The sequence stops before this number. Step > the increment between each number in the sequence. The default is 1. This generates number from 0 to 4 (the stop value 5 is not included), and increments by

This generates number from 1 to 9 and increments by 2. So, it generates the odd numbers between 1 and 9. ALGORITHM

BINARY SEARCH

The aim is to find the position of a target element in a list or array by repeatedly dividing the search space in half. This minimizes the number of comparisons needed to find the target. It is much faster than linear search for large datasets. If no doors left to search in, means the target value is not in the list. At this point return false, indicating the target is not found. Check if the element is in the middle of the list (middle index). If the element in there is = 50, you have found the target, so return True. The algorithm stops. If the target is smaller than the middle element, the target must be in the left half of the list (from the start to the middle index minus one). Focus on the left portion of the list, continue to search in this section. If the target is greater than the middle element the target must be in the right half of the list (from the middle index plus one to the end). Search in this section. The process continues until the target is found or the search space becomes empty. COMPLEXITY Best-case scenario > O(1) the best case occurs when the target is found at the middle of the list during the first comparison. Worst-case scenario > O(log n) much faster than linear search for large lists. In the worst case the target is either not present, or it is found after having search down to a single element. Since the search space is halved at each step, the time complexity is logarithmic. SORTING ALGORITHM The aim is to sort an unsorted element. The input is an unsorted array, and the output is a sorted list of elements (ascending or descending order).

  1. SELECTION SORT Is a simple sorting algorithm that works by repeatedly finding the smallest element from the unsorted part of the list and placing it in the correct position.

Start from the beginning of the list (at first, the whole list is unsorted). Find the smallest item in the whole list. Swap this smallest item with the item at the starting position. The first term now is in the correct place, so move on to the next position and repeat the process (look only at the right part of the list, so the unsorted part). There are two loops that control the sorting process:

  • Outer loop > selects each position in the array where the smallest element from the unsorted part should go. In the first iteration (i = 0), try to place the smallest element in the first position…
  • Inner loop > finds the smallest element from the remaining unsorted part of the array. This loop checks all the elements after i (the unsorted part) and finds the smallest element in that portion. Variable j is the index used to compare elements in the unsorted part of the array. If i = 0, the inner loop checks all the element from 1 to n-1; if i = 1, the inner loop checks all elements from 2 to n-1… COMPLEXITY Best-case scenario > O(n^2) Worst-case scenario > O(n^2) In this case there’s no best-case scenario, in fact the complexity is the same in both cases. The algorithm must visit all the array in any cases.
  1. BUBBLE SORT The idea of bubble sort algorithm is to repeatedly compare adjacent elements in a list and swap them if they are in the wrong order.
  2. Compare adjacent elements > start at the beginning of the list and compare the first two elements. If the first element is greater than the second, swap them. If the first element is smaller, leave them as they are
  3. Move to the next pair > after comparing the first two elements, move to the next pair (the second and third) and repeat the process.
  4. Repeat until the end > continue this process until the end of the list is reached.
  5. After each pass through the list, the largest elements will have bubbled up to its correct position at the end of the list.

The first line defines a function called rectangle_area that calculates the area of a rectangle. The function has two parameters:

  • Length > with derfauly value of 3
  • Height > with default value of 2 These default values mean that if no argument is provided when calling the function, length will automatically be 3, and height will automatically be 2. If the users provides values, the default values will be replaced by the provided arguments (in the last line, when I call the function: rectangle_area(2,2)). The second line calculates the area of the rectangle. The result is returned by the function. In the list line, I call the function without any arguments. Since no values are passed for length and height, the function uses the default values, 3 and 2, and prints the output 6. ARBITRARY NUMBER OF PARAMETERS It is possible to define a function with argument *args. That means that you can pass to the function every type and number of arguments. Create an array of numbers and pass it to the function. Define the function named average that calculate the average of a list of numbers. The function can take as argument any kind of (decide when I call the function). When the function is called, it calculates the average by dividing the sum of elements by the number of elements. In the last line, the function is called and takes as argument the array grades. Inside the function, the sum is calculating = 57, and the length = 6. The average is computed and print. Output = 9.5. METHOD (FUNCTIONS OF OBJECTS) Methods are functions that are associated with an object

LOWER and UPPER VARIABLES SCOPE Each variable in the code (identifier) has a scope. The scope of a variable refers to the context in which a variable is accessible or visible. Determines where a variable can be accessed or modified within your code.

1. Local variable It is a variable that is defined within a function or block of code (ex. loop conditionals). It can only be accessed within that function or block where it is defined. Once the function execution is over, the local variable is destroyed and can no longer be accessed 2. Global variable Is a variable that is defined outside the function, making it accessible form anywhere in the program, including inside functions (unless shadowed by a local variable). Global variables can be modified inside the functions using the global keyword. Define the global variable x (outside functions) and assign the value 7. Define the function access_global and use the keyword global to declare that we want to use the global variable x. global x tells python to refer to the variable x that exiosts in the global scope (outside the function), not create a new local variable named x inside the function. The next line x = 5 modify the value of the global variable and change it from 7 to 5. Print the current value of x. When we call the function in the last line:

  • The function modifies the global variable x to 5
  • The value of x is printed inside the function. Output printed: x visualize: 5 Global and local variables can be called with the same name!

The function cube takes as argument number and print its id before and after modifying it. The first pint statement prints the memory address of the number. The value is 5, because when we call the function, the argument takes as value 5. The operation inside the function modifies number by rising it to the power of 3, changing its value. Since integers are immutable, python creates as new integer object to store the result of 5*3 (125). The id changes. Since integers are immutable, python doesn’t modify the original object (5) but instead creates a new object (125). That’s why the id changes after the modification. When you modify an immutable object, Python does not change the object itself but rather creates a new object with the updated value. MUTABLE OBJECTS > list RECURSION A recursion is a technique where a function calls itself to solve a problem. Instead of solving the entire problem in one go, the function breaks it down into smaller parts and solves those. Base case > this stops the recursion and prevents it from running forever. Recursive case > this is where the function calls itself with a smaller or simple version of the problem. FACTORIAL FUNCTION > Recursive function The factorial of a number n is the product of all positive integers less than or equal to n. The factorial() takes as a number n as input. The base case is when n == 0, and in that case, the function returns 1 (since 0! = 1). For any number greater than 0, the recursive case computes n! as n(n-1)! The function calls itself with n-1, repeating the process until it reaches the base case. The factorial of a number n is the product of all positive integers from 1 to n. This function calls itself to break down the problem into smaller subproblems. The function continues calling itself until it reaches the base case (a simple condition where no further recursion is needed). Base case > if n is 0, the function returns 1. This is the stopping condition for the recursion.

Recursive case > if n is not 0, the function call itself with a smaller value, n-1. It multiplies the current value of n by the result of factorial(n-1). This repeats until the base case is reached. Step 1 > factorial(5) 5 is not 0, so the function calls factorial(4) and multiplies the result by 5. Step 2 > factorial(4) 4 is not 0, so the function calls factorial(3) and multiplies the result by 4. Step 3 > factorial(3) 3 is not 0, the function calls factorial(2) and multiplies the result by 3. Step 4 > factorial(2) 2 is not 0, the function calls factorial(1) and multiplies the result by 1. Step 5 > factorial(1) 1 is not 0, so the function calls factorial(0) and multiplies is by 1. Step 6 > factorial(0) Since n == 0, the function returns 1 (base case). Now that the base case has been reached and return 1, the function calls start unwinding and each call returns the result back: The function returns 10, which is the factorial of 5. MERGE SORT It is a divide and conquer algorithm. This means it divides the problem into smaller subproblems, solves those sub problems, and then combines their result to solve the larger problem.

Accessing to the elements of a list from the last element using negative indexes: LENGTH OF A LIST CONCATENATE LISTS Using + operator it is possible to concatenate two lists, two tuples, or two strings. The result will be a new sequence of the same type containing the elements of the two lists. The original sequences are not modified. ACCESSING THE LIST ELEMENTS With for and range you reach all the elements of a list. Initialized the list containing the values 1,2,3,4,5. The list has 5 elements, and their indexes ranges from 0 to 4. The for loop iterates over a sequence of numbers generated by the range() function. Len function returns 5 because there are 5 elements in the list. The range(len(concatenated_list)) generates a sequence of numbers from 0 to 4, which corresponds to the indexes of the list. So, i will tale the values 0,1,2,3,4 during each iteration of the loop. Inside the loop, the print line is executed for each value of i. f'{i}: {concatenated_list[i]}' is a formatted string (also called an f-string) that prints the index i followed by the corresponding value from the list concatenated_list[i]. In each iteration, the index i and its corresponding value from the list concatenated_list are printed. You can compare entire lists, element by element, using comparison operators. This will return True or False

ADDING ELEMENTS TO A LIST

The list a_list is initialized as an empty list. The range functyion generates a sequence of numbers starting from 1 to 5. The for loop will iterate over each number in this range. The for loop begins, and the first value from the range, 1, is assigned to number. The code inside the for block is executed and 1, is added to the a_list = [1]. The second value from the ranfe, 2, is assigned to number. The code is executed, and the element 2 is added into the list: a_list = [1,2]. … The final value from the range 5, is assigned to number. The code is executed, and the list becomes: a_list = [1,2,3,4,5]. The for loop finishes after the fifth iteration, as there are no more numbers in the range. The print statement is executed, printing the final list. The code works by adding each number from the range to a list.