Skip to content
Snippets Groups Projects
Commit ed6285e4 authored by Robin VAN DE MERGHEL's avatar Robin VAN DE MERGHEL :computer:
Browse files

Adding new course of Modelisation and resolution

parent 273cc306
No related branches found
No related tags found
No related merge requests found
import random
"""Data structure of a formula F.
-----------------------------
A variable is a string (with no ',', no '&', no ' ' and no '-')
A positive literal is a variable.
A negative literal is a variable with an additional '-' as first character.
A clause is a list of literals.
A formula is a list of clauses.
The dictionary of a formula is the dictionary whose keys are the variables
of the formula.
Boolean values of variables, literals, clauses, formulas.
---------------------------------------------------------
An assignment for a formula is a Boolean value for each variable of the
dictionary of the formula.
Given a formula F and an assignment A:
The boolean value of a positive literal with variable x is the Boolean
value of A[x].
The boolean value of a negative literal with variable x (-x) is the
Boolean value of not(A[x]).
The boolean value of a clause is the logical OR Boolean value
of its literals. A clause is 'satisfied' if its value is True.
The boolean value of a formula is the logical AND Boolean value
of its clauses. A formula is 'satisfied' if its value is True.
Illustration.
------------
F = [['a', '-b', 'c'], ['-a', 'b', '-d'], ['a', 'b', 'c'], ['-b', 'd', '-e']]
The dictionary of F has keys 'a', 'b', 'c', 'd', 'e'
An example of an assignment:
{'a':False, 'b':True, 'c':True, 'd':False, 'e':False}
"""
def get_formula_from_file(file):
"""Extract a formula from file and returns it as a list.
In file:
A variable is a string (with no ',', no '&', no ' ' and no '-').
A literal is either:
a variable (positive literal) or a variable beginning with
'-' (negative literal).
Literals in clauses are separated by ','.
Clauses are separated by '&'.
Formula is on one line in the file.
Example of formula: a,-b,cloclo&b,-a,-c&d,-a,-b&-cloclo,-name,-a,-b
"""
with open(file, "r") as fileIn:
line = fileIn.readline().strip()
clauses = line.split(",")
for clause in clauses:
yield clause.split("&")
# for clause in get_formula_from_file("formula.txt"):
# print(clause)
def variable_of_literal(literal):
"""Returns the name of the variable of the literal."""
return literal.replace("-", "")
def sign_of_literal(literal):
"""Returns the sign of the literal: '-' for a negative literal and
'+' otherwise."""
return "+" if not literal[0] == '-' else "-"
def set_of_variables_from_formula(f):
"""Returns the set of the names of variables appearing in the formula."""
fSet = set()
for clauses in f:
for clause in clauses:
fSet.add(variable_of_literal(clause))
return fSet
# print(set_of_variables_from_formula(get_formula_from_file("formula.txt")))
def construct_dictionary_from_vars(set_of_vars):
"""Constructs a dictionary from the set of variables.
The value of each entry is None (no assignment)."""
return {key: None for key in set_of_vars}
# print(construct_dictionary_from_vars(set_of_variables_from_formula(get_formula_from_file("formula.txt"))))
def random_assignment(d):
"""Takes a dictionary as input and puts a random Boolean value to each
variable. """
return {key: True if random.randint(0, 1) == 1 else False for key in d}
# print(random_assignment(construct_dictionary_from_vars(
# set_of_variables_from_formula(get_formula_from_file("formula.txt")))))
def boolean_value_of_literal(assignment, literal):
"""Given an assignment and a literal, returns the Boolean value of the
literal."""
return assignment if sign_of_literal(literal) == "+" else not (assignment)
def boolean_value_of_clause(assignment, clause):
"""Given an assignment and a clause, returns the Boolean value of the
clause."""
def boolean_value_of_formula(assignment, formula):
"""Given an assignment and a formula, returns the Boolean value of the
formula."""
pass
def number_of_true_clauses(assignment, formula):
"""Given an assignment and a formula, returns the number of clauses having
a Boolean value True."""
pass
def number_of_clauses(formula):
"""Returns the number of clauses of the formula."""
pass
def pretty_print_formula(formula):
"""Print a nice/readable view of the formula."""
pass
def pretty_print_assigned_formula(assignment, formula):
"""Print a nice/readable view of the formula with each variable replaced
by its Boolean value; also print the value of each clause. Illustration
True not(False) True = True
not(True) False not(True) = False
True False True = True"""
pass
def random_formula(n=26, c=10, min_len=1, max_len=10, file="FX"):
"""Generate a random formula with at most n variables, exactly c clauses,
each with at least min_len literals and at most max_len literals.
Put the final formula in file.
Each variable must be a non capital letter (a, b, c,...,z). """
pass
def iter_all_assignments(d):
"""An iterator to generate all the possible assignments of a dictionary d.
NB: the call returns an iterator of assignments, not the assignments."""
pass
def evaluate_all_assignments(formula):
"""Returns, for each possible assignment of the variables of the formula,
the list of the number of satisfied clauses (with Boolean value True)."""
pass
"""
Example of pretty print of formula a,-b,c&-a,b,-d&a,b,c&-b,d,-e&a,-c,e :
a or -b or c
-a or b or -d
a or b or c
-b or d or -e
a or -c or e
Example of a pretty print of an assignment for this formula:
False not(False) False = True
not(False) False not(False) = True
False False False = False
not(False) False not(True) = True
False not(False) True = True """
......@@ -14,6 +14,9 @@ def iter_syracuse(n):
n = 3*n + un
yield 1
# for val in iter_syracuse(10):
# print(val)
# ------------------------------------------------------------------------------
def iter_fibo():
......@@ -25,13 +28,17 @@ def iter_fibo():
yield un
un, un1 = un1, un + un1
# for val in iter_fibo():
# print(val)
# ------------------------------------------------------------------------------
def look_and_say_iter(z, k=1):
def look_and_say_iter():
"""La suite Look and say mise en oeuvre avec un itérateur."""
l = [1]
for _ in range(k):
while True:
yield l
......@@ -57,34 +64,125 @@ def look_and_say_iter(z, k=1):
# On met à jour la liste l
l = l2
# i = 0
# for val in look_and_say_iter():
# print(val)
# i+=1
# if i == 10:
# break
for i in look_and_say_iter(1, 10):
print(i)
# ------------------------------------------------------------------------------
#------------------------------------------------------------------------------
def iter_tous_les_facteurs(mot):
"""Création d'un itérateur qui génére tous les facteurs non vides du mot
donné en paramètre. Exemple : tous les facteurs de la chaine "abcd" sont :
a ab abc abcd b bc bcd c cd d """
pass
length = len(mot)
for intervalleX in range(length):
for intervalleY in range(intervalleX, length):
yield (mot[intervalleX: intervalleY+1])
# for val in iter_tous_les_facteurs("abcd"):
# print(val)
# ------------------------------------------------------------------------------
def decalage(liste):
length = len(liste)
return [liste[(i-1) % length] for i in range(length)]
def iter_toutes_les_listes_binaires(n):
"""Itérateur produisant toutes les listes de {0, 1} de taille n."""
pass
for i in range(2**n):
l = []
for j in range(n):
l.append((i >> j) % 2)
yield l
def iter_toutes_les_listes_binaires2(n):
def h(i):
if i == n:
yield resultat
else:
resultat[i] = 0
yield from h(i+1)
resultat[i] = 1
yield from h(i+1)
resultat = ["RIEN"] * n
yield from h(0)
# i = 0
# for val in iter_toutes_les_listes_binaires2(3):
# i += 1
# print(i,val)
# ------------------------------------------------------------------------------
def iter_nombres_premiers(v=1):
"""Itérateur produisant tous les nombres premiers à partir de v."""
import math # Bibliothèque autorisée si besoin.
pass
v = v if v % 2 == 1 else v+1
while True:
sqrtV = math.floor(math.sqrt(v))
vo2 = math.ceil(v/2)
isPrime = True
for div in range(2, sqrtV):
if v % div == 0:
isPrime = False
break
if isPrime == True:
yield v
v += 2
# i = 0
# for prime in iter_nombres_premiers(30):
# print(prime)
# i += 1
# if i == 10:
# break
# ------------------------------------------------------------------------------
def iter_tous_les_sous_ensembles(ensemble):
"""Itérateur produisant tous les sous-ensembles possibles de l'ensemble
donné en entrée."""
pass
length = len(ensemble)
for i in range(2**length):
l = []
for j in range(length):
if (i >> j) % 2 == 1:
l.append(ensemble[j])
yield l
def iter_tous_les_sous_ensembles2(ensemble):
liste = list(ensemble)
length = len(liste)
for el in iter_toutes_les_listes_binaires2(length):
yield [liste[i] for i in range(length) if el[i] == 1]
# i = 0
# for el in iter_tous_les_sous_ensembles2({"a", "b", "c", "d"}):
# i += 1
# print(i, el)
a,-b,cloclo&b,-a,-c&d,-a,-b&-cloclo,-name,-a,-b
\ No newline at end of file
......@@ -6,4 +6,26 @@
- TP
- 2h
##
\ No newline at end of file
## Prise de note du 7 Février
### Le système qu'on va utiliser
- On va travailler avec des ==équations binaires== (Vrai / Faux)
- On autorise les ==variables== (valeurs boléennes) : $x_i$
- On va utiliser : $\lnot, \lor$
- On va faire des ==littéraux== : $x_i, \lnot x_i$
- On va les manipuler avec des $\lor$ : $x_2 \lor x_4 \lor x_5$ (c'est une ==clause==)
### Les opérations sur les littéraux
- On peut donner une valeur à une variable : $x_2 = \lnot x_2$ : on dit que $x_2$ est ==assignée==
- Une clause est ==satisfaite== si au moins un de ses littéraux est vrai
- On peut faire un système de clauses :
$$\begin{array}{l}
x_1 \lor x_2 \lor x_3 \\
x_1 \lor \lnot x_2 \lor x_3 \\
\lnot x_1 \lor x_2 \lor x_3 \\
\lnot x_1 \lor \lnot x_2 \lor x_3 \\
\end{array}$$
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment