Skip to content

Instantly share code, notes, and snippets.

@lefuturiste
Created January 15, 2021 18:47
Show Gist options
  • Save lefuturiste/40ebaff0a7bac51a2b2f989d5fee4f6f to your computer and use it in GitHub Desktop.
Save lefuturiste/40ebaff0a7bac51a2b2f989d5fee4f6f to your computer and use it in GitHub Desktop.
TP_10
## Exercice 1
from math import log
def chaine_num(c):
#d = int(log(n)/log(256))
d = len(c)
N = 0
for k in range(d):
N += ord(c[k])*(256**k)
return N
def num_chaine(N):
k = 0
r = ''
while N > 0:
c = N % 256
N = N // 256
r += chr(c)
return r
## Exercice 4
from numpy import random as rd
from difflib import SequenceMatcher
class strColors:
HEAD = '\033[95m'
BLUE = '\033[94m'
SUCC = '\033[92m'
WARN = '\033[93m'
ERRO = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDE = '\033[4m'
def reviser(filePath):
# de quel langue à quel langue vous voulez vous entrainer ?
# a n'importe quelle moment taper 'QUIT' pour quitter
try:
file = open(filePath, 'rt', encoding='utf-8')
except FileNotFoundError:
print(f"{strColors.ERRO}❌ Chemin du fichier invalide :({strColors.ENDC}")
return
# on va parser le csv pour faire une structure de donnée de type:
langs = []
langsName = []
vocabulary = []
rawContent = file.readlines()
if len(rawContent) < 2:
print(f"{strColors.ERRO}❌ Il faut au moins deux lignes dans le fichier de révision :({strColors.ENDC}")
return
# on parse la première ligne
for lang in rawContent[0].strip().split(','):
lang = lang.strip()
if len(lang) == 0:
print(f"{strColors.ERRO}❌ Langue invalide ligne 1 :({strColors.ENDC}")
return
if lang in langs:
print(f"{strColors.ERRO}❌ Langue dupliqué :({strColors.ENDC}")
return
langs.append(lang)
# on parse la seconde ligne
for name in rawContent[1].strip().split(','):
name = name.strip()
if len(name) == 0:
print(f"{strColors.ERRO}❌ Nom de langue invalide ligne 2 :({strColors.ENDC}")
return
if name in langsName:
print(f"{strColors.ERRO}❌ Langue dupliqué :({strColors.ENDC}")
return
langsName.append(name)
if len(langs) < 2:
print(f"{strColors.ERRO}❌ Il faut au moins deux langues dans le fichier de révision :({strColors.ENDC}")
return
# on parse tout les mots
for i, line in enumerate(rawContent):
if i == 0 or i == 1:
continue
compo = line.split(',')
if len(compo) != len(langs):
print(f"{strColors.ERRO}❌ Je m'attendais à avoir {len(langs)} mots j'en ai eu {len(compo)} à la ligne {i+1} :({strColors.ENDC}")
return
word = []
for rawWord in compo:
rawWord = rawWord.strip()
if len(rawWord) < 2:
print(f"{strColors.ERRO}❌ Mot invalide à la ligne {i+1} :({strColors.ENDC}")
word.append(rawWord)
vocabulary.append(word)
print(f"{strColors.SUCC}✅ Fichier valide ! Avec {len(langs)} langues et {len(vocabulary)} mots. {strColors.ENDC}")
print(f"🏁 Langues supportés : {langs}")
## DEMANDE DE LA LANGUE
print(f"{strColors.BLUE}❓ De quel langue à quel langue souhaitez vous révisez ?{strColors.ENDC} Syntaxe: [langue d'origine]->[langue à apprendre]{strColors.ENDC} :")
ans = ''
originLang = ''
learningLang = ''
validAns = False
while not validAns:
ans = input('')
compo = ans.split('->')
if len(compo) == 2 and compo[0] in langs and compo[1] in langs and compo[0] != compo[1]:
validAns = True
if not validAns:
print(f"{strColors.ERRO}❌ Je ne suis pas sur de comprendre ce que tu veux dire 🤔🤔{strColors.ENDC}")
originLang = compo[0]
originIndex = langs.index(originLang)
learningLang = compo[1]
learningIndex = langs.index(learningLang)
## DEMANDE DE LA LONGUEUR DE L'ENTRAINEMENT
questions = raw = 20
print(f"{strColors.BLUE}❓ Combien de questions voulez vous ?{strColors.ENDC} (20 par défaut){strColors.ENDC} :")
validAns = False
while not validAns:
ans = input('')
if ans == '': break
try:
raw = int(ans)
except ValueError:
raw = 0
if raw > 1 and raw < 1000: validAns = True
if not validAns:
print(f"{strColors.ERRO}❌ Oula qu'est ce que c'est que ça!!{strColors.ENDC}")
questions = raw
print(questions)
vocPonderation = [1/len(vocabulary)]*len(vocabulary)
print(f'{strColors.HEAD}Bonne séance ! A tout moment vous pouvez la quitter avec le mot clé "QUIT!".{strColors.ENDC}')
chooseToEnd = False
score = total = 0
while not chooseToEnd:
#print('somme', sum(vocPonderation))
vocIndex = rd.choice(range(len(vocabulary)), p=vocPonderation)
#print('vocIndex', vocIndex)
voc = vocabulary[vocIndex]
# mode 1 : origin word is given, you have to give the coresponding learing word -- 70% of the time
# mode 2 : learning word is given, you have to give the coresponding origin word -- 30% of the time
fromLearning = bool(rd.choice(2, p=[0.78, 0.22]))
if fromLearning:
questionIndex, answerIndex = learningIndex, originIndex
else:
questionIndex, answerIndex = originIndex, learningIndex
total += 1
def redistribute(data, toRedistribute, offset = 0, poundIndex = None):
# counter les nb de donne neg
nbOfNull = len(list(filter(lambda x: x==0, data)))
toRedistributeToEach = toRedistribute/(len(data)-nbOfNull+offset)
if poundIndex != None:
data[poundIndex] -= toRedistribute
print(poundIndex, toRedistribute, toRedistributeToEach, data)
for i in range(len(data)):
if poundIndex != None and i == poundIndex: continue
if data[i] == 0: continue
data[i] += toRedistributeToEach
# si négatif, retour à 0
if data[i] < 0: data[i] = 0
return data
ans = input(f'Traduire "{voc[questionIndex]}" en {langsName[answerIndex]} : ')
if ans == 'QUIT!':
chooseToEnd = True
else:
similarity = lambda x, y: SequenceMatcher(None, x, y).ratio()
res = similarity(ans.lower(), voc[answerIndex].lower())
toRedistribute = None
if res == 1:
print(f"{strColors.SUCC}✅ Bravo !{strColors.ENDC}")
# on elève 50% de sa ponderation
toRedistribute = 0.75*vocPonderation[vocIndex]
# on rajoute 1 pt au score
score += 1
elif res > 0.88:
# on elève 25% de sa ponderation
toRedistribute = 0.10*vocPonderation[vocIndex]
print(f"{strColors.WARN}⚠️ Presque ça, la bonne orthographe était : \"{voc[answerIndex]}\" {strColors.ENDC}")
# on rajoute 0.88 pt au score
score += 0.88
else:
# on va lui ajouter 50% de sa ponderation
toRedistribute = -0.50*vocPonderation[vocIndex]
print(f"{strColors.ERRO}❌ Pas bon, c'était : \"{voc[answerIndex]}\" {strColors.ENDC}")
# on redistribue la valeur de ponderation qui a été enlevé
if toRedistribute != None:
#vocPonderation = redistribute(vocPonderation, toRedistribute, offset=-1, poundIndex=vocIndex)
toRedistributeToEach = toRedistribute/(len(vocPonderation)-1)
vocPonderation[vocIndex] -= toRedistribute
#print(vocIndex, toRedistribute, toRedistributeToEach, vocPonderation)
for i in range(len(vocPonderation)):
if i == vocIndex: continue
vocPonderation[i] += toRedistributeToEach
# si négatif, retour à 0
if vocPonderation[i] < 0: vocPonderation[i] = 0
# hack to equalize
sump = sum(vocPonderation)
vocPonderation = list(map(lambda x: x/sump, vocPonderation))
if total >= questions: chooseToEnd = True
print(f"💯 {strColors.BLUE} Votre score est de {score}/{total} soit {score/total*20}/20 {strColors.ENDC}")
# Utilisation: reviser('./vocabulaire.csv')
fr de en
Français Allemand Anglais
une patate eine kartoffel a potato
une maison eine house a home
un couteau qdsldlsq a knife
un ordinateur ein Computer a Computer
bonjour guten tag hello
merci danke thanks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment