Python bases in more than 128 words[Partie 5]

This article follows on from the first four parts that can be viewed here:

I am discussing the basics of the Python language to learn it quickly. In France these bases are taught in high school at the second SNT, first and senior NSI classes. They are also part of the knowledge program for CAPES NSI.

Consolidation of functions:

A module is a file that contains a set of functions that you want to include in your app.

Example file monmodule.py:

def greetings (name):
  print ("Hi" - name)

Using the module in a Python program:

import mymodule

monmodule.salutations ("Sebastian")

Module renaming:

import monmodule as mod

mod.salutations ("Daniel")

The dir function is an integrated function to list all function names (or variable names) in a module.

import platform

res - dir (platform)
print 

It is possible to import only parts of a module, using the keyword from.

from mymodule import greetings

greetings ("John")

Packages:

Packages allow a hierarchical structuring of the module's name space.

Packages help prevent collisions between module names.

Creating a package is quite simple because it uses the directory structure of the operating system.

If we consider a directory called pkg that contains two modules, module1.py and module2.py.

The content of the modules is:

def test():
    print ('test module 1')

Toto class:
    Pass
def test2():
    print ('test module 2')

Joe class:
    Pass

With this structure, if the pkg directory is in a location where it can be found (i.e. one of the directories contained in sys.path).

It is possible to refer to the two modules (pkg.module1, pkg.module2) and import them:

import pkg.module1, pkg.module2

pkg.module1.test()
x - pkg.module2.Joe()

Random value:

random import

(random.random)) #Retourne a decimal number randomly between 0 and 1
(random.randint(10,20)) #Retourne a whole in the defined gap
member '["Seb","Jean","Louise"]
(random.choice) #Retourne an item on the list randomly

Python bases in more than 128 words[Partie 4]

This article follows on from the first three parts that can be viewed here:

I am discussing the basics of the Python language to learn it quickly. In France these bases are taught in high school at the second SNT, first and senior NSI classes. They are also part of the knowledge program for CAPES NSI.

Exceptions:

When an error occurs, (an exception) it can be managed using the try statement:

try:
  print (r)
Except NameError:
  print ("undefined r variable")
Except:
  print ("Other exception") 

Comments:

#Ceci is a comment
#sur
#plusieurs line
print ("Hello Python")
"""
This is a comment
On
several line
"""
print ("Hello Python")

Classes:

Classes are like an object builder, it helps to model real concepts.

Person class:
  def __init__ (self, name, age):
    self.name
    self.age

  def ma_fonction (self):
    print ("Name of person: " 'self.name)

p1 - Person ("Sebastian," 36)
print (p1.name)
print (p1.age) 
p1.ma_fonction()
p1.age - 40 #Modification of the properties of the object
del p1.age #supprime ownership of the object
del p1 #supprime the object

self is a reference to the current instance of the class and is used to access variables that belong to the class. It may be named other than self, but it must be the first setting of any class function.

Heritage:

Inheritance defines a class that inherits all the methods and properties of another class.

Animal class:
   def walk():
       print ('walk')

Class Dog (Animal)
    Pass

c1 - Dog ()
c1.walk()

Manufacturer:

The function __init () is automatically called every time a new object is created.

super () will make the child class inherit all the methods and properties of its parent.

Student class (Person):
  def __init__ (self, name, first name):
    super().__init__ (name, first name) 

Python bases in more than 128 words[Partie 3]

This article follows on from the first two parts that can be viewed here:

I am discussing the basics of the Python language to learn it quickly. In France these bases are taught in high school at the second SNT, first and senior NSI classes. They are also part of the knowledge program for CAPES NSI.

Tuples:

A tuple is an orderly collection like lists and immutable (that does not change).

exampleTuple ("apple," "pear," "strawberry")
print (exampleTuple)
print (exampleTupl[1]e)
print (exampleTu[-1]ple) #L negative indexing means from the end, -1 refers to the last element, -2 refers to the penultimate element, etc.
print (exampleTup[1:2]le) #Vous can specify an index range by specifying where to start and where to finish the range.
z - list (exampleTuple) #conversion tuple on the list
z[1] - "banana" 
x - tuple(z) #conversion tuple list

for x in exampleTuple: #Boucle on a tuple
  print (x) 

if "pear" in exampleTuple: #test of existence in a tuple
  print ("Yes") 

Unpacking:

coordinates - (1.2,3)
x,y,z - coordinates
print (x)

Dictionaries:

A dictionary is an unordered, editable and indexed collection.

Customer
   "name": "Elodie"
   "age": "45"
   "year": 1980
 }

print (custome["age"]r)
custo["nouvelleCle"]mer - "new value" #ajoute a new key and value
customer.get("solde") #renvoi 'None' because the key does not exist

Functions:

The features allow the code to be organized into reusable pieces. In Python, a function is defined using the keyword def.

def exemple_fonction():
  print ("TestFunction")

exemple_fonction()

The data can be switched to functions as a setting. You can add as many settings as you like, just separate them by a comma.

def exemple_fonction (first name):
  print ("Hello" - first name)

exemple_fonction ("John")
exemple_fonction ("Pierre")

Python bases in more than 128 words[Partie 2]

This article follows the first part that can be found here: http://128mots.com/index.php/2019/12/04/python-les-bases-capes-nsi-snt-en-plus-de-128-mots/

As with the first article, I'm talking about the basics of the Python language to learn it quickly. In France these bases are taught in high school at the second SNT, first and senior NSI classes. They are also part of the knowledge program for CAPES NSI.

Operators' priority:

I summarize the priority of Python operators, from the highest priority to the lowest priority

  • Parentheses (): Grouping of operations
  • Exhibitor: x 'y'
  • Multiplication, matrix multiplication, division, whole division, modulo: ' , ', /, //, %
  • Addition, subtraction:

Mathematical functions:

import math
  • math.ceil (2.6) upper whole
  • math.floor(-5.3) whole part, gives here -8.0.
  • math.sqrt: square root.
  • math.pow (5, 5): 5 power 5.
  • math.exp(2): exponential function.
  • math.log(2): logarithm function
  • math.log(3, 2): log in base 2.
  • math.factorial(4): factor
  • math.fsum(L): sum of the items on a list
  • math.sin, math.cos, math.tan: trigonometric functions
  • math.pi: pi
  • math.degrees(y): converting radians to degrees
  • math.radians(y): conversion of degrees into radians

Conditional expressions:

Python relies on indentation to define the scope of the code.

x - 100
Y - 23
if x y:
  print ("x bigger than y")
elif a b:
  print ("equality")
else
  print ("y larger than x")

F-strings:

import math
print (f'The value of pi is 'math.pi:.3f'.')

Two-dimensional lists (matrices):

matrix,[[1, 2, 3] [4,5, 6], [7, 8, 9]]
print (matri[0][1]x)

Methods on the lists:

list.append ('n') #Ajoute an item at the end of the list
list.insert (0,'a') #Ajoute an item at the specified position
list.pop(1) #Enleve the item from the list to the specified position

Python bases in more than 128 words[Partie 1]

Here are my notes to learn the python language very quickly. In France these bases are taught in high school at the second SNT, first and senior NSI classes. They are also part of the knowledge program for CAPES NSI.

Logic operators:

  • and: returnS True if both statements are true
  • gold: Returns True if one of the statements is true
  • Not: Reverse the result, return Sorset if the result is true

Comparison operators:

  • Equality
  • Not equal
  • >< Supérieur / Inférieur supérieur=""></ Supérieur / Inférieur>
  • <=>Equal Lower /Equal Superior</=>
  • Different!

Keyword pass:

When the pass statement is executed, nothing happens, but you avoid an error when empty code is not allowed.

x - 22
y - 150

if x y:
  Pass

User entry:

Using input statement:

name - input ("User name:")
print ("Username is: "

While Loop:

The while loop executes a set of instructions as long as a condition is true. The break statement, allows to stop the loop even if the condition while is true.

x - 1
while x< 11:></ 11:>
  if x 5:
    Break
  x 1 

For Loop:

A for loop performs an iteration on a sequence (a list, a tuple, a dictionary, a set or a string of character).

A list:

for x in[1, 2, 3]:
  print (x)

A chain of character:

for x in "hello":
  print (x)

A tuple:

tupleObjet ('Citroen', 2019, 'C4', 23000)
 
for elements in tupleObj:
    print (elements)

A dictionary:

dico - 'color': 'green', 'animal': 'dog', 'legume': 'spinach'
for cle in dico:
    print

Range function:

To complete a specific number of times, use the range function ().

for x in range(10):
  print (x)

Lists:

A list is a collection that is ordered and editable and allows duplicates.

List["pomme", "banane", "poire"]
print (list[1])
print #A[-1]ffiche the last item on the list
print #L[2:3]orsque you specify a range, the return value will be a new list with the specified items.
print #Lorsque you specify a range, the return value will be a new list with the specified items.
#En omitt[:3]ing the initial value, the range will start at the first element:
print #En [1:]omitting the end value, the range will go to the end of the list:
print #des[-2:-1] negative indexes to start the search from the end of the list: This example returns the elements of the index -2 (included) to the index -1 (excluded).

Trifusion and Implementation Python in less than 128 words

Tri fusion follows the divide paradigm to rule that consists of dividing the initial task into two similar smaller tasks.

The algorithm is as follows:
We divide the list to be sorted into two halves.
We sort every one of them.
The two halves obtained are merged to reconstruct the sorted list.

This algorithm is applied recursively, i.e. until the list to be sorted is made up of a single item.

Tri fusion (source: wikipedia)
#Tri merger function of division of the table
def tri_fusion (table):
    if len (table)<= 1:></= 1:> 
        return table
    pivot - len (table)//2
    Table1 - Table 1[:pivot]
    Table2 - Table2[pivot:]
    left - tri_fusion (table1)
    right - tri_fusion (table2)
    fusion - fusion (left, right)
    return fusion


#Tri fusion function of 2 lists
def fusion (table1, table2):
    indice_tableau1 0
    indice_tableau2 0    
    taille_tableau1 - len (table1)
    taille_tableau2 - len (table2)
    tableau_fusionne[]
    while indice_tableau1<taille_tableau1 and=""></taille_tableau1><taille_tableau2:></taille_tableau2:>
        If table1< table[indice_tableau1]au2:></ tableau2[indice_tableau2]:>
            tableau_fusionne.append (table1[indice_tableau1])
            indice_tableau1 1
        else
            tableau_fusionne.append (table2[indice_tableau2])
            indice_tableau2 1
    while indice_tableau1<taille_tableau1:></taille_tableau1:>
        tableau_fusionne.append (table1)
        indice_tableau1
    while indice_tableau2<taille_tableau2:></taille_tableau2:>
        tableau_fusionne.append (table2)
        indice_tableau2
    return tableau_fusionne

Table[11, 222, 3, 899, 24, 5, 46, 67]
print (table)
tableau_trie - tri_fusion (table)
print (tableau_trie)

In-depth journey through the graphs and implementation Python in less than 128 words

The in-depth journey of a Graph is to explore the graph by memorizing the summits visited and the path to get there.

The principle and explore the graph from a given summit and one explores all its neighbors going as deep as possible (i.e. repeating the summit operation visited at the summit visited until one is stuck, then one returns via the path taken to the starting point).

The deep path allows to find the tree covering the graph which is not the same in general as the covering tree found via the path in width of the graph.

The algorithm in summary:

Downhill phase:

Start from the chosen summit to start and mark it.

As long as possible:

  • Go to an unvisited neighbour and mark it
  • Remember the stop or the arc through which you passed
  • If all the neighbours are already visited:
    • Back to the top by which it was discovered (backtrack phase: ascent)

If all the tops of the graph are visited (are in the covering tree) then the graph is related otherwise the graph is not related.

Example Python with 3 graphs:

Example of related graph
Example of unrelated graph
Example of related graph

Python module for the in-depth route:

#Parcours in depth of a graph
Recursive algorithm: The principle is to explore the graph and retrace your steps when you're stuck.
def parcours_en_profondeur (graph, sommet_en_cours:str, sommets_visites:[]):
	print ('Try to explore the summit:' ' str(sommet_en_cours))
	If sommet_en_cours not in sommets_visites:
		sommets_visites.append(sommet_en_cours) #Ajoute the current summit at the node visited
		print ('Exploring the summit:' - str(sommet_en_cours))
	sommets_voisins_non_visites[]
	for sommet_voisin in graph[sommet_en_cours]:
		If sommet_voisin not in sommets_visites:
			sommets_voisins_non_visites.append (sommet_voisin) - Makes a list of nearby summits not yet visited

	for summit in sommets_voisins_non_visites:
		#pour all the nearby unvisited peaks are made a deep route
		parcours_en_profondeur (graph, top, sommets_visites)

#Fonction test if the graph is related following an in-depth journey
def est_un_graphe_connexe (graph, sommets_visites):
	if len (sommets_visites)
		print ("The graph is related")
		print (20 - "-")
	else
		print ("The graph is not related")
		print (20 - "-")


graph ajacence #Liste
graph
	'A': ['B','C'],
	'B': ['A','C', 'D'],
	'C': ['D'],
	'D':['C','A']
}

sommets_visites[]
parcours_en_profondeur (graph,'A',sommets_visites)
est_un_graphe_connexe (graphe,sommets_visites)

Unrelated graph #Exemple: Top D is not connected to graph
graph
	'A': ['B','C'],
	'B': ['A','C'],
	'C': ['A'],
	'D':[]
}

sommets_visites
parcours_en_profondeur (graph,'A',sommets_visites)
est_un_graphe_connexe (graphe,sommets_visites)

#Autre example
graph
	'A': ,
	'B': ,
	'C': ,
	'D':
}

sommets_visites
parcours_en_profondeur (graph,'A',sommets_visites)
est_un_graphe_connexe (graphe,sommets_visites)

#en end of the route if all the peaks are in the summits visited then the graph is related

#Note
#J're reunited with the indentation errorError: unindent does not match any outer indentation level
#Je simply solved it by resuming all the indentation at the beginning of the line
#et by replacing it with Tabulation rather than spaces