relocated teletype file

This commit is contained in:
2019-03-09 00:41:20 +01:00
parent b670f9a195
commit f089a32282
11 changed files with 717 additions and 0 deletions
Vendored
BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.
+28
View File
@@ -0,0 +1,28 @@
"""
f : mvts possibles -> prochain meilleur mvt
"""
l=[[1,2],[3,4]]
"""[1,2]=>2
[3,4]=>4
[2,4]
2"""
def minmax(arbre, level = 0, maxi = True):
if type(arbre[0]) is not list:
if max and level%2==0:
return max(arbre)
else:
return min(arbre)
else:
if max and level%2==0:
return max([minmax(e,level+1,maxi) for e in arbre])
else:
return min([minmax(e,level+1,maxi) for e in arbre])
print(minmax(l))
+211
View File
@@ -0,0 +1,211 @@
"""
Features:
1:COMPLETED: print #renvoie str
2:COMPLETED: addition #renvoie Polynomial
3:COMPLETED: multiplication #renvoie Polynomial
4:COMPLETED: derive #renvoie un Polynomial
5:COMPLETED: division #renvoie couple de Polynomial
6:COMPLETED: pgcd #renvoie Polynomial
7: ppcm #renvoie Polynomial
8: taylor #renvoie str ou liste "je sais pas encore"
9: factoriser #renvoie str ou liste de liste des coefficients "pareil"
10: racines reelles #renvoie liste des racines reelles
11: racines complexes #renvoie liste des racines complexes
12: show #Affiche le polynome sur une fenetre pygame, pyglet ou matplotlib
"""
from copy import deepcopy
class Polynomial:
def __init__(self, coefficients):
"""Create a polynomial using its coefficients."""
self.coefficients = coefficients
def __repr__(self):
"""Return the usual representation of a polynomial."""
if self.coefficients==[]:
return "0"
liste = []
if self.coefficients[0]!=0:
liste.append(str(self.coefficients[0]))
for degre,coefficient in enumerate(self.coefficients[1:],1):
if coefficient!=0:
liste.append(str(coefficient) + "X^" + str(degre))
liste.reverse()
text = "+".join(liste)
text = text.replace("^1","").replace("+-","-").replace("1X","X")
return text
def adapt(self,coefficients,size):
"""Add zeros to the coefficients using coefficients and size."""
coefficients += [0]*(size-len(coefficients))
return coefficients
def __add__(self, other):
"""Add 2 polynomials together by adding their coefficients."""
maxdegree = max(self.degree(),other.degree())
cA = self.adapt(self.coefficients,maxdegree)
cB = self.adapt(other.coefficients,maxdegree)
newcoefficients = [a+b for (a,b) in zip(cA, cB)]
return Polynomial(newcoefficients)
def __sub__(self, other):
"""Substract 2 polynomials together by multiplying the second polynomial by -1 and adding it to the first using add method."""
return self+other*Polynomial([-1])
def __mul__(self, other):
"""Multiply 2 polynomials together using the formula for the coefficients."""
degree = len(self.coefficients) + len(other.coefficients)
A = self.coefficients + [0]*(degree-len(self.coefficients)+1)
B = other.coefficients + [0]*(degree-len(other.coefficients)+1)
newcoefficients = []
for k in range(degree + 1):
coeff = 0
for i in range(k + 1):
coeff += A[i] * B[k - i]
newcoefficients.append(coeff)
C = Polynomial(newcoefficients)
C.correct()
return C
def correct(self):
"""Correct the coefficients of the polynomial by deleting useless zeros at the end,"""
while len(self.coefficients)>1:
if self.coefficients[-1] == 0:
del self.coefficients[-1]
else:
break
if self.coefficients==[0]:
self.coefficients=[]
"""and then replace float coefficients by int coefficients if possible."""
for i in range(len(self.coefficients)):
if self.coefficients[i]==int(self.coefficients[i]):
self.coefficients[i]=int(self.coefficients[i])
def __len__(self):
"""Return the number of coefficients.
It is important to notice that it is not the degree due to the fact that
the polynomial might have a degree of -inf and the len method must have positive values.
In such a case this method will raise an error.
It is why it is better to use the degree method in the general case."""
A=deepcopy(self)
A.correct()
return len(A.coefficients)-1
def degree(self):
"""Return the degree of a polynomial.
It will return -1 if the degree is -inf to be computer friendly."""
A=deepcopy(self)
A.correct()
return len(A.coefficients)-1
def __getitem__(self,index):
"""Return a coefficient of the polynomial."""
return self.coefficients[index]
def __setitem__(self,index,value):
"""Change a coefficient of the polynomial."""
self.coefficients[index] = value
def __delitem__(self,index):
"""Delete a coefficient of the polynomial."""
del self.coefficients[index]
def derivate(self):
"""Derivate the polynomial."""
self.coefficients = [i*c for (i,c) in enumerate(self.coefficients)]
del self.coefficients[0]
def derivative(self):
"""Return the derivative polynomial."""
newcoefficients = [i*c for (i,c) in enumerate(self.coefficients)]
del newcoefficients[0]
return Polynomial(newcoefficients)
def unit(self):
"""Return the polynomial unit form."""
k=self.coefficients[-1]
newcoefficients=[]
for i in range(len(self.coefficients)):
newcoefficients.append(self.coefficients[i]/k)
A=Polynomial(newcoefficients)
A.correct()
return A
def unitarize(self):
"""Convert the polynomial into its unit form."""
self=self.unit()
def __xor__(self,other):
"""Return the HCF (PGCD en francais) of self and other by Euclide algorithm. Make use of "^" operator."""
R0 = deepcopy(self)
R1 = deepcopy(other)
R0.correct()
R1.correct()
listR=[R0,R1]
R2,Q2=R0/R1
listR.append(R2)
while listR[-1].degree()>0:
R,Q=listR[-2]/listR[-1]
listR.append(R)
return listR[-2]
#Resultat d'une enorme galere de 2h...
#Algorithme d'Euclide:
#a=b*q0+r0
#b=r*q1+r1
#r=r1*q2+r2
#r1=r2*q3+r3
#...
#ri=r(i-1)*q(i-1)+1+0
def __or__(self,other):
"""Return the LCM (PPCM en francais) using "i have absolutely no clue how to do this so figure it out!" Make use of "|" operator."""
#On sent la (tres) grosse fatigue apres minuit.
return "Figure it out!"
def __truediv__(self, other):
"""Return the division of 2 polynomials."""
R = deepcopy(self)
B = deepcopy(other)
R.correct()
B.correct()
Q = Polynomial([])
while R.degree()>=B.degree():
d = R.degree()-B.degree()+1
C = Polynomial([0 for i in range(d)])
C[-1] = R[-1]/B[-1]
R = R-B*C
Q = Q+C
Q.correct()
R.correct()
return [R,Q]
#Ce que j'ai du faire pour trouver l'implementation...
#On a: A=BQ+R
#[3,2,4,5,1]/[1,4,1]
#[3,2,3,1,0]=[3,2,4,5,1]-[0,0,1]*[1,4,1] #[0,0,1,4,1]
#[3,1,-1,0]=[3,2,3,1]-[0,1]*[1,4,1] #[0,1,4,1]
#[4,5,0]=[3,1,-1]-[-1]*[1,4,1] #[-1,-4,-1]
#[4,5]
#5=8*0+5 cas particulier de la division euclidienne
if __name__ == "__main__":
suite1 = [3,2,4,5,1]
suite2 = [1,4,1]
suite3 = [4,5]
A = Polynomial(suite1)
B = Polynomial(suite2)
C = Polynomial(suite3)
print("A =",A)
print("B =",B)
print("C =",C)
print("A+B =",A+B)
print("A*B =",A*B)
print("Derivative of A =",A.derivative())
print("A/B :",A/B)
print("Unit polynomial of C =",A.unit())
print("HCF (PGCD en francais) of A and B (written A^B) =",A^B)
print("LCM (PPCM en francais) of A and B (written A|B) =",A|B)
+83
View File
@@ -0,0 +1,83 @@
import random
class Puissance4:
def __init__(self):
self.board = Board()
self.players = [Player(0),Player(1)]
self.state = 0
def __call__(self):
while self.board.on:
self.board.check()
self.state += 1
turn = self.state % 2
player = self.players[turn]
player(self.board)
class Board:
def __init__(self,size=[7,6]):
self.size = size
self.grid = [[-1 for y in range(size[1])] for x in range(size[0])]
def check(self):
pass
def randomfill(self):
sx,sy=self.size
for x in range(sx):
for y in range(sy):
self.grid[x][y]=random.randint(-1,1)
def __repr__(self):
text=""
lx=[]
for x in range(self.size[0]):
ly=[]
for y in range(self.size[1]):
if self.grid[x][y]==-1:
ly.append(" ")
if self.grid[x][y]==0:
ly.append("X")
if self.grid[x][y]==1:
ly.append("O")
lx.append("|".join(ly))
text="\n".join(lx)
return text
class Player:
def __init__(self,side):
self.side = side
def __call__(self,board): #Jouer
self.randomPlay(board)
def randomPlay(self,board):
a=list(range(self.size[0]))
random.shuffle(a)
for e in a:
choice=self.choose(board,e)
if choice is not None:
x,y=choice
board.grid[x][y]=self.side
def choose(self,board,x):
l=list(range(self.size[1]))
l.reverse()
for y in l:
v=self.grid[x][y]
if v==0 or v==1:
return (x,y)
return None
def play(self,board,x):
i = board.size[2]
if board.grid[x].count(-1) == 0 or x > "grosse valeur inutile juset la pour que le programme plante pas quand je le test":
while board.grid[x][i] != -1:
i -= 1
game = Puissance4()
game()
#game.board.randomfill()
#print(str(game.board))
+18
View File
@@ -0,0 +1,18 @@
BLUE = ( 0, 0,255)
RED = (255, 0, 0)
GREEN = ( 0,255, 0)
YELLOW = (255,255, 0)
BLACK = ( 0, 0, 0)
WHITE = (255,255,255)
GREY = (100,100,100)
PURPLE = (100, 0,100)
HALFGREY = ( 50, 50, 50)
DARKGREY = ( 20, 20, 20)
DARKRED = ( 10, 10, 10)
DARKGREEN = ( 10, 10, 10)
DARKBLUE = ( 10, 10, 10)
LIGHTBROWN = (229,219,222)
LIGHTGREY = (200,200,200)
BEIGE = (199,175,138)
print("mycolors imported")
+294
View File
@@ -0,0 +1,294 @@
from __future__ import division
from mycolors import *
import pygame
from pygame.locals import *
import time
import json
class Window:
made=0
def __init__(self,name="Unnamed",size=None,text_font="monospace",text_size=65,text_color=WHITE,background_color=BLACK,fullscreen=False,build=True):
"""Create a window object using name, size text_font, text_size, text_color, background and set."""
Window.made+=1
self.number=Window.made
self.name=name
self.size=size
self.text_font=text_font
self.text_size=text_size
self.text_color=text_color
self.background_color=background_color
self.fullscreen=fullscreen
self.set()
self.log("Window has been created.")
if build:
self.build()
def set(self):
"""Set builtins attributs of window object."""
self.RIGHT = 0
self.UP = 1
self.LEFT = 2
self.DOWN = 3
self.selecter_color=self.reverseColor(self.background_color)
self.open=False
self.screenshots_taken=0
self.pause_cool_down=1
self.time=time.time()
self.pause_time=0.2
def build(self):
"""Creates apparent window."""
pygame.init()
self.info = pygame.display.Info()
self.font = pygame.font.SysFont(self.text_font, self.text_size)
if self.size is None:
if self.fullscreen:
self.size=[self.info.current_w,self.info.current_h]
else:
self.size=[2*self.info.current_w//3,2*self.info.current_h//3]
self.coordonnates=[0,0]+self.size
if self.fullscreen:
self.screen=pygame.display.set_mode(self.size,FULLSCREEN)
else:
self.screen=pygame.display.set_mode(self.size,RESIZABLE)
pygame.display.set_caption(self.name)
if self.text_color is None:
self.text_color=self.reverseColor(self.background_color)
self.clear()
self.flip()
self.open=True
def clear(self,color=None):
"""Clear to background color."""
if color is None:
color=self.background_color
self.screen.fill(color)
def scale(self,picture,size):
"""Return scaled picture using picture and size."""
return pygame.transform.scale(picture,size)
def check(self):
"""Update window's state depending if close buttons are pressed."""
for event in pygame.event.get():
if event.type == pygame.QUIT:
self.open=False
if event.type == KEYDOWN:
if event.key == K_ESCAPE:
self.open=False
def update(self):
"""Updates all window's main attributs."""
self.mouse_click=bool(pygame.mouse.get_pressed()[0])
self.mouse_position=pygame.mouse.get_pos()
for event in pygame.event.get():
if event.type == pygame.QUIT:
self.open=False
if event.type == KEYDOWN:
if event.key == K_ESCAPE:
self.open=False
def pause(self):
"""Wait for user to click on space."""
while self.open:
self.check()
keys=pygame.key.get_pressed()
if keys[K_SPACE]:
break
if self.open:
time.sleep(self.pause_time)
def press(self):
"""Return all keys."""
return pygame.key.get_pressed()
def direction(self):
"""Return keys for arrows pressed. Trigonometric orientation is used."""
keys=pygame.key.get_pressed()
return (keys[K_RIGHT],keys[K_UP],keys[K_LEFT],keys[K_DOWN])
def select(self):
"""Wait for user to click on screen, then return cursor position."""
while self.open:
self.check()
for event in pygame.event.get():
if event.type == MOUSEBUTTONDOWN and event.button == 1:
return (event.pos[0],event.pos[1])
def point(self):
"""Return cursor position on screen."""
return pygame.mouse.get_pos()
def click(self):
"""Return bool value for clicking on screen."""
return bool(pygame.mouse.get_pressed()[0])
def press(self):
"""Return bool value for clicking on screen."""
return pygame.key.get_pressed()
def flip(self):
"""Refresh screen."""
pygame.display.flip()
def screenshot(self):
"""Save picture of the surface."""
self.picture_saved+=1
pygame.image.save(self.screen,self.name+"-"+str(self.picture_saved)+".png")
def getPicture(self,picture_directory):
"""Return picture using picture directory."""
return pygame.image.load(picture_directory)
def placePicture(self,picture_directory,coordonnates,color=None):
"""Draw a picture on screen using pygame picture directory and position."""
x,y,sx,sy=coordonnates
picture=pygame.image.load(picture_directory)
picture=pygame.transform.scale(picture,(sx,sy))
if color is not None:
picture=colorize(picture,color)
self.screen.blit(picture, position)
def centerText(self,message,size=None):
"""Centers Text on screen."""
sx,sy=self.size
if size is None:
size=self.text_size
l=len(message)
letter_size=size/4
x=sx//2-letter_size*l//2
y=sy//2-size/3
return (x,y)
def alert(self,message):
"""Quickly display text on window."""
position=self.centerText(message)
self.print(message,position)
self.flip()
def print(self,text,position,size=None,color=None,font=None):
"""Display text on screen using position, size, color and font."""
if size is None:
size=self.text_size
if color is None:
color=self.text_color
if font is None:
font=self.font
label = font.render(text, 1, color)
self.screen.blit(label, position)
def drawRect(self,coordonnates,color):
"""Draw a rectangle on the screen using color and coordonnates relative to window's fiducials."""
wsx,wsy=self.size
wcx,wcy,wcsx,wcsy=self.coordonnates
rcx,rcy,rcsx,rcsy=coordonnates
x,y=(rcx-wcx,rcy-wcy)
w,h=(rcsx*wsx/wcsx,rcsy*wsy/wcsy)
pygame.draw.rect(self.screen,color,(x,y,w,h),0)
def place(self,position):
"""Return position relative to window's fiducials."""
wcx,wcy,wcsx,wcsy=self.coordonnates
pcx,pcy=position
x,y=(rcx-wcx,rcy-wcy)
return (x,y)
def randomColor(self):
"""Return random color."""
import random
r=random.randint(0,255)
g=random.randint(0,255)
b=random.randint(0,255)
color=(r,g,b)
return color
def reverseColor(self,color):
"""Return reverse color."""
r,g,b=color
r=255-r
g=255-g
b=255-b
color=(r,g,b)
return color
def lighten(self,color,luminosity=80): #View later
"""Return lightened color using color and luminosity percentage."""
r,g,b=color
if luminosity>=50:
r+=(255-r)*luminosity/100
g+=(255-g)*luminosity/100
b+=(255-b)*luminosity/100
else:
r-=r*luminosity/100
g-=g*luminosity/100
b-=b*luminosity/100
color=r,g,b
return color
def colorize(self,image, color):
"""Return image colorized"""
image = image.copy()
image.fill((0,0,0,255),None,pygame.BLEND_RGBA_MULT)
image.fill(color[0:3]+(0,),None,pygame.BLEND_RGBA_ADD)
return image
def wavelengthToRGB(self,wavelength):
"""Convert wavelength to rgb color type."""
gamma,max_intensity=0.80,255
def adjust(color, factor):
if color==0: return 0
else: return round(max_intensity*pow(color*factor,gamma))
if 380<=wavelength<=440: r,g,b=-(wavelength-440)/(440-380),0,1
elif 440<=wavelength<=490: r,g,b=0,(wavelength-440)/(490-440),1
elif 490<=wavelength<=510: r,g,b=0,1,-(wavelength-510)/(510-490)
elif 510<=wavelength<=580: r,g,b=(wavelength-510)/(580-510),1,0
elif 580<=wavelength<=645: r,g,b=1,-(wavelength-645)/(645-580),0
elif 645<=wavelength<=780: r,g,b=1,0,0
else: r,g,b=0,0,0
if 380<=wavelength<=420: factor=0.3+0.7*(wavelength-380)/(420-380)
elif 420<=wavelength<=701: factor=1
elif 701<=wavelength<=780: factor=0.3+0.7*(780-wavelength)/(780-700)
else: factor=0
r,g,b=adjust(r,factor),adjust(g,factor),adjust(b,factor)
return (r,g,b)
def kill(self):
"""Quit pygame."""
pygame.quit()
def log(self,message):
"""Print message with window mention."""
text="["+self.name+"] "+message
print(text)
def __del__(self):
"""Executed before the window is destroyed."""
self.log("Window has been closed.")
if __name__=="__main__":
w=Window("Window Prototype")
#save(w,"grosse fenetre")
#w=load("grosse fenetre")
#print(w.lighten(BLUE))
#w.alert("test")
w.pause()
w.clear()
w.alert("je raconte de la merde juste pour avoir une longue chaine de caractere")
w.pause()
w.kill()
+3
View File
@@ -0,0 +1,3 @@
import pygame
from mywindow import Window
+80
View File
@@ -0,0 +1,80 @@
import numpy as np
from math import sqrt
import random
from copy import deepcopy
def pgcd(a,b):
t = b
b = a % b
if b == 0:
return t
else:
return pgcd(t,b)
def ppcm(a, b):
return a * b // pgcd(a, b)
def transvection(a,i,j):
"""Anciennement appelee la sainte transvection"""
if a[j][i]!=0:
p = ppcm(a[i][i],a[j][i])
k1 = p//a[i][i]
k2 = p//a[j][i]
a[i] *= k1
a[j] *= k2
a[j] = a[i]-a[j]
return a
def transpose(a):
"""Echange l'abscisse et l'ordonnee pour chaque case"""
b=np.array([[a[i][j] for i in range(a.shape[1])] for j in range(a.shape[0])])
return b
def exchange(a,j1,j2):
"""Li1 <-> Li2"""
l = deepcopy(a[j1])
a[j1] = deepcopy(a[j2])
a[j2] = l
return a
def index_pivot(a, i,jmin):
"""Renvoie un pivot"""
for j in range(jmin,len(a)):
if a[j][i] != 0:
return j
def triangular(a):
"""Renvoie la matrice triangularise"""
for i in range(len(a[0])-1):
jmin=i+1
jp = index_pivot(a,i,jmin)
if a[i][i]==0:
a = exchange(a,i,jp)
for j in range(jmin,len(a)):
a = transvection(a,i,j)
for j in range(len(a)):
a[j]=a[j]/pgcdl(a[j])
return a
def identity(a):
pass
def pgcdl(l):
"""Renvoie le pgcd d'une liste"""
p=l[0]
for i in range(1,len(l)):
p=pgcd(p,l[i])
return p
if __name__=="__main__":
c=5 #taille de la matrice carre de depart
a=np.array([[random.randint(0,10) for i in range(c)] for j in range(c)])
print(a)
b=triangular(a)
print(b)
#c=transpose(b)
#print(c)