Arrays with NumPy

* Arrays are used for large-scale scientific calculations. * Arrays require the NumPy library. * Arrays function like lists. * Arrays are significantly faster and more memory-efficient. * Limitation: All elements in an array must be of the same type. ### Multi-Dimensional Arrays * Arrays can have more than one dimension. * A 2D array has rows and columns. * Example: ``` tblNum = np.array([[1,2,3],[4,5,6]]) print(np.tblNum[0,0]) #Result displayed 1 ``` #### Example - 2D Array * `tblValeurs` is a 2-dimensional array. * `tblValeurs` contains 1-dimensional arrays as elements. ### Exercises * Ex 1: Convert pounds to kilograms. * Ex 2: And the index is... ### EX 1: Convert Pounds to Kilograms * Write a program that: * Creates a NumPy array containing at least 5 weight measurements (in pounds). * Converts the pound values in the array to kilogram values in a new array. Note: 1 \text{ pound} = 0.454 \text{ kgs}. * Prints the values of both arrays. ### EX 2: And the Index Is... * Analyze the base code included in exercise 2 on Repl.it to understand 2D array indexing. * Research NumPy functionalities to modify the program to display the index of each array element. * Consult the solution if needed. ### EX 2: And the Index Is... (Solutions) * The solution addresses the problem in two ways: * The first solution uses the `.shape` method to determine the number of columns and rows. * The second solution uses the `.ndindex` and `.shape` methods to create iterable sequences based on the size of `tblValeurs`. This method is more difficult to understand. ### U2 L4 Arrays (Part 2) * The video explains the process of traversing: * A 2-dimensional list. * A 2D array. ### Traversing a 2D Array * Use nested loops. * Example Code: ```python import numpy as np # Establish the array. tblValeurs = np.array([[1,2,3,4], [6,7,8,9], [11,12,13,14]]) # Traverse the array # Iterate each rangée of the array for rangée in tblValeurs: # Within each iterate each élément of the rangée. for élément in rangée: # Add tabulation after each élément print (élément, "\t", end="") print("") # Jump to next line at the end of each rangée. ``` ### Arrays and Statistics * Arrays are useful for calculating statistics, especially measures of central tendency: * Mean: Sum of data divided by the number of data points. * Median: The value that separates a population into two equal parts, or the average of the two middle values (values must be sorted in ascending order). * Mode: The most frequent value in a distribution. If all values are distinct, there is no mode. ### Errors Types * Syntax Error * Prevents the program from running (failure): Python does not understand the code. * Examples: * Misspelled code (e.g., `Print` instead of `print`). * Missing required symbol (e.g., `:`). * Indentation error. * Runtime Error * Causes the program to crash during execution. * Examples: * The program cannot find data. * The program cannot manipulate data. * Logic Error * The program appears to function, meaning it does not crash. * However, the program output is incorrect or nonsensical. * Example: Code respects syntax rules but produces an incorrect or unexpected result. Logic errors are more difficult to find. ### Debugging Strategies * Code a small block at a time. * Code and test each function, loop, or instruction group before continuing. * Advantage: Errors are easier to target. * Use `#` to disable a line of code or `"""` (triple quotes) to disable a block of code. * To identify the erroneous line of code. * Use `print()` to check values: * Inserting `print()` can be very useful for verifying that a variable's value/type matches what is expected. * Use `break` to stop a loop: ```python for var in sequence: # code in the loop if (condition): break # more code # The break exits the loop. ``` * Use the Python debugger: * Python installed on a computer comes with a debugger called `pdb`. * The debugger allows executing a program line by line to check each step. * Each IDE (IDLE, PyCharm, Repl.it) contains a debugger with its own properties. However, they can all execute one command at a time while monitoring variable values. * Search online for more information. * Follow your code on paper: * The programmer writes down the value of variables after each step, creating a column for each variable to track the flow of values. ### U2 L7 Manipulating a NumPy Array #### Functions for Manipulating a NumPy Array | Operation | Syntax (Example) | | :-------------------------------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Create an empty NumPy array | `tblNotes = np.array([])` | | Add a value to the last position in an array | `Nombre = 14`
`tblNotes = np.append(tblNotes, Nombre)` | | Count the number of values in the array | `tblNotes.size` or `len(tblNotes)` | | Determine the dimensions of an array | `tlbNotes.shape` Dimensions are given in a tuple: `(r, c)`
`r` = number of rows (int)
`c` = number of columns (int) | | Remove the value at the specified index | `intIndex = 0`
`tblNotes = np.delete(tblNotes, intIndex)` | | Find the index(es) of a value in the array | `Index = np.where(tblNotes == Nombre)` | | Count occurrences of a value in the array | `intCompte = np.count_nonzero(tblNotes == 30)` | | Sort the array | `tlbNotes.sort()` | | Empty the array | `tblNotes = np.array([])` (same as creating an empty array) | #### Manipulation Demo ```python # Methods for manipulating a numpy array import numpy as np # create a numpy array tblNotes = np.array([]) # add 5 notes to the array with append tblNotes = np.append(tblNotes, 87) tblNotes = np.append(tblNotes, 78) tblNotes = np.append(tblNotes, 54) tblNotes = np.append(tblNotes, 97) tblNotes = np.append(tblNotes, 78) # # to count number of elements in the array print (f"There are {tblNotes.size} notes in the list: {tblNotes}") # - calculate the average of the array values print (f"\nAverage: {tblNotes.mean ()}") # The 'delete' method removes the value at the specified index tblNotes = np.delete (tblNotes, 0) print("\nWith the first element removed:", tblNotes) # The count_nonzero method counts the number of times a value appears in the array print ("\nNumber of times the value 78 is in the table: ", , np.count_nonzero (tblNotes == 78)) # The 'where' method finds the index of the indicated value indice np. where (tblNotes == 78) for i in indice: print ("\nThe note 78 is at index/s:", i) # The sort method sorts the values in ascending order tblNotes.sort() print ("\nWith the notes sorted in ascending order:", tblNotes) # erase values tblNotes = np.array([]) print ("\nWith all elements removed: ", tblNotes) ``` ### U3 Les Fonctions - Functions * Functions: creation, parameters, scope, return values. * Create, import, use your own modules. * Summative Assessment: April 7-10 (tentative). ### L1: À quoi servent les fonctions? - What are functions for? * Most programs perform 3 actions: 1. Accept input values. 2. Perform operations on these values. 3. Produce output of the results. * Until now, code has been in the main function saved as `main.py`. #### Function advantages 1. Organize the code * Breaks the code into 'chunks' and lightens the code contained in the main program. 2. The function is reusable * A function can be used several times in several different program, making sure it is contained in a module. 3. Testing * Simplifies the validation of a program; it is not necessary to debug the function if it has already been verified. 4. Extensibility * An update can easily be done in a function without affecting the rest of the program. 5. Abstraction * It is not necessary to understand the code behind the function to use it. #### Functions Natives Python's native functions can be used without importing a library #### Placing functions Functions can be declared anywhere but must be declared before being used. *Best Practice*: Declare all functions at the beginning of the main program, which: * Simplifies code. * Avoids reference errors #### Syntax and structure of a function 1. Start with the keyword `def` 2. Name the function (lowercase letters) 3. Add parentheses. 4. Name the parameters (optional) 5. Don't forget the colon (`:`) 6. The code belonging to the function must be indented. 7. Return one or more values. 8. The documentation explaining the function is included at the beginning, surrounded by 3 quotes. #### Function parameters Most functions accept at least one parameter. Example: Function that calculates various measurements of a circle. * Input: radius value * Uses constant (Pi) imported from the math module. * Output: * Displays messages on the console. * No output to the program that used the function. #### Function circleinfo() Functions `print()` and `len()` are native Python functions. The principle of abstraction allows us to use them without knowing their programming. A function can be used in another function, provided it is declared beforehand. A parameter can be any type. The author of the program calling the function must ensure that the correct type is used to avoid errors. #### Functions and their parameters Functions can accept data structures in addition to numbers, decimals and strings such as lists, arrays and dictionaries. Once transferred to the function, these elements are treated the same way. #### Dictionaries Dictionaries are another useful structure, whose elements have no predetermined order Each entry contains the *key* and then the associated *value*, defined between curly braces (`{}`) ```py dctMonDictionnaire = { "marque":"Ford", "modele": "Mustang" "année": 1964 } ``` #### Key A key can be of any type, but is generally an integer or string To access a value, you must use its key #### Un mot clé: pass A good strategy for writing and checking your code is to define your functions without adding the code. This allows you to use the function in the main program without generating an error. * Empty function that allows you to program by breaking up your code. #### Value returns In addition to accepting values as parameters, functions can also return values. #### Syntax for returning a value ```py maFonction(param1, param 2) ``` *Function `maFonction` accepts 2 parameters and returns 1 value.* *The function is executed ONLY when it is used by a main program.* #### Syntax for returning more than one value ```py maFonction(param1, param2) ``` *Function `maFonction` accepts parameters, returns more than one value and is executed ONLY when used by a main program.* #### Scope of a variable Run the « Exploring the Scope of a Variable » program posted in Classroom. Observe what happens with the values of the variables that are passed to the function versus the values of the variables that are inside a function. Answer the questions asked by adding comments in the program itself. #### Value Transfer 1. Do the values transferred to the functions have to be of the same type? (For example, can a function only accept "int" variables, or only "string" variables, etc.) 2. Are there differences in how values are modified in functions? 3. What do we mean by "inside" and "outside" the function? 4. What do you notice about the value of the dictionary dctUnDiction1 after the call to function3? After the call to function 4? #### General rule Modifying a value inside a function does NOT modify the value outside the function. #### Exceptions: If the modification is done with a method as is the case with the function4() which uses the `.update()` method #### Local and Global Variables A variable declared inside a function cannot be seen outside that function; it is a local variable. A variable declared outside a function - can be seen and used everywhere in a program; it is a global variable. Conventions (Best practices) Even if it is possible to access a global variable inside a function: * It is NOT DESIRABLE to do so. * IT IS EVEN LESS DESIRABLE TO MODIFY IT. #### Modules A module is a series of functions and variables declared in the same file ending in `.py`. Anyone can write a module in Python and make it available to others in a code repository. Several modules are pre-installed with Python, such as `math` or `sys`, and written in C to speed things up. To import a module in Python, use the command `import module` or `import module as mm` To use a function within a module, enter the Module name, function name, and parameters as follows: ```py module.fonction(param1, param2, …) ``` #### Neutralisation Module Exercise * Create a module called "Neutralisation" that contains 4 functions: * First function: The reverse charge * Input parameter: A string composed of "+" and "-" * Returns a string that "neutralizes" the input string. For example, if the first function receives the string "++--++", it returns "--++--" * Second function: The final charge * Input parameter: A string composed of "+" and "-" * Returns the charge of the string: * "+" if there are more "+" than "-" in the string * "-" if there are more "-" than "+" in the string * "0" if there are as many "+" as "-" in the string * Third function: Sum of 2 charges * Input parameters: two strings composed of "+" and "-" * Returns a string that "neutralizes" the 2 input strings, following the model below: * Example 1: If string 1 = "++--++" and string 2 = "--++--" * The function returns: "000000" * Example 2: If string 1 = "++--++" and string 2 = "+-+-+-" * The function returns: "+00-+0" * Fourth function: The sum of a charge * Input parameter: a string composed of "+", "-", and "0" * Returns the "sum" of the string according to the following rules: * "+" is worth 1 * "-" is worth -1 * "0" is worth 0 * Example: If the input string = "+00-+0", the "sum" will be: 1 + 0 + 0 + (-1) + 1 + 0 = 1 #### Main Program Write a main program that offers a menu to the user with the following options: 1. Reverse charge 2. Final charge 3. Sum of 2 charges 4. Sum of a charge 5. Quit the program Add the code necessary to properly manage each menu choice. For example, if the user chooses option 1, the program prompts them to give a charge composed of "+" and "-". Important: The main program is responsible for validating the received data before calling the functions. #### Pascal's Triangle A program is to be created that: * Asks the user for the number of rows (positive integer > 0) * Call a function to create the triangle. *Extra Challenge*: Center the triangle using a variation of the following method: `str.center(width[, fillchar])` ### Object Oriented Programming * Reusability is the basis of advancement in programming * Math libraries are an example * Can use functions to calculate sin, cosine etc * Reusability of functions is limited compared to object-oriented programming #### Defining an object You have already used objects from a number of different python libraries This is a way of organizing your program #### How to define a object an object groups: * The data of an object (called properties) * The code that uses these variables (called methods) *The object is defined in a "class"* *Property = variable of on object* *Use the term method instead of function* *Class variable*: property is defined in the structure of the class. generally the same value for each instance *Instance variable*: Defined inside a method when object is created. It's value is unique * An object is like a "instance" of the class, or a real house that uses a class like a "plan" and is what tells us how to construct the object. * A class is simply a MODEL used to create the object #### Methods of Accessibility * For each property with python use `get` methods to access proprety vlaues * Use `set` methods to change or set the property values * To enforce restricted acces use an underscore (_) at the start, this serves aa a reminder that is is best practice not access variables directly * There is no mechanism to prevent direct access with python *Decorators functions are another way to created class methods that make it easier to access an objects propreties* * @property ... Used to make it easier to 'get' the property value * @proprety.setter ... used to make it easer to 'set' or change the proprety value including validation * @proprety.deleter .. Used to delete a proprety. *Special methods = to make it easier * print(object) executes * _str_ * * len(object) execute _len_ * * for i in object executes _getitem_ method* #### Big Data / Lists and objects * Classes allow information to be categorized into an object * Multiple objects may then be created * When more than 4 objects exist it becomes more challenging to use and organize these objects * *lists* are Data structures that can contain many data that are integer, text or more complex Every object is added to the list with the .append() method *Advantages*? Objects can be easily orgaized and appended to a list *Disadvantages*? Must know the index. Dictionaries? Can easily use multiple objects that just use an object instead of index.