diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 0000000..500bc70 --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,3 @@ +{ + "python.linting.pylintEnabled": true +} \ No newline at end of file diff --git a/13.py b/13.py new file mode 100644 index 0000000..050cabc --- /dev/null +++ b/13.py @@ -0,0 +1,36 @@ +class Humain: + def __init__(self,nom,age): + self.nom=nom + self._age=age + # property(getter , setter , deleter, helper) + + + + def _getage(self): + return self._age + + def _setage(self,nage): + if nage<0 :self._age=0 + else: self._age=nage + age=property(_getage, _setage) + + +#programme principal +h1=Humain("Jojo",21) + +print(h1.age) +h1.age=11 +print(h1.age) + +h1.nom="ALI" +nage=int(input("nouveau age pour Ali: ")) +h1._age=nage + + +print("______________") +print(h1._age) +print("______________") +h1._setage(nage) +print(h1._age) + + diff --git a/900.py b/900.py new file mode 100644 index 0000000..b8473fd --- /dev/null +++ b/900.py @@ -0,0 +1,12 @@ +a=input("entrer votre age :") +b=5 +try : + age=int(b/a) +#except: ZeroDivisionError + print("age doit etre # 0") +except: + print("erreur dans la saisie de l'age") +else: + print("votre age est ",age) +finally: + print("fin du programme") diff --git a/README.md b/README.md deleted file mode 100644 index 26039c7..0000000 --- a/README.md +++ /dev/null @@ -1,2 +0,0 @@ -# codePython -mes exercices python pour mes eleves diff --git a/UI reservation.py b/UI reservation.py new file mode 100644 index 0000000..65f952c --- /dev/null +++ b/UI reservation.py @@ -0,0 +1,43 @@ +from tkinter import * +from tkinter import ttk +from tkinter import messagebox + +root=Tk() +root.title(' Ticket Reservation') +style=ttk.Style() +style.theme_use('classic') +#full name +ttk.Label(root, text= "Full name :").grid(row=0,column=0,padx=10,pady=10) +EntryFullName=ttk.Entry(root,width=30, font=('Arial',16)).grid(row=0,column=1, columnspan=2,pady=10) +#Gender +ttk.Label(root, text=" Gender :").grid(row=1,column=0) +SpanGender=StringVar() +ttk.Radiobutton(root,text="Male",variable=SpanGender, value="Male").grid(row=1,column=1) +ttk.Radiobutton(root,text="Female",variable=SpanGender, value="Female").grid(row=1,column=2) +#comment +ttk.Label(root, text= "Comment :").grid(row=2,column=0,padx=10,pady=10) +txtComment=Text(root,width=30, heigh=10, font=('Arial',16)) +txtComment.grid(row=2, column=1,columnspan=2) +#button list and submit +buSubmit=ttk.Button(root,text="Submit") +buSubmit.grid(row=3,column=3) +buList=ttk.Button(root,text="List") +buList.grid(row=3,column=2) + +#action for submit and list +def BuSubmit(): + print("FullName :{}".format(EntryFullName.getText(0,'end'))) + print("Gender :{}".format(SpanGender.get())) + print("Comments :{}".format(txtComment.get(1.0,'end'))) + EntryFullName.Delete(0,'end') + txtComment.Delete(1.0,'end') + +buSubmit.config(command=BuSubmit) + + + + + + + +root.mainloop() diff --git a/__pycache__/first.cpython-37.pyc b/__pycache__/first.cpython-37.pyc new file mode 100644 index 0000000..087767f Binary files /dev/null and b/__pycache__/first.cpython-37.pyc differ diff --git a/__pycache__/re.cpython-37.pyc b/__pycache__/re.cpython-37.pyc new file mode 100644 index 0000000..31215d7 Binary files /dev/null and b/__pycache__/re.cpython-37.pyc differ diff --git a/animal.py b/animal.py new file mode 100644 index 0000000..4a43611 --- /dev/null +++ b/animal.py @@ -0,0 +1,13 @@ +class Animal: + def animal_sound(self,animal,sound): + print( f"le {animal} fait {sound}.") + def sound(self): + raise NotImplementedError("la classe n'aps definit le son de l'animal") + + +class Chien(Animal): + def sound(self): + return {"Haw Haw"} + +c=Chien() +print(c.sound()) diff --git a/calc.py b/calc.py new file mode 100644 index 0000000..bc816aa --- /dev/null +++ b/calc.py @@ -0,0 +1,43 @@ +# Program make a simple calculator that can add, subtract, multiply and divide using functions + +# This function adds two numbers +def add(x, y): + return x + y + +# This function subtracts two numbers +def subtract(x, y): + return x - y + +# This function multiplies two numbers +def multiply(x, y): + return x * y + +# This function divides two numbers +def divide(x, y): + return x / y + +print("Select operation.") +print("1.Add") +print("2.Subtract") +print("3.Multiply") +print("4.Divide") + +# Take input from the user +choice = input("Enter choice(1/2/3/4):") + +num1 = int(input("Enter first number: ")) +num2 = int(input("Enter second number: ")) + +if choice == '1': + print(num1,"+",num2,"=", add(num1,num2)) + +elif choice == '2': + print(num1,"-",num2,"=", subtract(num1,num2)) + +elif choice == '3': + print(num1,"*",num2,"=", multiply(num1,num2)) + +elif choice == '4': + print(num1,"/",num2,"=", divide(num1,num2)) +else: + print("Invalid input") diff --git a/carre.py b/carre.py new file mode 100644 index 0000000..bebbfef --- /dev/null +++ b/carre.py @@ -0,0 +1,7 @@ +from turtle import * +for j in range(10): + + for i in range(6): + forward(160+j) + right(144+j) + diff --git a/classpoint.py b/classpoint.py new file mode 100644 index 0000000..3bda418 --- /dev/null +++ b/classpoint.py @@ -0,0 +1,60 @@ +#!/usr/bin/python # This is server.py file + +import socket # Import socket module + +s = socket.socket() # Create a socket object +host = socket.gethostname() # Get local machine name +port = 12345 # Reserve a port for your service. +s.bind((host, port)) # Bind to the port + +s.listen(5) # Now wait for client connection. +while True: + c, addr = s.accept() # Establish connection with client. + print 'Got connection from', addr + c.send('Thank you for connecting') + c.close() # Close the connection + + + +#!/usr/bin/python # This is client.py file + +import socket # Import socket module + +s = socket.socket() # Create a socket object +host = socket.gethostname() # Get local machine name +port = 12345 # Reserve a port for your service. + +s.connect((host, port)) +print s.recv(1024) +s.close() + +class Point: + def __init__( self, x=0, y=0): + self.x = x + self.y = y + def __del__(self): + class_name = self.__class__.__name__ + print ("destroyed") + +pt1 = Point() +pt2 = Point() +pt3 = Point() +print (id(pt1), id(pt2), id(pt3)) # prints the ids of the obejcts + + +#!/usr/bin/python +import time; # This is required to include time module. +import calendar +ticks = time.time() +print ("Number of ticks since 12:00am, January 1, 1970:", ticks) +cal1 = calendar.month(1977, 9) +cal2 = calendar.month(1986, 2) +cal3 = calendar.month(2017, 5) + +print(cal1 , cal2 , cal3) + +import tkinter +top = tkinter.Tk() +# Code to add widgets will go here... +top.mainloop() + diff --git a/contact.py b/contact.py new file mode 100644 index 0000000..7244883 --- /dev/null +++ b/contact.py @@ -0,0 +1,34 @@ +class Contact: + def __init__(self, nom,age): + self.nom=nom + self._age=age + def get_age(self): + return self._age + def set_age(self,new_age): + if new_age>0 : + self._age=new_age + else: + self._age=0 + @property + def age(self): + return self._age + @age.setter + def age(self,newage): + if newage>0: + self._age=newage + else: + print("age incorrect") + self._age=0 + +c0=Contact("Omi",62) +c1=Contact("Mourad",42) +c2=Contact("Mehdi",2) +#print(c1.get_age()) +#print(c2.get_age()) +c1.set_age(34) +#print(c1.get_age()) +c1.set_age(-3) +#print(c1.get_age()) +print(c0.age) +c2.age=-99 +print(c2.age) \ No newline at end of file diff --git a/contmgr.py b/contmgr.py new file mode 100644 index 0000000..8699b57 --- /dev/null +++ b/contmgr.py @@ -0,0 +1,11 @@ +import contextlib +@contextlib.contextmanager +def context_manager(num): + print('Enter') + yield num + 1 + print('Exit') +with context_manager(2) as cm: +# the following instructions are run when the 'yield' point of the context +# manager is reached. +# 'cm' will have the value that was yielded + print('Right in the middle with cm = {}'.format(cm)) diff --git a/datachart.py b/datachart.py new file mode 100644 index 0000000..ef1ff0b --- /dev/null +++ b/datachart.py @@ -0,0 +1,23 @@ +import numpy as np +import matplotlib.pyplot as plt + + +N = 5 +menMeans = (20, 35, 30, 35, 27) +womenMeans = (25, 32, 34, 20, 25) +menStd = (2, 3, 4, 1, 2) +womenStd = (3, 5, 2, 3, 3) +ind = np.arange(N) # the x locations for the groups +width = 0.35 # the width of the bars: can also be len(x) sequence + +p1 = plt.bar(ind, menMeans, width, yerr=menStd) +p2 = plt.bar(ind, womenMeans, width, + bottom=menMeans, yerr=womenStd) + +plt.ylabel('Scores') +plt.title('Scores by group and gender') +plt.xticks(ind, ('G1', 'G2', 'G3', 'G4', 'G5')) +plt.yticks(np.arange(0, 81, 10)) +plt.legend((p1[0], p2[0]), ('Men', 'Women')) + +plt.show() diff --git a/datframe.py b/datframe.py new file mode 100644 index 0000000..2083edc --- /dev/null +++ b/datframe.py @@ -0,0 +1,12 @@ +import numpy as np +import pandas as pd +from numpy.random import randn + +np.random.seed(0) +df = pd.DataFrame(randn(4,4),['A','B','C','X'],['D','E','F','Y']) +print(df) + + +df2= pd.DataFrame(randn(6,8),['Lundi','Mardi','Mercredi','Jeud','Vendredi','Samedi',], + ['8-9','9-10','10-11','11-12','14-15','15-16','16-17','17-18']) + diff --git a/drag.py b/drag.py new file mode 100644 index 0000000..7b2ccd7 --- /dev/null +++ b/drag.py @@ -0,0 +1,21 @@ +import turtle +from turtle import Turtle, Screen +screen=Screen() +t=Turtle('turtle') +t.speed(-1) + + +def dragging(x,y): + t.ondrag(None) + t.setheading(t.towards(x,y)) + t.goto(x,y) + t.ondrag(dragging) + +def clickright(): + t.clear() +def main(): + turtle.listen() + t.ondrag(dragging) + turtle.onscreenclick(clickright(),3) + screen.mainloop() +main() diff --git a/drapeau.py b/drapeau.py new file mode 100644 index 0000000..d2a822c --- /dev/null +++ b/drapeau.py @@ -0,0 +1,46 @@ +import turtle +x=800 +y=800 +turtle.setup(x,y) +turtle.bgcolor('red') +#cercle blanc +turtle.penup() +turtle.goto(0,-90) +turtle.pencolor('white') +turtle.pendown() +turtle.begin_fill() +turtle.circle(90,None,None) +turtle.color('white') +turtle.end_fill() + +#cercle rouge +turtle.penup() +turtle.goto(0,-60) +turtle.pen() +turtle.pencolor('red') +turtle.pendown() +turtle.begin_fill() +turtle.circle(60,None,None) +turtle.color('red') +turtle.end_fill() + + +#etoile +turtle.penup() +turtle.goto(38,15) +turtle.pen() +turtle.pencolor('white') +turtle.pendown() +turtle.begin_fill() +turtle.left(18) + +for i in range(5): + turtle.forward(25) + turtle.right(144) + +turtle.forward(25) +turtle.left(72) +turtle.color('red') +turtle.end_fill() + + diff --git a/ennum.py b/ennum.py new file mode 100644 index 0000000..687dc09 --- /dev/null +++ b/ennum.py @@ -0,0 +1,7 @@ +friends = ['john', 'pat', 'gary', 'michael'] +for i, name in enumerate(friends): + print ("iteration {iteration} is {name}".format(iteration=i, name=name)) +parents, babies = (1, 1) +while babies < 100: + print ('This generation has {0} babies'.format(babies), + parents, babies = (babies, parents + babies)) diff --git a/fff.py b/fff.py new file mode 100644 index 0000000..0586f19 --- /dev/null +++ b/fff.py @@ -0,0 +1,8 @@ +n=int(input("donner l''ordre de la suite de fibo:")) +if n==0 : f=0 +elif n==1 : f=1 +else: + f=1 + for (i,w) in(0,0) :(i++,w+f) + w=f +print(w) diff --git a/fib.py b/fib.py new file mode 100644 index 0000000..beae15c --- /dev/null +++ b/fib.py @@ -0,0 +1,17 @@ +def gen_fib(): + count = int(input("How many fibonacci numbers would you like to generate? ")) + i = 1 + if count == 0: + fib = [] + elif count == 1: + fib = [1] + elif count == 2: + fib = [1,1] + elif count > 2: + fib = [1,1] + while i < (count - 1): + fib.append(fib[i] + fib[i-1]) + i += 1 + + return fib +print (gen_fib()) diff --git a/fibb.py b/fibb.py new file mode 100644 index 0000000..fb1938e --- /dev/null +++ b/fibb.py @@ -0,0 +1,6 @@ +def fibb(n : int)-> int : + a,b=0,1 + for _ in range(n): + yield a + b,a=a+b,b + return(a) diff --git a/first.py b/first.py new file mode 100644 index 0000000..f048c21 --- /dev/null +++ b/first.py @@ -0,0 +1,7 @@ +def gm(): + print("Hi Mourad have a nice time !") + print("----------------------------") + +def ge(): + print("Hi Mehdi good evening enjoy") + print("+++++++++++++++++++++++++++") \ No newline at end of file diff --git a/foo.txt b/foo.txt new file mode 100644 index 0000000..e45ca9e --- /dev/null +++ b/foo.txt @@ -0,0 +1 @@ +go python \ No newline at end of file diff --git a/frames.py b/frames.py new file mode 100644 index 0000000..ceb8bf4 --- /dev/null +++ b/frames.py @@ -0,0 +1,35 @@ +from tkinter import * +from tkinter import ttk +root=Tk() + + +f0=ttk.Frame(root) +f0.pack() +f0.config(width=200,height=200,relief=RIDGE) + +f1=ttk.Frame(root) +f1.pack() +f1.config(width=200,height=200,relief=RIDGE) + +f2=ttk.Frame(root) +f2.pack() +f2.config(width=200,height=200,relief=RIDGE) + +text=ttk.Entry(f0,text='').pack() + +b1=ttk.Button(f1,text='1').grid(row=0,column=0) +b2=ttk.Button(f1,text='2').grid(row=0,column=1) +b3=ttk.Button(f1,text='3').grid(row=0,column=2) +b4=ttk.Button(f1,text='4').grid(row=1,column=0) +b5=ttk.Button(f1,text='5').grid(row=1,column=1) +b6=ttk.Button(f1,text='6').grid(row=1,column=2) +b7=ttk.Button(f1,text='7').grid(row=2,column=0) +b8=ttk.Button(f1,text='8').grid(row=2,column=1) +b9=ttk.Button(f1,text='9').grid(row=2,column=2) +b0=ttk.Button(f1,text='0').grid(row=3,column=0) +b1=ttk.Button(f1,text='.').grid(row=3,column=1) +b2=ttk.Button(f1,text='=').grid(row=3,column=2) + +b3=ttk.Button(f2,text='B3').pack() +b4=ttk.Button(f2,text='B4').pack() +b5=ttk.Button(f2,text='B5').pack() diff --git a/graph.py b/graph.py new file mode 100644 index 0000000..f23fb2d --- /dev/null +++ b/graph.py @@ -0,0 +1,8 @@ +import math +import numpy as np +import matplotlib.pyplot as plt +x=np.linspace(-2*np.pi,2*np.pi) +y=np.sin(x) +print(y) +plt.plot(x,y) +plt.show() \ No newline at end of file diff --git a/graphy.py b/graphy.py new file mode 100644 index 0000000..b3ae0f5 --- /dev/null +++ b/graphy.py @@ -0,0 +1,10 @@ +import os +import numpy as np +import matplotlib.pyplot as plt +x=np.linspace(-4*np.pi, 4*np.pi) +y=np.cos(x) +plt.plot(x,y) +plt.legend() +plt.xlabel('X') +plt.ylabel('Y=Cos(x)') +plt.show() diff --git a/heritage.py b/heritage.py new file mode 100644 index 0000000..4d67702 --- /dev/null +++ b/heritage.py @@ -0,0 +1,10 @@ +#classe mere +class vehicule: + def __init__(,self,nom,qessence): + self.nom=nom + self.essence=qessence + def affiche(self): + return self.nom +#classe fille +class voiture(vehicule): + diff --git a/hh.py b/hh.py new file mode 100644 index 0000000..60647a1 --- /dev/null +++ b/hh.py @@ -0,0 +1,27 @@ +import turtle + +def draw_multicolor_square(t, sz): + + """Make turtle t draw a multi-color square of sz.""" + + for i in ["red", "purple", "hotpink", "blue"]: + + t.color(i) + t.forward(sz) + t.left(90) + +wn = turtle.Screen() # Set up the window and its attributes +wn.bgcolor("lightgreen") +tess = turtle.Turtle() # Create tess and set some attributes +tess.pensize(3) + +size = 15 # Size of the smallest square +for i in range(20): + + draw_multicolor_square(tess, size) + size += 8 # Increase the size for next time + tess.forward(20) # Move tess along a little + tess.right(36) # and give her some extra turn + + +wn.mainloop() diff --git a/hhhhh.py b/hhhhh.py new file mode 100644 index 0000000..57cdfd6 --- /dev/null +++ b/hhhhh.py @@ -0,0 +1,15 @@ +import turtle +x=800 +y=800 +turtle.setup(x,y) +turtle.bgcolor('red') +#cercle blanc +turtle.penup() +turtle.goto(0,-10) +turtle.pencolor('white') +turtle.pendown() +turtle.begin_fill() +turtle.goto(0,0) +turtle.color('white') +turtle.end_fill() + diff --git a/his.py b/his.py new file mode 100644 index 0000000..2fd0dfe --- /dev/null +++ b/his.py @@ -0,0 +1,8 @@ +import numpy as np +import matplotlib.pyplot as plt +# Build a vector of 10000 normal deviates with variance 0.5^2 and mean 2 +mu, sigma = 2, 0.5 +v = np.random.normal(mu,sigma,10000) +# Plot a normalized histogram with 50 bins +plt.hist(v, bins=50, density=1) # matplotlib version (plot) +plt.show() diff --git a/iii.py b/iii.py new file mode 100644 index 0000000..2a79bc7 --- /dev/null +++ b/iii.py @@ -0,0 +1,12 @@ +import math +a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] + +num = int(raw_input("Choose a number: ")) + +a1 = [] + +for i in a: + if i < num: + a1.append(i) + +print (a1) diff --git a/imopet.py b/imopet.py new file mode 100644 index 0000000..d468977 --- /dev/null +++ b/imopet.py @@ -0,0 +1,22 @@ +#import numpy as np +#import re +class User: + def __init__(self, name, age,email): + self.name=name + self.age=age + self.email=email + self._secret="Mehdi aime le chocolat" + self.__friend="Ziko Rahma Anas Ghazal" + def identity(self): + return f"Name: {self.name} Age:{self.age}" + + +fuser=User("Mourad",42,"elbeji@gmail.com") +suser=User("Mehdi",2,"mehdibeji@gmail.com") + +print(fuser.identity()) +print(suser.identity()) + + + + diff --git a/integral.py b/integral.py new file mode 100644 index 0000000..11c118f --- /dev/null +++ b/integral.py @@ -0,0 +1,35 @@ +import numpy as np +import matplotlib.pyplot as plt +from matplotlib.patches import Polygon +def func(x): + return (x - 3) * (x - 5) * (x - 7) + 85 +a, b = 2, 9 # integral limits +x = np.linspace(0, 10) +y = func(x) + +fig, ax = plt.subplots() +plt.plot(x, y, 'r', linewidth=2) +plt.ylim(ymin=0) + +# Make the shaded region +ix = np.linspace(a, b) +iy = func(ix) +verts = [(a, 0), *zip(ix, iy), (b, 0)] +poly = Polygon(verts, facecolor='0.9', edgecolor='0.5') +ax.add_patch(poly) + +plt.text(0.5 * (a + b), 30, r"$\int_a^b f(x)\mathrm{d}x$", + horizontalalignment='center', fontsize=20) + +plt.figtext(0.9, 0.05, '$x$') +plt.figtext(0.1, 0.9, '$y$') + +ax.spines['right'].set_visible(False) +ax.spines['top'].set_visible(False) +ax.xaxis.set_ticks_position('bottom') + +ax.set_xticks((a, b)) +ax.set_xticklabels(('$a$', '$b$')) +ax.set_yticks([]) + +plt.show() \ No newline at end of file diff --git a/les liste.py b/les liste.py new file mode 100644 index 0000000..5ff87a7 --- /dev/null +++ b/les liste.py @@ -0,0 +1,11 @@ + +from tkinter import * +f1=Tk() +f1.title("Hello ") + +f1.resizable(width=False,height=False) + + + +mainloop() + diff --git a/listealea.py b/listealea.py new file mode 100644 index 0000000..177b9de --- /dev/null +++ b/listealea.py @@ -0,0 +1,3 @@ +import random as alea +l=[1,2,3,4,5,6,7,8,9] +print(alea.choice(l)) diff --git a/loops.py b/loops.py new file mode 100644 index 0000000..b4538b4 --- /dev/null +++ b/loops.py @@ -0,0 +1,17 @@ +l=['Naima','Moncef','ahmed','slim','mourad','Houda','Mehdi'] +s='mourad' + +for i in range(0,12): + for j in range(i): + print('%-4d ' %(i+j-1),end=' ') + print() + +start=2 +end=100 +for i in range(start,end+1): + if i>1 : + for j in range(2,i): + if (i %j) ==0 : + break + else : + print(i, ' -- ',i+2,' -- ' ,i+6,' -- ',i+8) diff --git a/mandelbort.py b/mandelbort.py new file mode 100644 index 0000000..8531b8a --- /dev/null +++ b/mandelbort.py @@ -0,0 +1,19 @@ +import numpy as np +import matplotlib.pyplot as plt +def mandelbrot( h,w, maxit=20 ): + """Returns an image of the Mandelbrot fractal of size (h,w).""" + y,x = np.ogrid[ -1.4:1.4:h*1j, -2:0.8:w*1j ] + c = x+y*1j + z = c + divtime = maxit + np.zeros(z.shape, dtype=int) + + for i in range(maxit): + z = z**2 + c + diverge = z*np.conj(z) > 2**2 # who is diverging + div_now = diverge & (divtime==maxit) # who is diverging now + divtime[div_now] = i # note when + z[diverge] = 2 # avoid diverging too much + + return divtime +plt.imshow(mandelbrot(400,400)) +plt.show() diff --git a/master.py b/master.py new file mode 100644 index 0000000..b931898 --- /dev/null +++ b/master.py @@ -0,0 +1,3 @@ +from first import gm , ge +gm() +ge() diff --git a/methodestatique.py b/methodestatique.py new file mode 100644 index 0000000..fb84576 --- /dev/null +++ b/methodestatique.py @@ -0,0 +1,26 @@ +#methode de classe +class Humain: + lieu="Terre" + def __init__(self,nom,age):#constructeur + self.nom=nom + self.age=age + def parler(self,message):#methode d'instance + print("{} a dit :{}".format(self.nom, message)) + def changelieu(cls,lieu):# methode de classe + Humain.lieu=lieu + changelieu = classmethod(changelieu) + def defin(): + print(" blaaaaaaaaaaaaa ") + defin = staticmethod(defin) + +#programme principal +h1=Humain("bob",24) +h1.parler(" bonjour ") +#methode d'instancde ne fonctionne que sur des +# objets de la classe +Humain.changelieu("Mars") +#methode de classe elle travaille sur la classe +# elle meme +print("planete actuelle :{}".format(Humain.lieu)) + +Humain.defin() diff --git a/mlearning1.py b/mlearning1.py new file mode 100644 index 0000000..89fdab2 --- /dev/null +++ b/mlearning1.py @@ -0,0 +1,21 @@ +import numpy as np +import matplotlib.pyplot as plt +from sklearn.linear_model import LinearRegression + +x = np.array([[1980],[1983],[1984],[1990],[1994]]) +y = np.array([[1500],[1580],[1850],[3520],[4000]]) +plt.scatter(x ,y) +plt.title("Used Cars Prices", fontsize=24) +plt.xlabel("X axes", fontsize=14) +plt.ylabel("Y axes", fontsize=14) +plt.grid(True) + +model = LinearRegression() +model.fit(x,y) +h=model.predict([1987]) +print(h) + + + + +plt.show() diff --git a/moyenne.py b/moyenne.py new file mode 100644 index 0000000..8a7bc95 --- /dev/null +++ b/moyenne.py @@ -0,0 +1,11 @@ +n=int(input('Nombre de notes a saisir :')) +s=0 +for i in range(n): + s+=float(input('saisir la note ')) + +moy=s/n +print('La moyenne est ',moy) +if (moy>10): + print('ADMIS') +else: + print('Refuse') \ No newline at end of file diff --git a/num.py b/num.py new file mode 100644 index 0000000..5668752 --- /dev/null +++ b/num.py @@ -0,0 +1,2 @@ +print(10+10) +print(176**1450) \ No newline at end of file diff --git a/numpytest.py b/numpytest.py new file mode 100644 index 0000000..fde8a4e --- /dev/null +++ b/numpytest.py @@ -0,0 +1,18 @@ +import numpy as np +import sys +import time +size =100000 +a = np.array([(1,2,3),(4,5,6)]) +L1= range(size) +L2=range(size) +a1 = np.arange(size) +a2 = np.arange(size) +start=time.time() +print("time 1",start) +result= [(x,y) for x,y in zip(L1,L2)] +print("result 1",result) +start=time.time() +result =a1+a2 +print("time 2",start) +print("result 2 ",result) +print((time.time()-start)*1000) diff --git a/otp.py b/otp.py new file mode 100644 index 0000000..75adadd --- /dev/null +++ b/otp.py @@ -0,0 +1,15 @@ +import math , random +digits='0123456789abcdefghijklmnopqrstuvwxyz!@#$%&*ABCDEFGHIJKLOPMNVXZQWERTYUS()' +otp='' +l=[] +f=open('a:\pwd.txt','a') +for k in range(1,11): + for i in range(1,9): + otp+=digits[math.floor(random.random()*len(digits))] + print(otp) + otp+='\n' + f.write(otp) + otp='' +f.close() + + diff --git a/pand1.py b/pand1.py new file mode 100644 index 0000000..ea0f13a --- /dev/null +++ b/pand1.py @@ -0,0 +1,12 @@ +import pandas as pd +import matplotlib.pyplot as plt +from matplotlib import style +style.use("fivethirtyeight") + +xyz_web={'State':['Tunis','Beja','Gafsa','Sousse'],'Pop':[2500,350,650,700],'Succes':[54,35,23,56]} + +df=pd.DataFrame(xyz_web) +df.set_index('State',inplace=True) + +df.plot() +plt.show() diff --git a/pass.py b/pass.py new file mode 100644 index 0000000..dd0acb1 --- /dev/null +++ b/pass.py @@ -0,0 +1,9 @@ +import re +import os +import string +import random + +def pw_gen(size = 8, chars=string.ascii_letters + string.digits + string.punctuation): + return ''.join(random.choice(chars) for _ in range(size)) + +print(pw_gen(int(input('How many characters in your password?')))) diff --git a/password gen.py b/password gen.py new file mode 100644 index 0000000..c80faad --- /dev/null +++ b/password gen.py @@ -0,0 +1,11 @@ +import String +import re +import urllib + +from random import randint + +characters = string.ascii_letters + string.punctuation + string.digits + +password = "".join(choice(characters) for x in range(randint(8, 16))) + +print (password) diff --git a/ploy.py b/ploy.py new file mode 100644 index 0000000..fb420a5 --- /dev/null +++ b/ploy.py @@ -0,0 +1,14 @@ +# Python program to draw hexagon +# using Turtle Programming +import turtle +polygon = turtle.Turtle() + +num_sides = 20 +side_length = 70 +angle = 360.0 / num_sides + +for i in range(num_sides): + polygon.forward(side_length) + polygon.left(angle) + +turtle.done() diff --git a/ppandas.py b/ppandas.py new file mode 100644 index 0000000..3d5355c --- /dev/null +++ b/ppandas.py @@ -0,0 +1,2 @@ +import pandas as pandas +df = pd.DataFrame() diff --git a/ppppp.py b/ppppp.py new file mode 100644 index 0000000..ae33f2c --- /dev/null +++ b/ppppp.py @@ -0,0 +1,27 @@ +import numpy as np +import matplotlib.pyplot as plt + +# Fixing random state for reproducibility +np.random.seed(19680801) + +dt = 0.01 +t = np.arange(0, 30, dt) +nse1 = np.random.randn(len(t)) # white noise 1 +nse2 = np.random.randn(len(t)) # white noise 2 + +# Two signals with a coherent part at 10Hz and a random part +s1 = np.sin(2 * np.pi * 10 * t) + nse1 +s2 = np.sin(2 * np.pi * 10 * t) + nse2 + +fig, axs = plt.subplots(2, 1) +axs[0].plot(t, s1, t, s2) +axs[0].set_xlim(0, 2) +axs[0].set_xlabel('time') +axs[0].set_ylabel('s1 and s2') +axs[0].grid(True) + +cxy, f = axs[1].cohere(s1, s2, 256, 1. / dt) +axs[1].set_ylabel('coherence') + +fig.tight_layout() +plt.show() diff --git a/progClasse.py b/progClasse.py new file mode 100644 index 0000000..69232c8 --- /dev/null +++ b/progClasse.py @@ -0,0 +1,33 @@ + + +class Humain: + humain_cree=0#attribut de classe + def __init__(self,cprenom,cage):#constructeur + self.prenom=cprenom + self.age=cage + Humain.humain_cree +=1 + + def parler(self , message):#methode de classe + print("{} a dit :{}".format(self.prenom , message)) + + + + + + + + +print("lancement de programme") +h1 = Humain("jojo",1)#instanciation de la classe +h1.age=17#acces et modification d un attribut + +#print("prenom de h1 :{}".format(h1.prenom)) +h2 = Humain("dodo",2) +h3=Humain("mmm",21) +print("prenom de h1 :{}".format(h1.prenom)) +print("age de h1 :{}".format(h1.age)) +print("prenom de h2 :{}".format(h2.prenom)) +print("age de h1 :{}".format(h2.age)) + +print("Nombre des humain est :{}".format(Humain.humain_cree)) +h1.parler("Bonjour ")#appel a la methode de classe diff --git a/pygame1.py b/pygame1.py new file mode 100644 index 0000000..c239515 --- /dev/null +++ b/pygame1.py @@ -0,0 +1,32 @@ +import pygame +pygame.init() + +win=pygame.display.set_mode((500,500)) +pygame.display.set_caption('First game') + +x=60 +y=60 +width=40 +height=60 +vel =6 + +run =True +while run: + pygame.time.delay(1000) + for event in pygame.event.get() : + if event.type==pygame.QUIT : + run=False + keys=pygame.key.get_pressed() + if keys[pygame.K_LEFT ]: + x-=vel + if keys[pygame.K_RIGHT ]: + x+=vel + if keys[pygame.K_UP]: + y+=vel + if keys[pygame.K_DOWN ]: + y-=vel + + pygame.draw.rect(win,(255,0,0),(x,y,width,height)) + pygame.display.update() + +pygame.quit() diff --git a/pypass.py b/pypass.py new file mode 100644 index 0000000..92a6cc9 --- /dev/null +++ b/pypass.py @@ -0,0 +1,102 @@ +# Python program to generate random +# password using Tkinter module +import random +import pyperclip +from tkinter import * +from tkinter.ttk import * + +# Function for calculation of password +def low(): + entry.delete(0, END) + + # Get the length of passowrd + length = var1.get() + + lower = "abcdefghijklmnopqrstuvwxyz" + upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" + digits = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 !@#$%^&*()" + password = "" + + # if strength selected is low + if var.get() == 1: + for i in range(0, length): + password = password + random.choice(lower) + return password + + # if strength selected is medium + elif var.get() == 0: + for i in range(0, length): + password = password + random.choice(upper) + return password + + # if strength selected is strong + elif var.get() == 3: + for i in range(0, length): + password = password + random.choice(digits) + return password + else: + print("Please choose an option") + + +# Function for generation of password +def generate(): + password1 = low() + entry.insert(10, password1) + + +# Function for copying password to clipboard +def copy1(): + random_password = entry.get() + pyperclip.copy(random_password) + + +# Main Function + +# create GUI window +root = Tk() +var = IntVar() +var1 = IntVar() + +# Title of your GUI window +root.title("Random Password Generator") + +# create label and entry to show +# password generated +Random_password = Label(root, text="Password") +Random_password.grid(row=0) +entry = Entry(root) +entry.grid(row=0, column=1) + +# create label for length of password +c_label = Label(root, text="Length") +c_label.grid(row=1) + +# create Buttons Copy which will copy +# password to clipboard and Generate +# which will generate the password +copy_button = Button(root, text="Copy", command=copy1) +copy_button.grid(row=0, column=2) +generate_button = Button(root, text="Generate", command=generate) +generate_button.grid(row=0, column=3) + +# Radio Buttons for deciding the +# strength of password +# Default strength is Medium +radio_low = Radiobutton(root, text="Low", variable=var, value=1) +radio_low.grid(row=1, column=2, sticky='E') +radio_middle = Radiobutton(root, text="Medium", variable=var, value=0) +radio_middle.grid(row=1, column=3, sticky='E') +radio_strong = Radiobutton(root, text="Strong", variable=var, value=3) +radio_strong.grid(row=1, column=4, sticky='E') +combo = Combobox(root, textvariable=var1) +#$)URrQyZ +# Combo Box for length of your password +combo['values'] = (8, 9, 10, 11, 12, 13, 14, 15, 16, + 17, 18, 19, 20, 21, 22, 23, 24, 25, + 26, 27, 28, 29, 30, 31, 32, "Length") +combo.current(0) +combo.bind('<>') +combo.grid(column=1, row=1) + +# start the GUI +root.mainloop() diff --git a/pypy.py b/pypy.py new file mode 100644 index 0000000..f11640c --- /dev/null +++ b/pypy.py @@ -0,0 +1,9 @@ +import numpy as np +import pandas as pd +import matplotlib.pyplot as plt +x=np.arange(-3,3,0.5) +y=x**2 +z=np.sin(x) +w=np.exp(-x**2) +plt.plot(x,y,x,z,x,w,x,x) +plt.show() \ No newline at end of file diff --git a/re.py b/re.py new file mode 100644 index 0000000..1d9d826 --- /dev/null +++ b/re.py @@ -0,0 +1,11 @@ +import os +import urllib +import re + +s=urllib.urlopen('htt[s://www.python.org') +html=s.read() +s.close() + +print('open tags') +re.findall('<[^/>][^>]*>',html)[0:2] +print('close tags') diff --git a/readccsv.py b/readccsv.py new file mode 100644 index 0000000..f8b7d9b --- /dev/null +++ b/readccsv.py @@ -0,0 +1,14 @@ +import pandas as pd +country = pd.read_csv('A:\\Lemonade.csv',index_col=0) +country.to_html('A:\\edu.html') +country.to_excel('A:\\edu1.xlsx') +df=pd.DataFrame(country) + + + + + + + + + diff --git a/reservation system.py b/reservation system.py new file mode 100644 index 0000000..e69de29 diff --git a/scatter.py b/scatter.py new file mode 100644 index 0000000..4060bb9 --- /dev/null +++ b/scatter.py @@ -0,0 +1,13 @@ +import matplotlib.pyplot as plt +from numpy.random import rand + +fig , ax = plt.subplots() + +for color in ['red','green','blue']: + n=750 + x,y=rand(2,0) + scale = 200.0*rand(n) + ax.scatter(x,y,c=color,s=scale,label=color,alpha=0.3,edgecolor='none') +ax.legend() +ax.grid(True) +plt.show() diff --git a/sckitlearn.py b/sckitlearn.py new file mode 100644 index 0000000..551e3b3 --- /dev/null +++ b/sckitlearn.py @@ -0,0 +1,45 @@ +print(__doc__) + +# Author: Nelle Varoquaux +# Alexandre Gramfort +# License: BSD + +import numpy as np +import matplotlib.pyplot as plt +from matplotlib.collections import LineCollection + +from sklearn.linear_model import LinearRegression +from sklearn.isotonic import IsotonicRegression +from sklearn.utils import check_random_state + +n = 100 +x = np.arange(n) +rs = check_random_state(0) +y = rs.randint(-50, 50, size=(n,)) + 50. * np.log1p(np.arange(n)) + +# ############################################################################# +# Fit IsotonicRegression and LinearRegression models + +ir = IsotonicRegression() + +y_ = ir.fit_transform(x, y) + +lr = LinearRegression() +lr.fit(x[:, np.newaxis], y) # x needs to be 2d for LinearRegression + +# ############################################################################# +# Plot result + +segments = [[[i, y[i]], [i, y_[i]]] for i in range(n)] +lc = LineCollection(segments, zorder=0) +lc.set_array(np.ones(len(y))) +lc.set_linewidths(np.full(n, 0.5)) + +fig = plt.figure() +plt.plot(x, y, 'r.', markersize=12) +plt.plot(x, y_, 'g.-', markersize=12) +plt.plot(x, lr.predict(x[:, np.newaxis]), 'b-') +plt.gca().add_collection(lc) +plt.legend(('Data', 'Isotonic Fit', 'Linear Fit'), loc='lower right') +plt.title('Isotonic regression') +plt.show() diff --git a/simplifyPrograms.py b/simplifyPrograms.py new file mode 100644 index 0000000..e4bb916 --- /dev/null +++ b/simplifyPrograms.py @@ -0,0 +1,26 @@ +import networkx as nx +import matplot.pyplot as plt + + + +#define a graph +G=nx.Graph() + + + + +#read file data +readfile=open("c:\autoexec.bat","r") +for line in readfile: + spline=line.split(",") + if(int(spline[2]): + G.add_edge(spline[0],spline[1],color='r') + print(line) + G.add_edge(spline[0],spline[1],color='b') + +pos=nx.circular_layout(G) +edges=G.edges() +colors=[G[u],[v]['color'] for u,v in edges] +nx.draw(G,pos,node_color='b',with_label='True',edges=edges,edge_color=colors) +plt.show() + diff --git a/snake.py b/snake.py new file mode 100644 index 0000000..2fb5ad9 --- /dev/null +++ b/snake.py @@ -0,0 +1,20 @@ +import random +import curses + +s=curses.initscr() +curses.curs_set(0) +sh,sw =s.getmaxyx() +w=curses.newwin(sh,sw,0,0) +w.keypad(1) +w.timeout(1000) + +snkx=sw/4 +snky=sh/2 +snake=[ + [snky,snkx], + [snky,snkx-1], + [snky,snkx-2] + ] +food=[sh/2,sw/2] +w.addch(food[0],food[1],curses.ACS_PI) + diff --git a/socket.py b/socket.py new file mode 100644 index 0000000..767f883 --- /dev/null +++ b/socket.py @@ -0,0 +1,4 @@ +x='go python' +with open('foo.txt','w') as f : + f.write(x) + \ No newline at end of file diff --git a/soiral.py b/soiral.py new file mode 100644 index 0000000..a53753b --- /dev/null +++ b/soiral.py @@ -0,0 +1,21 @@ +import turtle #Outside_In +wn = turtle.Screen() +wn.bgcolor("light green") +wn.title("Turtle") +skk = turtle.Turtle() +skk.color("blue") + +def sqrfunc(size): + for i in range(5): + skk.fd(size) + skk.left(90) + size = size+5 + +sqrfunc(6) +sqrfunc(26) +sqrfunc(46) +sqrfunc(66) +sqrfunc(86) +sqrfunc(106) +sqrfunc(126) +sqrfunc(146) diff --git a/soleiil.py b/soleiil.py new file mode 100644 index 0000000..c546d60 --- /dev/null +++ b/soleiil.py @@ -0,0 +1,10 @@ +from turtle import * +color('red', 'yellow') +begin_fill() +while True: + fd(400) + lt(170) + if abs(pos()) < 1: + break +end_fill() +done() diff --git a/sortb.py b/sortb.py new file mode 100644 index 0000000..033c569 --- /dev/null +++ b/sortb.py @@ -0,0 +1,12 @@ +import os +def sortb(arr): + while True : + corrected = False + for i in range(0,len(arr)-1): + if arr[i]>arr[i+1]: + arr[i],arr[i+1]=arr[i+1],arr[i] + corrected = True + if not corrected : + return arr +t=[k for k in range(1,10) input()] +print(sortb(t)) \ No newline at end of file diff --git a/stylelll.py b/stylelll.py new file mode 100644 index 0000000..f9a2480 --- /dev/null +++ b/stylelll.py @@ -0,0 +1,8 @@ +import pandas as pd +import numpy as np + +np.random.seed(24) +df = pd.DataFrame({'A': np.linspace(1, 10, 10)}) +df = pd.concat([df, pd.DataFrame(np.random.randn(10, 4), columns=list('BCDE'))], + axis=1) +df.iloc[0, 2] = np.nan diff --git a/teee.py b/teee.py new file mode 100644 index 0000000..ba524fc --- /dev/null +++ b/teee.py @@ -0,0 +1,16 @@ +import numpy as np +from numpy.random import rand +from numpy.linalg import solve, inv +print("Hello") +a=np.array([[1,2,3],[4,5,6],[7,8,9]]) +b=a.transpose() +inv(a) +solve(a,b) +c=rand(3,3) +d=np.dot(a,c) +import matplotlib.pyplot as plt +import matplotlib as mpl + +x = np.linspace(0, 20, 100) +plt.plot(x, np.sin(x)) +plt.show() diff --git a/test1.py b/test1.py new file mode 100644 index 0000000..ba524fc --- /dev/null +++ b/test1.py @@ -0,0 +1,16 @@ +import numpy as np +from numpy.random import rand +from numpy.linalg import solve, inv +print("Hello") +a=np.array([[1,2,3],[4,5,6],[7,8,9]]) +b=a.transpose() +inv(a) +solve(a,b) +c=rand(3,3) +d=np.dot(a,c) +import matplotlib.pyplot as plt +import matplotlib as mpl + +x = np.linspace(0, 20, 100) +plt.plot(x, np.sin(x)) +plt.show() diff --git a/testa.pas.txt b/testa.pas.txt new file mode 100644 index 0000000..ab9f030 --- /dev/null +++ b/testa.pas.txt @@ -0,0 +1,3 @@ +program test; +uses wincrt; +write("hello world") \ No newline at end of file diff --git a/testa.py b/testa.py new file mode 100644 index 0000000..ab9f030 --- /dev/null +++ b/testa.py @@ -0,0 +1,3 @@ +program test; +uses wincrt; +write("hello world") \ No newline at end of file diff --git a/testa.sql b/testa.sql new file mode 100644 index 0000000..e69de29 diff --git a/tetris.py b/tetris.py new file mode 100644 index 0000000..ffbcf4b --- /dev/null +++ b/tetris.py @@ -0,0 +1,275 @@ +#!/usr/bin/env python +"tetris -- a brand new game written in python by Alfe" + +import sys, random, time, select, os #, termios + +width = 10 +height = 22 + +blocks = [ [ (0,0), (0,1), (0,-1), (1,0) ], # T + [ (0,0), (0,1), (0,2), (0,-1) ], # I + [ (0,0), (0,1), (1,1), (-1,0) ], # S + [ (0,0), (0,-1), (1,-1), (-1,0) ], # Z + [ (0,0), (0,1), (1,1), (1,0) ], # O + [ (0,0), (-1,1), (-1,0), (1,0) ], # L + [ (0,0), (1,1), (-1,0), (1,0) ], # J + ] + +inverted = '\033[7;1m' +blue = '\033[7;34m' +normal = '\033[0m' +clear_screen = '\033[2J' # clear the screen +home = '\033[H' # goto top left corner of the screen +# (the latter two were found using 'clear | od -c') + +empty = ' ' +black = inverted + ' ' + normal # two inverted spaces +blue = blue + ' ' + normal # two inverted spaces +floor = '==' + +left = 'left' +right = 'right' +turn = 'turn' +down = 'down' +quit = 'quit' + +shaft = None + +def play_tetris(): + initialize_shaft() + while True: # until game is lost + block = get_random_block() + coordinates = (width/2-1, 1) # in the middle at the top + if not place_block(block, coordinates, blue): # collision already? + return # game is lost! + next_fall_time = time.time() + fall_delay() + # ^^^ this is the time when the block will fall automatically + # one line down + while True: # until block is placed fixedly + print_shaft() + remove_block(block, coordinates) + x, y = coordinates + try: + try: + command = get_command(next_fall_time) + except Timeout: # no command given + raise Fall() + else: # no exception, so process command: + if command == left: + new_coordinates = (x-1, y) + new_block = block + elif command == right: + new_coordinates = (x+1, y) + new_block = block + elif command == turn: + new_coordinates = (x, y) + new_block = turn_block(block) + elif command == down: + raise Fall() + elif command == quit: + return + else: + raise Exception("internal error: %r" % command) + if place_block(new_block, new_coordinates, + blue): # command ok? + # execute the command: + block = new_block + coordinates = new_coordinates + else: + place_block(block, coordinates, blue) + # ignore the command which could not be executed + # maybe beep here or something ;-> + except Fall: + # make the block fall automatically: + new_coordinates = (x, y+1) + next_fall_time = time.time() + fall_delay() + if place_block(block, new_coordinates, blue): # can be placed? + coordinates = new_coordinates + else: + place_block(block, coordinates, + black) # place block there again + break # and bail out + remove_full_lines() + +class Timeout(Exception): pass +class Fall(Exception): pass + +def remove_full_lines(): + global shaft, width, height + def line_full(line): + global width + for x in range(width): + if line[x] == empty: + return False + return True + + def remove_line(y): + global shaft, width + del shaft[y] # cut out line + shaft.insert(0, [ empty ] * width) # fill up with an empty line + + for y in range(height): + if line_full(shaft[y]): + remove_line(y) + +def fall_delay(): + return 1.3 # cheap version; implement raising difficulty here + +def turn_block(block): + "return a turned copy(!) of the given block" + result = [] + for x, y in block: + result.append((y, -x)) + return result + +def get_command(next_fall_time): + "if a command is entered, return it; otherwise raise the exception Timeout" + while True: # until a timeout occurs or a command is found: + timeout = next_fall_time - time.time() + if timeout > 0.0: + (r, w, e) = select.select([ sys.stdin ], [], [], timeout) + else: + raise Timeout() + if sys.stdin not in r: # not input on stdin? + raise Timeout() + key = os.read(sys.stdin.fileno(), 1) + if key == 'j': + return left + elif key == 'l': + return right + elif key == 'k': + return turn + elif key == ' ': + return down + elif key == 'q': + return quit + else: # any other key: ignore + pass + +def place_block(block, coordinates, color): + "if the given block can be placed in the shaft at the given coordinates"\ + " then place it there and return True; return False otherwise and do not"\ + " place anything" + global shaft, width, height + block_x, block_y = coordinates + for stone_x, stone_y in block: + x = block_x + stone_x + y = block_y + stone_y + if (x < 0 or x >= width or + y < 0 or y >= height or # border collision? + shaft[y][x] != empty): # block collision? + return False # cannot be placed there + # reached here? ==> can be placed there + # now really place it: + for stone_x, stone_y in block: + x = block_x + stone_x + y = block_y + stone_y + shaft[y][x] = color + return True + +def remove_block(block, coordinates): + global shaft + block_x, block_y = coordinates + for stone_x, stone_y in block: + x = block_x + stone_x + y = block_y + stone_y + shaft[y][x] = empty + +def get_random_block(): + if random.randint(1, 10) == 1: + return perfect_block() or random.choice(blocks) + return random.choice(blocks) + +def perfect_block(): + result = [] + for y in range(height): + if filter(lambda b: b != empty, shaft[y]): # found summit + random_order = range(width) + random.shuffle(random_order) + for x in random_order: + if shaft[y][x] == empty: # found space besides summit + for x_ in range(width-x): # fill to the right + if shaft[y][x+x_] != empty: + break + for y_ in range(height-y): + if shaft[y+y_][x+x_] == empty: + result.append((x_, y_)) + else: + break + for x_ in range(-1, -x-1, -1): # fill to the left + if shaft[y][x+x_] != empty: + break + for y_ in range(height-y): + if shaft[y+y_][x+x_] == empty: + result.append((x_, y_)) + else: + break + # shift block in x direction to center it: + xmin = min(map(lambda v: v[0], result)) + xmax = max(map(lambda v: v[0], result)) + return map(lambda v: (v[0]-(xmax+xmin)/2, v[1]), result) + return None + +def initialize_shaft(): + global width, height, shaft, empty + shaft = [ None ] * height + for y in range(height): + shaft[y] = [ empty ] * width + +def print_shaft(): + # cursor-goto top left corner: + sys.stdout.write(home) + for y in range(height): + if y > 3: # does this line have a border? (the topmost ones do not) + sys.stdout.write(']') + else: + sys.stdout.write(' ') + for x in range(width): + sys.stdout.write(shaft[y][x]) + if y > 3: # does this line have a border? (the topmost ones do not) + sys.stdout.write('[\n') + else: + sys.stdout.write('\n') + + # print bottom: + sys.stdout.write(']' + floor * width + '[\n') + +def prepare_tty(): + "set the terminal in char mode (return each keyboard press at once) and"\ + " switch off echoing of this input; return the original settings" + stdin_fd = sys.stdin.fileno() # will most likely be 0 ;-> + old_stdin_config = termios.tcgetattr(stdin_fd) + [ iflag, oflag, cflag, lflag, ispeed, ospeed, cc ] = \ + termios.tcgetattr(stdin_fd) + cc[termios.VTIME] = 1 + cc[termios.VMIN] = 1 + iflag = iflag & ~(termios.IGNBRK | + termios.BRKINT | + termios.PARMRK | + termios.ISTRIP | + termios.INLCR | + termios.IGNCR | + #termios.ICRNL | + termios.IXON) + # oflag = oflag & ~termios.OPOST + cflag = cflag | termios.CS8 + lflag = lflag & ~(termios.ECHO | + termios.ECHONL | + termios.ICANON | + # termios.ISIG | + termios.IEXTEN) + termios.tcsetattr(stdin_fd, termios.TCSANOW, + [ iflag, oflag, cflag, lflag, ispeed, ospeed, cc ]) + return (stdin_fd, old_stdin_config) + +def cleanup_tty(original_tty_settings): + "restore the original terminal settings" + stdin_fd, old_stdin_config = original_tty_settings + termios.tcsetattr(stdin_fd, termios.TCSADRAIN, old_stdin_config) + +original_tty_settings = prepare_tty() # switch off line buffering etc. +sys.stdout.write(clear_screen) +try: # ensure that tty will be reset in the end + play_tetris() +finally: + cleanup_tty(original_tty_settings) diff --git a/thread.py b/thread.py new file mode 100644 index 0000000..8fc85e2 --- /dev/null +++ b/thread.py @@ -0,0 +1,33 @@ +import time +import threading + +verou=threading.RLock() +def f1(): + i=0 + while i<3 : + with verou: + ch="ABC" + for c in ch: + print(c) + time.sleep(1.3) + i+=1 +def f2(): + i=0 + while i<3: + print("f2 VVVVVVV") + time.sleep(1.3) + i+=1 +print("Execution sequentielle") +f1() +f2() +print("----------------------") + +print(" execution asynchrone ") + +th1=threading.Thread(target =f1) +th2=threading.Thread(target =f2) + +th1.start() +th2.start() +th1.join() +th2.join() diff --git a/tictac.py b/tictac.py new file mode 100644 index 0000000..61d8363 --- /dev/null +++ b/tictac.py @@ -0,0 +1,432 @@ +import random +import tkinter as tk +from tkinter import ttk +import tkinter.messagebox + +root = tk.Tk() + +""" *** Memory *** """ +board2 = [["0", "1", "2"], ["3", "4", "5"], ["6", "7", "8"]] +a = ["X"] + +""" *** Functions *** """ +player = tkinter.messagebox.askyesno("First thing first", "Playing against another player?") +print("is there another player? ", player) + + +def turn(pos1, board2, button, a): + """ enter choice to memory and change the board and interface """ + print("playing with", a) + for i in range(len(board2)): + for n in range(len(board2[i])): + if board2[i][n] == str(pos1): + board2[i][n] = str(a[0]) + + # toggle button text + + if button["text"] == " ": + button["text"] = str(a[0]) + + # change a to new turn + if player: + + if a[0] == "X": + a[0] = "O" + print("changed x to o") + + else: + a[0] = "X" + print("changed o to x") + + else: + print("cant, already taken") + aiturn = True + return aiturn + + # check win state + aiturn = win() + + # Ai + + if not player: + + print("fired ai") + + if not aiturn: + board2, aiturn = checkatk(board2, aiturn) + print("ai turn for atk is ", aiturn) + + if not aiturn: + board2, aiturn = checkdef(board2, aiturn) + print("ai turn for def is ", aiturn) + + if not aiturn: + board2, pos1, a, button, aiturn = aiplay(board2, pos1, a, button, aiturn) + print("ai turn for random is ", aiturn) + + # aiturn = False + + for i in range(3): + print(board2[i][0], board2[i][1], board2[i][2]) + + # check win state + aiturn = win() + + return board2, pos1, button, a, aiturn + + +def aiplay(board2, pos1, a, button, aiturn): + """ chose a random number and play it""" + pos1 = "".join(random.sample(["0", "1", "2", "3", "4", "5", "6", "7", "8"], 1)) + + for i in range(len(board2)): + for n in range(len(board2[i])): + if str(board2[i][n]) == str(pos1): + print(str(board2[i][n]), " is the changed value") + board2[i][n] = "O" + options[str(pos1)]() + aiturn = True + + return board2, pos1, a, button, aiturn + else: + # repeat if choice is taken + board2, pos1, a, button, aiturn = aiplay(board2, pos1, a, button, aiturn) + return board2, pos1, a, button, aiturn + + +def win(): + """check win state""" + for i in range(3): + + if "XXX" == str("".join(board2[i][0:3])) or "XXX" == (board2[0][i] + board2[1][i] + board2[2][i]): + reset(1) + aiturn = True + if player: + a[0] = "X" + return aiturn + + if (board2[0][0] + board2[1][1] + board2[2][2]) == "XXX" or ( + board2[0][2] + board2[1][1] + board2[2][0]) == "XXX": + reset(1) + aiturn = True + if player: + a[0] = "X" + return aiturn + + for i in range(3): + + if "OOO" == str("".join(board2[i][0:3])) or "OOO" == (board2[0][i] + board2[1][i] + board2[2][i]): + reset(2) + + if (board2[0][0] + board2[1][1] + board2[2][2]) == "OOO" or ( + board2[0][2] + board2[1][1] + board2[2][0]) == "OOO": + reset(2) + + info = 0 + for i in range(3): + for n in range(3): + if board2[i][n] == "X": + info += 1 + + if board2[i][n] == "O": + info += 1 + + if info == 9: + reset(0) + aiturn = True + return aiturn + + + +def reset(n): + """ win state, reset board """ + if n == 0: + tkinter.messagebox.showinfo('No one won', 'No one won, restarting') + else: + tkinter.messagebox.showinfo('There is a winner!', 'Player ' + str(n) + ' is the winner!') + numb = 0 + button1["text"] = " " + button2["text"] = " " + button3["text"] = " " + button4["text"] = " " + button5["text"] = " " + button6["text"] = " " + button7["text"] = " " + button8["text"] = " " + button9["text"] = " " + for i in range(len(board2)): + for n in range(len(board2[i])): + board2[i][n] = str(numb) + numb += 1 + + return board2 + + +def checkatk(board2, aiturn): + """win the game on the next move""" + danger = 0 + danger2 = 0 + danger3 = 0 + danger4 = 0 + + for n in range(3): + for i in range(3): + if i == 0: + danger = 0 + if board2[n][i] == "O": + danger += 1 + + if danger == 2: + for i in range(3): + if board2[n][i] != "O" and board2[n][i] != "X" and not aiturn: + options[board2[n][i]]() + print("Ai played") + board2[n][i] = "O" + danger = 0 + aiturn = True + + for i in range(3): + if i == 0: + danger2 = 0 + if board2[i][n] == "O": + danger2 += 1 + + if danger2 == 2: + for i in range(3): + if board2[i][n] != "O" and board2[i][n] != "X" and not aiturn: + options[board2[i][n]]() + print("Ai played") + board2[i][n] = "O" + danger2 = 0 + aiturn = True + + if board2[1][1] == "O": + danger3 += 1 + danger4 += 1 + + if board2[0][0] == "O": + danger3 += 1 + if board2[2][2] == "O": + danger3 += 1 + + if board2[2][0] == "O": + danger4 += 1 + if board2[0][2] == "O": + danger4 += 1 + + if danger3 == 2 and not aiturn: + if board2[0][0] != "O" and board2[0][0] != "X": + options[board2[0][0]]() + print("Ai played") + board2[0][0] = "O" + aiturn = True + + if board2[1][1] != "O" and board2[1][1] != "X": + options[board2[1][1]]() + print("Ai played") + board2[1][1] = "O" + aiturn = True + + if board2[2][2] != "O" and board2[2][2] != "X": + options[board2[2][2]]() + print("Ai played") + board2[2][2] = "O" + aiturn = True + + if danger4 == 2 and not aiturn: + if board2[0][2] != "O" and board2[0][2] != "X": + options[board2[0][2]]() + print("Ai played") + board2[0][2] = "O" + aiturn = True + + if board2[1][1] != "O" and board2[1][1] != "X": + options[board2[1][1]]() + print("Ai played") + board2[1][1] = "O" + aiturn = True + + if board2[2][0] != "O" and board2[2][0] != "X": + options[board2[2][0]]() + print("Ai played") + board2[2][0] = "O" + aiturn = True + + return board2, aiturn + + +def checkdef(board2, aiturn): + """block player in the next move""" + danger = 0 + danger2 = 0 + danger3 = 0 + danger4 = 0 + + for n in range(3): + for i in range(3): + if i == 0: + danger = 0 + if board2[n][i] == "X": + danger += 1 + + if danger == 2: + for i in range(3): + if board2[n][i] != "O" and board2[n][i] != "X" and not aiturn: + options[board2[n][i]]() + print("Ai played") + board2[n][i] = "O" + danger = 0 + aiturn = True + + for i in range(3): + if i == 0: + danger2 = 0 + if board2[i][n] == "X": + danger2 += 1 + + if danger2 == 2: + for i in range(3): + if board2[i][n] != "O" and board2[i][n] != "X" and not aiturn: + options[board2[i][n]]() + print("Ai played") + board2[i][n] = "O" + danger2 = 0 + aiturn = True + + if board2[1][1] == "X": + danger3 += 1 + danger4 += 1 + + if board2[0][0] == "X": + danger3 += 1 + if board2[2][2] == "X": + danger3 += 1 + + if board2[2][0] == "X": + danger4 += 1 + if board2[0][2] == "X": + danger4 += 1 + + if danger3 == 2 and not aiturn: + if board2[0][0] != "O" and board2[0][0] != "X": + options[board2[0][0]]() + print("Ai played") + board2[0][0] = "O" + aiturn = True + + if board2[1][1] != "O" and board2[1][1] != "X": + options[board2[1][1]]() + print("Ai played") + board2[1][1] = "O" + aiturn = True + + if board2[2][2] != "O" and board2[2][2] != "X": + options[board2[2][2]]() + print("Ai played") + board2[2][2] = "O" + aiturn = True + + if danger4 == 2 and not aiturn: + if board2[0][2] != "O" and board2[0][2] != "X": + options[board2[0][2]]() + print("Ai played") + board2[0][2] = "O" + aiturn = True + + if board2[1][1] != "O" and board2[1][1] != "X": + options[board2[1][1]]() + print("Ai played") + board2[1][1] = "O" + aiturn = True + + if board2[2][0] != "O" and board2[2][0] != "X": + options[board2[2][0]]() + print("Ai played") + board2[2][0] = "O" + aiturn = True + + return board2, aiturn + + +# functions to change the buttons the ai chose + +def ch1(): + button1["text"] = "O" + + +def ch2(): + button2["text"] = "O" + + +def ch3(): + button3["text"] = "O" + + +def ch4(): + button4["text"] = "O" + + +def ch5(): + button5["text"] = "O" + + +def ch6(): + button6["text"] = "O" + + +def ch7(): + button7["text"] = "O" + + +def ch8(): + button8["text"] = "O" + + +def ch9(): + button9["text"] = "O" + + +# dictionary + +options = {"0": ch1, + "1": ch2, + "2": ch3, + "3": ch4, + "4": ch5, + "5": ch6, + "6": ch7, + "7": ch8, + "8": ch9, + } + +""" *** Layout *** """ + +button1 = ttk.Button(root, text=" ", command=lambda: turn("0", board2, button1, a)) +button2 = ttk.Button(root, text=" ", command=lambda: turn("1", board2, button2, a)) +button3 = ttk.Button(root, text=" ", command=lambda: turn("2", board2, button3, a)) +button4 = ttk.Button(root, text=" ", command=lambda: turn("3", board2, button4, a)) +button5 = ttk.Button(root, text=" ", command=lambda: turn("4", board2, button5, a)) +button6 = ttk.Button(root, text=" ", command=lambda: turn("5", board2, button6, a)) +button7 = ttk.Button(root, text=" ", command=lambda: turn("6", board2, button7, a)) +button8 = ttk.Button(root, text=" ", command=lambda: turn("7", board2, button8, a)) +button9 = ttk.Button(root, text=" ", command=lambda: turn("8", board2, button9, a)) + +root.grid_columnconfigure(0, weight=1) +root.grid_columnconfigure(1, weight=1) +root.grid_columnconfigure(2, weight=1) + +root.grid_rowconfigure(0, weight=1) +root.grid_rowconfigure(1, weight=1) +root.grid_rowconfigure(2, weight=1) + +button1.grid(row=0, column=0, sticky="nsew", padx=4, pady=4) +button2.grid(row=0, column=1, sticky="nsew", padx=4, pady=4) +button3.grid(row=0, column=2, sticky="nsew", padx=4, pady=4) +button4.grid(row=1, column=0, sticky="nsew", padx=4, pady=4) +button5.grid(row=1, column=1, sticky="nsew", padx=4, pady=4) +button6.grid(row=1, column=2, sticky="nsew", padx=4, pady=4) +button7.grid(row=2, column=0, sticky="nsew", padx=4, pady=4) +button8.grid(row=2, column=1, sticky="nsew", padx=4, pady=4) +button9.grid(row=2, column=2, sticky="nsew", padx=4, pady=4) + +root.mainloop() diff --git a/tictacgame.py b/tictacgame.py new file mode 100644 index 0000000..b935a54 --- /dev/null +++ b/tictacgame.py @@ -0,0 +1,104 @@ +from tkinter import * +from tkinter import ttk + +ActivePlayer=1 #set active player +p1=[] +p2=[] + + + +root=Tk() +root.title("Tic tac : Player 1 ") +style=ttk.Style() +style.theme_use('classic') + + +bu1=ttk.Button(root,text=' ') +bu1.grid(row=0,column=0,sticky='snew',ipadx=40,ipady=40) +bu1.config(command=lambda:BuClick(1)) + +bu2=ttk.Button(root,text=' ') +bu2.grid(row=0,column=1,sticky='snew',ipadx=40,ipady=40) +bu2.config(command=lambda:BuClick(2)) + +bu3=ttk.Button(root,text=' ') +bu3.grid(row=0,column=2,sticky='snew',ipadx=40,ipady=40) +bu3.config(command=lambda:BuClick(3)) + + +bu4=ttk.Button(root,text=' ') +bu4.grid(row=1,column=0,sticky='snew',ipadx=40,ipady=40) +bu4.config(command=lambda:BuClick(4)) + +bu5=ttk.Button(root,text=' ') +bu5.grid(row=1,column=1,sticky='snew',ipadx=40,ipady=40) +bu5.config(command=lambda:BuClick(5)) + +bu6=ttk.Button(root,text=' ') +bu6.grid(row=1,column=2,sticky='snew',ipadx=40,ipady=40) +bu6.config(command=lambda:BuClick(6)) + +bu7=ttk.Button(root,text=' ') +bu7.grid(row=2,column=0,sticky='snew',ipadx=40,ipady=40) +bu7.config(command=lambda:BuClick(7)) + +bu8=ttk.Button(root,text=' ') +bu8.grid(row=2,column=1,sticky='snew',ipadx=40,ipady=40) +bu8.config(command=lambda:BuClick(8)) + +bu9=ttk.Button(root,text=' ') +bu9.grid(row=2,column=2,sticky='snew',ipadx=40,ipady=40) +bu9.config(command=lambda:BuClick(9)) + + +def BuClick(id): + global Activeplayer + global p1 + global p2 + + if (ActivePlayer==1) : + setLayout(id,'X') + p1.append(id) + root.title("Player 2 play now") + ActivePlayer=2 + #print("P1:{}".format(p1)) + elif (ActivePlayer==2) : + setLayout(id ,'O') + p2.append(id) + root.title("Player 1 play now") + ActivePlayer=1 + #print("P2:{}".format(p2)) + +def setLayout(id,texte): + if (id==1): + bu1.config(text=texte) + bu1.state('disabled') + elif id==2: + bu2.config(text=texte) + bu2.state('disabled') + elif id==3: + bu3.config(text=texte) + bu3.state('disabled') + elif id==4: + bu4.config(text=texte) + bu4.state('disabled') + elif id==5: + bu5.config(text=texte) + bu5.state('disabled') + elif id==6: + bu6.config(text=texte) + bu6.state('disabled') + elif id==7: + bu7.config(text=texte) + bu7.state('disabled') + elif id==8: + bu8.config(text=texte) + bu8.state('disabled') + elif id==9: + bu9.config(text=texte) + bu9.state('disabled') + #print(texte)# to do set button text + +#def checkwiner(): + +root.mainloop() diff --git a/tn flag.py b/tn flag.py new file mode 100644 index 0000000..52b0b08 --- /dev/null +++ b/tn flag.py @@ -0,0 +1,77 @@ + +#drapeau tunisien +import turtle +x=540 +y=360 +turtle.setup(x,y) +turtle.bgcolor("red") +turtle.penup() +#def whitecircle(posx,posy,radius, color1): +turtle.goto(0,-90) +turtle.pen() +turtle.pencolor('white') +turtle.pendown() +turtle.begin_fill() +turtle.circle(90, None, None) +turtle.color('white') +turtle.end_fill() +#turtle.done() +#def redcircle(posx,posy,radius, color2): +turtle.penup() +turtle.goto(0,-60) +turtle.pen() +turtle.pencolor('red') +turtle.pendown() +turtle.begin_fill() +turtle.circle(60, None, None) +turtle.color('red') +turtle.end_fill() +#turtle.done() + +turtle.penup() +turtle.goto(18,-54) +turtle.pen() +turtle.pencolor('white') +turtle.pendown() +turtle.begin_fill() +turtle.circle(54, None, None) +turtle.color('white') +turtle.end_fill() +#turtle.done() + +#star +turtle.penup() +turtle.goto(30,15) +turtle.pen() +turtle.pencolor('red') +turtle.pendown() +turtle.begin_fill() +turtle.left(18) + +turtle.forward(25) +turtle.right(144) +turtle.forward(25) +turtle.left(72) + +turtle.forward(25) +turtle.right(144) +turtle.forward(25) +turtle.left(72) + +turtle.forward(25) +turtle.right(144) +turtle.forward(25) +turtle.left(72) + +turtle.forward(25) +turtle.right(144) +turtle.forward(25) +turtle.left(72) + +turtle.forward(25) +turtle.right(144) +turtle.forward(25) +turtle.left(72) + +turtle.color('red') +turtle.end_fill() diff --git a/treeview.py b/treeview.py new file mode 100644 index 0000000..c6e1886 --- /dev/null +++ b/treeview.py @@ -0,0 +1,46 @@ +from tkinter import * +from tkinter import ttk +root=Tk() + +tv=ttk.Treeview(root) +tv.pack() +tv.heading('#0',text='Name') + +tv.insert('','1','item1',text='Mahdi') +tv.insert('','2','item2',text='Houda') +tv.insert('','3','item3',text='Mourad') +tv.insert('','4','item4',text='Maram') + +tv.insert('item1','0','item5',text='DOUDOU') +tv.insert('item1','0','item6',text='MAROUMA') +tv.insert('item2','0','item7',text='Mahdouch') +tv.insert('item3','0','item8',text='BOU OMRIN') + + +tv.detach('item8') +tv.move('item8','item4','0') + +tv.delete('item6') +tv.configure(column=('age')) +tv.heading('age',text='Family age') + +tv.set('item1','age','1.5') +tv.set('item2','age','32') +tv.set('item3','age','40') + +tv.column('age',width=70,anchor='center') + +def selectitem(event): + print(tv.selection()) +tv.bind('TreeviewSelect',selectitem) + + + + + + + + + + + diff --git a/tt.py b/tt.py new file mode 100644 index 0000000..03c715e --- /dev/null +++ b/tt.py @@ -0,0 +1,3 @@ +b=input('donner b :') +y=float(b) +print(2*y) diff --git a/tttg.py b/tttg.py new file mode 100644 index 0000000..a833cdf --- /dev/null +++ b/tttg.py @@ -0,0 +1,7 @@ + +t=[k**2 for k in range(10)] + +print(t) + + + diff --git a/tupleprime.py b/tupleprime.py new file mode 100644 index 0000000..692d3af --- /dev/null +++ b/tupleprime.py @@ -0,0 +1,34 @@ +def permutation(lst): + + if len(lst) == 0: + return [] + + # If there is only one element in lst then, only + # one permuatation is possible + if len(lst) == 1: + return [lst] + + # Find the permutations for lst if there are + # more than 1 characters + + l = [] # empty list that will store current permutation + + # Iterate the input(lst) and calculate the permutation + for i in range(len(lst)): + m = lst[i] + + # Extract lst[i] or m from the list. remLst is + # remaining list + remLst = lst[:i] + lst[i+1:] + + # Generating all permutations where m is first + # element + for p in permutation(remLst): + l.append([m] + p) + return l + + +# Driver program to test above function +data = list('abcde') +for p in permutation(data): + print (p) \ No newline at end of file diff --git a/tur.py b/tur.py new file mode 100644 index 0000000..214cb1a --- /dev/null +++ b/tur.py @@ -0,0 +1,6 @@ +import turtle +star = turtle.Turtle() +for i in range(50): + star.forward(50) + star.right(144) +turtle.done() diff --git a/tur.txt b/tur.txt new file mode 100644 index 0000000..e69de29 diff --git a/userDB.db b/userDB.db new file mode 100644 index 0000000..44c4675 Binary files /dev/null and b/userDB.db differ diff --git a/web1.py b/web1.py new file mode 100644 index 0000000..f03a3f6 --- /dev/null +++ b/web1.py @@ -0,0 +1,20 @@ +#import http.server +#import socketserver +#port=80 +#address=("",port) +#handler = http.server.SimpleHTTPRequestHandler +#httpd=socketserver.TCPServer(address,handler) +#print("serveur demmarer sur le port {port}") + +#hhtpd.serve_forever() + + +import http.server +port=80 +address=("",port) +server = http.server.CGIHTTPRequestHandler +httpd=socketserver.TCPServer(address,handler) +print("serveur demmarer sur le port {port}") + +hhtpd.serve_forever() +