


















































































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!



















































































% > 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:
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:
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
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).
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:
The first line defines a function called rectangle_area that calculates the area of a rectangle. The function has two parameters:
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 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
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.