diff --git a/.DS_Store b/.DS_Store index ca8b31c..ecfd01c 100644 Binary files a/.DS_Store and b/.DS_Store differ diff --git a/Fox Snow Dive - Yellowstone - BBC Two-dP15zlyra3c.mp4.part b/Fox Snow Dive - Yellowstone - BBC Two-dP15zlyra3c.mp4.part new file mode 100644 index 0000000..bb0317d Binary files /dev/null and b/Fox Snow Dive - Yellowstone - BBC Two-dP15zlyra3c.mp4.part differ diff --git a/HackerRank/between two sets.py b/HackerRank/between two sets.py new file mode 100644 index 0000000..e9be3eb --- /dev/null +++ b/HackerRank/between two sets.py @@ -0,0 +1,81 @@ +def pgcd(a,b): + if a==0: + return b + if b==0: + return a + a=abs(a) + b=abs(b) + mi=min(a,b) + ma=max(a,b) + if ma%mi==0: + return mi + else: + return pgcd(ma-mi,mi) + +def pgcds(l): + a=float("inf") + for i in range(len(l)): + for j in range(i+1,len(l)): + na=pgcd(l[i],l[j]) + if naa: + a=na + return na + + +a=[2,4] +b=[16,32,96] + +def divideAll(d,l): + for e in l: + if e%d!=0: + return False + return True + +def multipleOfAll(m,l): + for e in l: + if m%e!=0: + return False + return True + + +"""l=[] +pa=pab=ppcms(a) +pb=pgcds(b) +print(pa) +print(pb) +while pa<=min(b): + if divideAll(pa,b): + l.append(pa) + pa+=pab + print(pa,divideAll(pa,b))""" + + + +l=list(range(max(a),min(b)+1)) + +fl=[] +for e in l: + if divideAll(e,b) and multipleOfAll(e,a): + fl.append(e) + +print(len(fl)) diff --git a/HackerRank/birthday.py b/HackerRank/birthday.py new file mode 100644 index 0000000..8e34db2 --- /dev/null +++ b/HackerRank/birthday.py @@ -0,0 +1,18 @@ +import itertools + +s=list(range(6)) + +scy=itertools.cycle(iter(s)) + +def extract(it,mi,ma): + it1,it = itertools.tee(it) + return ([next(it1) for i in range(ma)][mi:],it) + + +a,scy=extract(scy,1,3) + +print(a) +print(extract(scy,1,3)) + + +print(" ".join(map(str,s))) diff --git a/HackerRank/chess.py b/HackerRank/chess.py new file mode 100644 index 0000000..7901c26 --- /dev/null +++ b/HackerRank/chess.py @@ -0,0 +1,28 @@ +import random + +def queensAttack(n, k, r_q, c_q, obstacles): + f=lambda o:(1<=o[0]<=n and 1<=o[1]<=n) + obstacles=list(filter(f,obstacles)) + nob=[[x-r_q,y-c_q] for [x,y] in obstacles] + obstacles=[[x,y] for (x,y) in list(set([(x,y) for (x,y) in obstacles]))] + def polar(x,y): + n=math.sqrt(x**2+y**2) + + + + directions=[[x,y] for x in [-1,0,1] for y in [-1,0,1] if (x,y)!=(0,0)] + a=0 + for direction in directions: + dx,dy=direction + x,y=r_q+dx,c_q+dy + while f([x,y]): + if [x,y] in obstacles: + break + x+=dx + y+=dy + a+=1 + return a + + + +print(queensAttack(100,50,6,7,[[random.randint(1,100),random.randint(1,100)] for i in range(50)])) diff --git a/HackerRank/hackerrank samy.py b/HackerRank/hackerrank samy.py new file mode 100644 index 0000000..9eb6e24 --- /dev/null +++ b/HackerRank/hackerrank samy.py @@ -0,0 +1,14 @@ +import functools + +binary=lambda x,m:list(reversed([int((x%2**(i+1))//2**i) for i in range(m)])) +xor=lambda l:list(map(lambda x:1-x,l)) +decimal=lambda l:sum([v*2**i for (i,v) in enumerate(list(reversed(l)))]) +prod=lambda l:functools.reduce(lambda a,b:a*b,l) + +n=5 +a=prod(list(range(1,n+1))) +print(a) + +a=binary(a,32) +a=xor(a) +a=decimal(a) diff --git a/HackerRank/matrix rotation.py b/HackerRank/matrix rotation.py new file mode 100644 index 0000000..80c0e6a --- /dev/null +++ b/HackerRank/matrix rotation.py @@ -0,0 +1,53 @@ +import random + + + + +def getNewPosition(x,y,w,h,r): + d=min(min(w-1-x,x),min(h-1-y,y)) + while r>0 and not(h==w==0): + r-=1 + if x==d and y!=h-1-d: + x,y=(x,y+1) + continue + if y==d and x!=d: + x,y=(x-1,y) + continue + if x==w-1-d and y!=d: + x,y=(x,y-1) + continue + if y==h-1-d and x!=w-1-d: + x,y=(x+1,y) + continue + return (x,y) + +def rotate(m,r=1): + h=len(m) + w=len(m[0]) + if w>1 and h>1: r%=(2*(h+w-2)) + nm=[[0 for x in range(w)] for y in range(h)] + for x in range(w): + for y in range(h): + nx,ny=getNewPosition(x,y,w,h,r) + nm[ny][nx]=m[y][x] + return nm + +def toSpaceStr(m): + t=[] + for y in range(len(m)): + t.append(" ".join([str(e) for e in m[y]])) + return "\n".join(str(e) for e in t) + +x1,y1=[random.randrange(2,10,2) for i in range(2)] + +m=[[random.randint(1,9) for x in range(5)] for y in range(4)] +m=[[y*4+x+1 for x in range(4)] for y in range(4)] +#m=[[0]] + + +tm=toSpaceStr(m) +print(tm,end='\n\n') + +rm=rotate(m,2) +trm=toSpaceStr(rm) +print(trm,end='') diff --git a/Info/.DS_Store b/Info/.DS_Store index d85a630..bebb423 100644 Binary files a/Info/.DS_Store and b/Info/.DS_Store differ diff --git a/Info/Td/TD12-TableauxEtPivotDeGauss.py b/Info/Td/TD12-TableauxEtPivotDeGauss.py new file mode 100644 index 0000000..471d43f --- /dev/null +++ b/Info/Td/TD12-TableauxEtPivotDeGauss.py @@ -0,0 +1,164 @@ +import random + +#1 +A= [[1,2,-1], + [-2,0,3], + [4,1,-1]] + + +print("Matrice:",A) + +#2 +#print(A[1]) + +#3 +#print(A[1][2]) + +#4 +#print(A[:][1]) + +#5a +def MatNulle(n,p): + """Cree la matrice nulle de taille np.""" + return [[0 for j in range(p)] for i in range(n)] + +#5b +print("Matrice Nulle de taille (n,p):",MatNulle(3,4)) + +#5c +def MatNulleBis(n,p=None): + """Cree la matrice nulle de taille np.""" + if not p: p=n + return [[0 for j in range(p)] for i in range(n)] + + +#5d +print("Matrice nulle carre:",MatNulleBis(5)) + +#5e +def MAlea(k,n,p=None): + """Cree la matrice comporant n lignes, p colonnes et dont les coefficients sont des entiers aleatoires de [-k,k].""" + if not p: p=n + return [[random.randint(-k,k) for j in range(p)] for i in range(n)] + +#6 +def Pivot(M,j): + """Renvoie l'index de la ligne i qui contient l'élément de la colonne M d'indice j qui a la plus grande valeur absolue.""" + m=abs(M[j][j]) + p=j + for i in range(j+1,len(M)): + t=M[i][j] + if abs(t)>m: + m=t + p=i + return p + +print("pivot:",Pivot(A,0)) + + +#7 +def EchangerLigne(M,i,l): + """Permet d'echanger la i-eme ligne et la l-eme ligne de la matrice M.""" + M[i],M[l]=M[l],M[i] + + +EchangerLigne(A,0,1) +print(A) + +#8 +def CombLigne(M,i,l,r): + """Permet de remplacer la ligne i de la matrice M par Li-r*Ll.""" + M[i]=[M[i][j]-r*M[l][j] for j in range(len(M[i]))] + +#CombLigne(A,1,0,A[Pivot(A,0)][0]) +p=Pivot(A,0) +print(p) +EchangerLigne(A,0,p) +print(A) +CombLigne(A,1,0,A[1][0]/p) +print("Combine les lignes i et l:",A) + + +#9 Algorithme +"""Pivot Triangulaire Sup: +Donnees: M une matrice + +l<-nombre de lignes de la matrice M +Pour j de 0 a l-1 FAIRE: + p<-Pivot de la matrice m a partir de la colonne 0 + Echanger les lignes j et p de la matrice M + Pour i de j+1 a l-1 FAIRE: + Realise Li <- Li-r*Lj pour la matrice M +""" + + +#9 +def PivotTriangulaireSup(M): + """Permet de triangulariser la matrice.""" + l=len(M) + for j in range(l): + p=Pivot(M,j) + EchangerLigne(M,j,p) + if p!=0: + for i in range(j+1,l): + CombLigne(M,i,j,M[i][j]/M[j][j]) + +#10 + + +def Afficher(B,precision=3): + for i in range(len(B)): + text="" + for j in range(len(B[i])): + text+=str(float(B[i][j]))[:precision] + if j90: self.rot[0] = 90 + elif self.rot[0]<-90: self.rot[0] = -90 + + def update(self,dt,keys): + s = dt*10 + rotY = -self.rot[1]/180*math.pi + dx,dz = s*math.sin(rotY),s*math.cos(rotY) + if keys[key.W]: self.pos[0]+=dx; self.pos[2]-=dz + if keys[key.S]: self.pos[0]-=dx; self.pos[2]+=dz + if keys[key.A]: self.pos[0]-=dz; self.pos[2]-=dx + if keys[key.D]: self.pos[0]+=dz; self.pos[2]+=dx + + if keys[key.SPACE]: self.pos[1]+=s + if keys[key.LSHIFT]: self.pos[1]-=s + + +class Window(pyglet.window.Window): + + def push(self,pos,rot): glPushMatrix(); glRotatef(-rot[0],1,0,0); glRotatef(-rot[1],0,1,0); glTranslatef(-pos[0],-pos[1],-pos[2],) + def Projection(self): glMatrixMode(GL_PROJECTION); glLoadIdentity() + def Model(self): glMatrixMode(GL_MODELVIEW); glLoadIdentity() + def set2d(self): self.Projection(); gluOrtho2D(0,self.width,0,self.height); self.Model() + def set3d(self): self.Projection(); gluPerspective(70,self.width/self.height,0.05,1000); self.Model() + + def setLock(self,state): self.lock = state; self.set_exclusive_mouse(state) + lock = False; mouse_lock = property(lambda self:self.lock,setLock) + + def __init__(self,*args,**kwargs): + """Create pyglet window.""" + super().__init__(*args,**kwargs) + self.set_minimum_size(300,200) + self.keys = key.KeyStateHandler() + self.push_handlers(self.keys) + pyglet.clock.schedule(self.update) + + self.model=Model2() + self.player=Player((0.5,1.5,1.5),(-30,0)) + + def on_mouse_motion(self,x,y,dx,dy): + """Set the parameters of the view of the player using the position of the mouse.""" + if self.mouse_lock: self.player.mouse_motion(dx,dy) + + def on_key_press(self,KEY,MOD): + """Determine if the window must be closed.""" + if KEY == key.ESCAPE: self.close() + #elif KEY == key.E: self.mouse_lock = not self.mouse_lock + self.mouse_lock=True + + def update(self,dt): + """Update the player's view using time dt and knowning keys.""" + self.player.update(dt,self.keys) + + def on_draw(self): + """Overload function automatically called by the pyglet window while running.""" + self.clear() + self.set3d() + self.push(self.player.pos,self.player.rot) + self.model.draw() + glPopMatrix() + + +if __name__ == '__main__': + window = Window(width=1440,height=900,caption='Minecraft',fullscreen=True) + r,g,b,alpha=0,0,0,1 #Color of the background and transparency alpha, each component's value must be between 0 and 1 + glClearColor(r,g,b,alpha) #Apply the background + #glEnable allows to change the parameters of the opengl interface + glEnable(GL_DEPTH_TEST) #Allow the objects not to be displayed when behing others, must be enabled to prevent weird bugs + #glEnable(GL_CULL_FACE) + pyglet.app.run() diff --git a/Sockets/chat client.py b/Sockets/chat client.py new file mode 100644 index 0000000..e69de29 diff --git a/Sockets/chat server.py b/Sockets/chat server.py new file mode 100644 index 0000000..69dc62d --- /dev/null +++ b/Sockets/chat server.py @@ -0,0 +1,64 @@ +import socket +import select + +HEADER_LENGTH=10 +IP="127.0.0.1" +PORT=1234 + + +server_socket=socket.socket(socket.AF_INET,socket.SOCK_STREAM) +server.socket.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1) + +server_socket.bind((IP,PORT)) + +server_socket.listen() + +sockets_list=[server_socket] + +clients={} + +def receive_message(client_socket): + try: + message_header=client_socket.recv(HEADER_LENGTH) + if not len(message_header): + return False + else: + message_length=int(message_header.decode("utf-8").strip()) + return {"header":message_header,"data":client_socket.recv(message_length)} + except: + return False + +while True: + read_sockets,_,exception_sockets=select.select(sockets_list,[],sockets_lists) + for notified_socket in read_sockets: + if notified_socket==server_socket: + client_socket,client_address=server_socket + + user = receive_message(client_socket) + if user is False: + continue + + sockets_list.append(client_socket) + + clients[client_socket]=user + + print(f"Accepted new connection from {client_address[0]}:{client_address[1]} username: {user['data'].decode('utf-8')}") + + else: + message=receive_message(notified_socket) + if message is False: + print(f"Closed connection from {clients[notified_socket]['data'].decode('utf-8')}) + sockets_list.remove(notified_socket) + del clients[notified_sockets] + continue + + user = clients[notified_socket] + + print(f"Received message from {user['data'].decode('utf-8')}: {message['data'].decode('utf-8')}") + for client_socket in clients: + if client_socket != notified_socket: + client_socket.send(user['header']+user['data']+message['header']+message['data']) + + for notified_socket in exception_sockets: + sockets_list.remove(notified_socket) + del clients[notified_socket] diff --git a/Sockets/client.py b/Sockets/client.py new file mode 100644 index 0000000..4beaec1 --- /dev/null +++ b/Sockets/client.py @@ -0,0 +1,31 @@ +import socket +import pickle + +HEADERSIZE=10 + +s=socket.socket(socket.AF_INET,socket.SOCK_STREAM) +s.connect((socket.gethostname(),1234)) + +while True: + full_msg=b'' + new_msg=True + while True: + msg=s.recv(16) + if new_msg: + print(f"new message length: {msg[:HEADERSIZE]}") + msglen=int(msg[:HEADERSIZE]) + new_msg=False + + full_msg+=msg + + if len(full_msg)-HEADERSIZE==msglen: + print("fullmsg recvd") + print(full_msg[HEADERSIZE:]) + + d=pickle.loads(full_msg[HEADERSIZE:]) + print(d) + + new_msg=True + full_msg=b'' + + print(full_msg) diff --git a/Sockets/server.py b/Sockets/server.py new file mode 100644 index 0000000..3cf5921 --- /dev/null +++ b/Sockets/server.py @@ -0,0 +1,21 @@ +import socket +import time +import pickle + + +HEADERSIZE=10 + +s=socket.socket(socket.AF_INET,socket.SOCK_STREAM) +s.bind((socket.gethostname(),1234)) +s.listen(5) + +while True: + clientsocket,address=s.accept() + print(f"Connection from {address} has been established!") + + d={1:"Hey",2:"There"} + msg=pickle.dumps(d) + + msg=bytes(f'{len(msg):<{HEADERSIZE}}',"utf-8")+msg + + clientsocket.send(msg) diff --git a/Sockets/test infinite loop.py b/Sockets/test infinite loop.py new file mode 100644 index 0000000..747098e --- /dev/null +++ b/Sockets/test infinite loop.py @@ -0,0 +1,2 @@ +while True: + print("Shut me off!") diff --git a/Tests/test pydoc.py b/Tests/test pydoc.py new file mode 100644 index 0000000..9f925a9 --- /dev/null +++ b/Tests/test pydoc.py @@ -0,0 +1,3 @@ +import errno + +print(errno.E2BIG) diff --git a/Tests/test2 pydoc.py b/Tests/test2 pydoc.py new file mode 100644 index 0000000..a896e52 --- /dev/null +++ b/Tests/test2 pydoc.py @@ -0,0 +1,7 @@ +#-utf8:# -*- coding: utf-8 -*- + + +import pwd + +print(pwd.getpwall()) +#print(len(pwd.getpwnam("olivierpartensky").pw_passwd)) diff --git a/Youtube/youtube-dl-2.py b/Youtube/youtube-dl-2.py index 3ebe930..8ee9656 100644 --- a/Youtube/youtube-dl-2.py +++ b/Youtube/youtube-dl-2.py @@ -15,7 +15,7 @@ ydl_opts = { 'postprocessors': [{ 'key': 'FFmpegExtractAudio', 'preferredcodec': 'mp3', - 'preferredquality': '192' + #'preferredquality': '192' #Makes no difference at all. }], 'postprocessor_args': [ '-ar', '16000' @@ -46,14 +46,16 @@ def download(url,options): if __name__=="__main__": #Choose your directory - DIRECTORY='/Users/olivierpartensky/Videos/2019/Youtube/Downloads' + DIRECTORY='/Users/olivierpartensky/Videos/2019/Youtube/JJD' os.chdir(DIRECTORY) print(DIRECTORY) #Choose your musics - #jjd_ocean="https://www.youtube.com/watch?v=XGyrclIGB9E" + jjd_ocean="https://www.youtube.com/watch?v=XGyrclIGB9E" + url=jjd_ocean #playlist='https://www.youtube.com/playlist?list=UUMOgdURr7d8pOVlc-alkfRg' - url="https://www.youtube.com/playlist?list=UUMOgdURr7d8pOVlc-alkfRg" + #url="https://www.youtube.com/playlist?list=UUMOgdURr7d8pOVlc-alkfRg" + #url="https://www.youtube.com/playlist?list=UU9IdQzchnAAwsjQb6DCugPw" #Download them download(url,ydl_opts) diff --git a/Youtube/youtube-dl-3.py b/Youtube/youtube-dl-3.py new file mode 100644 index 0000000..a292b25 --- /dev/null +++ b/Youtube/youtube-dl-3.py @@ -0,0 +1,165 @@ +from __future__ import unicode_literals +import youtube_dl +from pydub import AudioSegment +from pydub.playback import play + +import os +import subprocess + +"""I tried all the codecs on my machine but none is able to convert ogg nor webm into mp3 without loss of audio quality.""" + +#import audiotools + +#os.system("""/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)""""") +#os.system("brew install ffmpeg") +#os.system("pip3.6 install youtube-dl") + + +#Choose the youtube-dl downloading options +#https://github.com/ytdl-org/youtube-dl for more informations +ydl_opts = { + 'format': 'bestaudio/best', + 'postprocessors': [{ + 'key': 'FFmpegExtractAudio', + #'preferredcodec': 'mp3', + 'preferredquality': '192' + }], + 'postprocessor_args': [ + '-ar', '16000' + ], + 'prefer_ffmpeg': True, + 'keepvideo': False, + 'ignoreerrors':True +} + +#Main functions used +def clean(): + """Delete all the webm files and rename the mp3 files with the original youtube names.""" + l=os.listdir() + for i,f in enumerate(l): + if f[-4:]=="webm": + os.remove(f) + if f[-3:]=="mp3": + nf=f[:-16]+".mp3" + os.rename(f,nf) + +def clean2(): + """Convert all the files into mp3.""" + l=os.listdir() + for i,f in enumerate(l): + #nf=f[:-16]+".mp3" + nf=f[:-4]+".mp4" + print(nf) + convert_video(f,nf) + + +def clean3(): + """Convert all the files into mp3.""" + l=os.listdir() + for i,f in enumerate(l): + #nf=f[:-16]+".mp3" + nf=f[:-5]+".mp3" + print(f,nf) + convert_music_absoletely(f,nf) + +def convert_video(video_input, video_output): + #"-b:v","1M" unknown argument + #cmds = ['ffmpeg', '-i', video_input,"-b:a","192", video_output] + cmds = ['ffmpeg', '-i', video_input, video_output] + #avconv -i test.webm test.mp3 + #ffmpeg -i input.webm -acodec libmp3lame -aq 4 output.mp3 + #cmds ['ffmpeg','-i',video_input,'-acodec','libmp3lame','-aq','4',video_output] + #os.system("ffmpeg -i "+video_input+" -acodec libmp3lame -aq 4 "+video_output) + subprocess.Popen(cmds) + +def convert_music_absoletely(input,output): + """Try to convert the input into the output format using all the codes available.""" + sound = AudioSegment.from_file(input) + codecs=getCodecs() + for codec in codecs: + try: + sound.export(output,codec=codec)#, codec="libmp3lame") + print("Codec: "+codec+" worked.") + break + except: + print("Codec: "+codec+" failed.") + +def convert_music(input,output): + sound = AudioSegment.from_ogg(input) + #play(sound) + sound.export(output,format="mp3")#,codec="avui")#, codec="libmp3lame") + +def convert_using_audiotools(input,output): + pass +#def convert_to_audio(video_input,video_output) + + +def clear(): + """Delete all the files in the actual directory.""" + l=os.listdir() + for i,f in enumerate(l): + os.remove(f) + + + +def download(url,options={}): + """Download all the musics using a youtube playlist url.""" + print("clearing") + clear() + print("downloading") + with youtube_dl.YoutubeDL(options) as ydl: + ydl.download([url]) + print("cleaning") + clean3() + print("Download is over.") + +def showFormats(url): + """Show the different formats.""" + cmd=["youtube-dl","-F",url] + output=subprocess.Popen( cmd, stdout=subprocess.PIPE ).communicate()[0] + output=str(output) + l=output.split("\\n") + for e in l: + print(e) + +def showCodecs(): + """Show the different formats.""" + cmd=["ffmpeg","-codecs"] + output=subprocess.Popen( cmd, stdout=subprocess.PIPE ).communicate()[0] + output=str(output) + l=output.split("\\n") + for e in l[10:]: + print(e[8:].split(" ")[0]) + +def getCodecs(): + """Show the different formats.""" + cmd=["ffmpeg","-codecs"] + output=subprocess.Popen( cmd, stdout=subprocess.PIPE ).communicate()[0] + output=str(output) + l=output.split("\\n") + nl=[] + for e in l[10:]: + nl.append(e[8:].split(" ")[0]) + return nl + + + +if __name__=="__main__": + #Choose your directory + DIRECTORY='/Users/olivierpartensky/Videos/2019/Youtube/JJD' + os.chdir(DIRECTORY) + print(DIRECTORY) + + #Choose your musics + jjd_ocean="https://www.youtube.com/watch?v=XGyrclIGB9E" + url=jjd_ocean + #playlist='https://www.youtube.com/playlist?list=UUMOgdURr7d8pOVlc-alkfRg' + #url="https://www.youtube.com/playlist?list=UUMOgdURr7d8pOVlc-alkfRg" + #url="https://www.youtube.com/playlist?list=UU9IdQzchnAAwsjQb6DCugPw" + + #Download them + #showFormats(url) + showCodecs() + download(url,ydl_opts) + + #clean() diff --git a/grass_side.png b/grass_side.png deleted file mode 100644 index 9bb29dd..0000000 Binary files a/grass_side.png and /dev/null differ diff --git a/hackerrank magic square.py b/hackerrank magic square.py new file mode 100644 index 0000000..2b34d2d --- /dev/null +++ b/hackerrank magic square.py @@ -0,0 +1,109 @@ +import random +import itertools + +def getRandomMatrix(): + return [[random.randint(1,3) for i in range(3)] for i in range(3)] + +def isMagicSquare(s): + return sum(s[0][i] for i in range(3))==sum(s[1][i] for i in range(3))==sum(s[2][i] for i in range(3))==sum(s[i][0] for i in range(3))==sum(s[i][1] for i in range(3))==sum(s[i][2] for i in range(3))==sum([s[i][i] for i in range(3)])==sum([s[2-i][i] for i in range(3)]) + + +def isMagicSquare15(s): + return sum(s[0][:])==sum(s[1][:])==sum(s[2][:])==sum(s[:][0])==sum(s[:][1])==sum(s[:][2])==sum([s[i][i] for i in range(3)])==sum([s[2-i][i] for i in range(3)])==15 + +def getSquareFromList(l): + return [[l[3*i],l[3*i+1],l[3*i+2]] for i in range(3)] + +def getSquaresFromLists(ls): + return [getSquareFromList(l) for l in ls] + + +def getListFromSquare(m): + return m[0][:]+m[1][:]+m[2][:] + + +def getListsFromSquares(ms): + return [getListFromSquare(m) for m in ms] + +def getRandomSudokuList(): + a=list(range(1,10)) + l=[] + for i in range(9): + r=random.randint(0,8-i) + l.append(a[r]) + del a[r] + return l + +def getRandomSudokuSquare(): + l=getRandomSudokuList() + return getSquareFromList(l) + + +def filterMagicSquares(ms): + return [m for m in ms if isMagicSquare(m)] + +def filterMagicSquares15(ms): + return [m for m in ms if isMagicSquare15(m)] + +def getMinimumCost(m,qs): + c=8*9 + for q in qs: + nc=compare(q,m) + if nc