blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
9516c757ff8eacaff3edb929e59fc7032610f4f1 | QuinPoley/ChessGame | /pieces.py | 8,000 | 3.703125 | 4 | class Piece:
def __init__(self, color, letter, number):
self.position = letter, number
self.letter = letter
self.number = number
self.color = color
self.hasMoved = False
def returnLegalMoves():
return None
def move(self, letter, number):
firstmove = False
if(not self.hasMoved):
self.hasMoved = True
firstmove = True
self.letter = letter
self.number = number
return firstmove
def returnHasMoved(self):
return self.hasMoved
class Pawn(Piece):
def __init__(self, color, letter, number):
super().__init__(color, letter, number)
self.value = 1
def returnLegalMoves(self):
legalmoves = []
if (self.color == "white"):
#it can only move up that column, or capture in adjacent columns.
legalmoves.append((self.letter, (self.number+1)))
legalmoves.append(((self.letter+1), (self.number+1)))
legalmoves.append(((self.letter-1), (self.number+1)))
if(self.hasMoved == False):
legalmoves.append((self.letter, (self.number+2)))
else:
legalmoves.append((self.letter, (self.number-1)))
legalmoves.append(((self.letter+1), (self.number-1)))
legalmoves.append(((self.letter-1), (self.number-1)))
if(self.hasMoved == False):
legalmoves.append((self.letter, (self.number-2)))
return legalmoves # Giving all possible moves now, if piece can capture we check for that later
def __str__(self):
return self.color + " pawn @ " + chr(96+self.letter) +","+ self.number.__str__() # 96 Because the letter a is 97, and letter is 1 indexed
class King(Piece):
def __init__(self, color, letter, number):
super().__init__(color, letter, number)
self.value = 100
def returnLegalMoves(self):
legalmoves = []
#it doesnt matter if we include moves off board because the only clicks registered are on the board
if(self.letter > 1):
legalmoves.append(((self.letter-1), self.number))
if(self.number > 1):
legalmoves.append(((self.letter-1), (self.number-1)))
if(self.number < 8):
legalmoves.append(((self.letter-1), (self.number+1)))
if(self.letter < 8):
legalmoves.append(((self.letter+1), self.number))
if(self.number > 1):
legalmoves.append(((self.letter+1), (self.number-1)))
if(self.number < 8):
legalmoves.append(((self.letter+1), (self.number+1)))
if(self.number > 1):
legalmoves.append((self.letter, (self.number-1)))
if(self.number < 8):
legalmoves.append((self.letter, (self.number+1)))
if(self.hasMoved == False):
legalmoves.append(((self.letter+2), self.number)) # Castle
legalmoves.append(((self.letter-2), self.number))
return legalmoves
def __str__(self):
return self.color + " King @ " + chr(96+self.letter) +","+ self.number.__str__()
class Queen(Piece):
def __init__(self, color, letter, number):
super().__init__(color, letter, number)
self.value = 10
def returnLegalMoves(self):
legalmoves = []
howFar = 9-self.letter if 9-self.letter < 9-self.number else 9-self.number #9?
for x in range(1, howFar):
legalmoves.append(((self.letter+x), (self.number+x)))# Diag Fwd Right
howFar = self.letter if self.letter < 9-self.number else 9-self.number
for x in range(1, howFar):
legalmoves.append(((self.letter-x), (self.number+x)))# Diag Fwd Left
howFar = 9-self.letter if 9-self.letter < self.number else self.number
for x in range(1, howFar):
legalmoves.append(((self.letter+x), (self.number-x)))# Diag Back Right
howFar = self.letter if self.letter < self.number else self.number
for x in range(1, howFar):
legalmoves.append(((self.letter-x), (self.number-x)))# Diag Back Left
for x in range((self.letter+1), 9):
legalmoves.append((x, self.number))
for x in range(1, self.letter):
legalmoves.append((x, self.number))
for x in range((self.number+1), 9):
legalmoves.append((self.letter, x))
for x in range(1, self.number):
legalmoves.append((self.letter, x))
return legalmoves
def __str__(self):
return self.color + " Queen @ " + chr(96+self.letter) +","+ self.number.__str__()
class Bishop(Piece):
def __init__(self, color, letter, number):
super().__init__(color, letter, number)
self.value = 3
def returnLegalMoves(self):
legalmoves = []
howFar = 9-self.letter if 9-self.letter < 9-self.number else 9-self.number #9?
for x in range(1, howFar):
legalmoves.append(((self.letter+x), (self.number+x)))# Diag Fwd Right
howFar = self.letter if self.letter < 9-self.number else 9-self.number
for x in range(1, howFar):
legalmoves.append(((self.letter-x), (self.number+x)))# Diag Fwd Left
howFar = 9-self.letter if 9-self.letter < self.number else self.number
for x in range(1, howFar):
legalmoves.append(((self.letter+x), (self.number-x)))# Diag Back Right
howFar = self.letter if self.letter < self.number else self.number
for x in range(1, howFar):
legalmoves.append(((self.letter-x), (self.number-x)))# Diag Back Left
return legalmoves
def __str__(self):
return self.color + " Bishop @ " + chr(96+self.letter) +","+ self.number.__str__()
class Knight(Piece):
def __init__(self, color, letter, number):
super().__init__(color, letter, number)
self.value = 3
def returnLegalMoves(self):
legalmoves = []
# This one is trickiest, +1 and the other is +2
if(self.letter > 1):
if(self.number < 7):
legalmoves.append(((self.letter-1), (self.number+2)))
if(self.number > 2):
legalmoves.append(((self.letter-1), (self.number-2)))
if(self.letter < 8):
if(self.number < 7):
legalmoves.append(((self.letter+1), (self.number+2)))
if(self.number > 2):
legalmoves.append(((self.letter+1), (self.number-2)))
if(self.letter < 7):
if(self.number > 1):
legalmoves.append(((self.letter+2), (self.number-1)))
if(self.number < 8):
legalmoves.append(((self.letter+2), (self.number+1)))
if(self.letter > 2):
if(self.number < 8):
legalmoves.append(((self.letter-2), (self.number+1)))
if(self.number > 1):
legalmoves.append(((self.letter-2), (self.number-1)))
return legalmoves
def __str__(self):
return self.color + "Knight @" + chr(96+self.letter) +","+ self.number.__str__()
class Rook(Piece):
def __init__(self, color, letter, number):
super().__init__(color, letter, number)
self.value = 5
def returnLegalMoves(self):
legalmoves = []
for x in range((self.letter+1), 9):
legalmoves.append((x, self.number))
for x in range(1, self.letter):
legalmoves.append((x, self.number))
for x in range((self.number+1), 9):
legalmoves.append((self.letter, x))
for x in range(1, self.number):
legalmoves.append((self.letter, x))
return legalmoves
def __str__(self):
return self.color + "Rook @" + chr(96+self.letter) +","+ self.number.__str__()
|
8e03751fb6c7e483d09dec12e3606bef9a443189 | jtbarker/pyocto-wordcounter | /countwordfreq.py | 690 | 4.0625 | 4 | #! /usr/bin/python
""" this program breaks a string into a list of component words
and counts each word, by Jon Barker, 2014-1-7"""
# import matplotlib
# import os
# print(dir(matplotlib))
def main():
print "input a sentence and i will count the words for you"
sentence = str(input("your sentence: "))
main()
# def wordcount(x):
# global a
# a = x.split(" ")
# if __name__ == "__main__":
# main()
# tester = "i am a an awesome person hello thanks hello goodbye"
# def wordcount(x):
# global a
# a = x.split(" ")
# return a
# wordcount(tester)
# lis = []
# for i in range(1,len(a)):
# if j in a == i:
# for c in tester:
# lis.append(c)
|
d052bdd3529c7c444cbec14bc1fe3ce1ae5b6093 | shaikafiya/pythonprogramming | /pangram.py | 141 | 3.734375 | 4 | s=input()
n=[]
for i in s:
if(i not in n):
n.append(i)
if(len(n)==27 or len(n)==28):
print("yes")
else:
print("no")
|
88f49fdde71ecb4ffcdbe49a889e058190d0feb9 | shaikafiya/pythonprogramming | /even num between two intervals.py | 101 | 3.515625 | 4 | n,m=input().split()
n=int(n)
m=int(m)
for k in range(n+1,m):
if(k%2==0):
print(k,end=" ")
|
359d0387e3684f13ae34726654419d169fb22efb | frankc95/exercise | /workbook_01.py | 140 | 3.796875 | 4 | weight_lbs = input('Weight (lbs): ')
weight_kg = int(weight_lbs) * 0.45
txt = "your weight in kilograms is "
print (txt + str(weight_kg))
|
0194f671da5971a2f30a4df885e6318312f6c172 | jeremysinger/python-forloop-parser | /tests/test3.py | 277 | 4 | 4 |
for i in range(0,10):
for j in range(0,i):
for k in range(i,j):
print(i,j)
for a in range(5):
for b in range(2):
print('foo')
for x in range(a):
for y in range(a-1):
for z in range(y):
print('bar')
|
f9b68289368ca68d3bc557f7e11261c9d8683c79 | mikyqwe/python.py | /firstday.py | 483 | 4.09375 | 4 | """Write a script that writes the day of the week for the New Year Day, for the last x years (x is given as argument)."""
import time
saptamana=["Luni","Marti","Miercuri","Joi","Vineri","Sambata","Duminica"]
def f(x):
date="01-01"
for i in range(1,x+1):
currentYear=2020+1-i
currentdate=date+"-"+str(currentYear)
formatedate=time.strptime(currentdate,"%m-%d-%Y")
print("Pentru anul {} prima zi a saptamanii este {}".format(currentYear,saptamana[formatedate.tm_wday]))
f(5) |
057a72a1e97177d2266389973837f9edf8b67806 | deepalikushwaha18/SDET-Training-Python | /Activity2.py | 160 | 4.1875 | 4 | num=int(input("enter number:"))
mod = num % 2
if mod > 0:
print("You picked an odd number.")
else:
print("You picked an even number.")
|
5945cce076d47a3dc3f23ed6dad61a3153ae4721 | MarcPartensky/Python-Games | /Game Structure/geometry/version4/myrect.py | 7,466 | 4 | 4 | class Rect:
"""Define a pure and simple rectangle."""
def createFromCorners(corners):
"""Create a rectangle."""
coordonnates=Rect.getCoordonnatesFromCorners(corners)
#print("c:",coordonnates)
return Rect(coordonnates[:2],coordonnates[2:])
def createFromRect(rect):
"""Create a rect from a pygame rect."""
coordonnates=Rect.getCoordonnatesFromRect(rect)
return Rect(coordonnates[:2],coordonnates[2:])
def createFromCoordonnates(coordonnates):
"""Create a rect using the coordonnates."""
return Rect(coordonnates[:2],coordonnates[2:])
def __init__(self,position,size):
"""Create a rectangle."""
self.position=position
self.size=size
def getCorners(self):
"""Return the corners of the case."""
px,py=self.position
sx,sy=self.size
return (px-sx/2,py-sy/2,px+sx/2,py+sy/2)
def setCorners(self):
"""Set the corners of the case."""
coordonnates=self.getCoordonnatesFromCorners(corners)
self.position=coordonnates[:2]
self.size=coordonnates[2:]
def __contains__(self,position):
"""Determine if a position is in the rectangle."""
x,y=position
return (self.xmin<=x<=self.xmax) and (self.ymin<=y<=self.ymax)
def getCoordonnates(self):
"""Return the coordonnates ofthe rectangle."""
return self.position+self.size
def setCoordonnates(self,coordonnates):
"""Set the coordonnates of the rectangle."""
self.position=coordonnates[:2]
self.size=coordonnates[2:]
def getRect(self):
"""Return the rect of the rectangle."""
return Rectangle.getRectFromCoordonnates(self.getCoordonnates)
def setRect(self,rect):
"""Set the rect of the rectangle."""
self.setCoordonnates(Rectangle.getCoordonnatesFromRect(rect))
def getCenter(self):
"""Return the center of the rectangle."""
return self.position
def setCenter(self,centers):
"""Set the center of the rectangle."""
self.position=center
def getX(self):
"""Return the x component."""
return self.position[0]
def setX(self,x):
"""Set the x component."""
self.position[0]=x
def getY(self):
"""Return the y component."""
return self.position[1]
def setY(self,y):
"""Set the y component."""
self.position[1]=y
def getSx(self):
"""Return the size of the x component."""
return self.size[0]
def setSx(self,sx):
"""Set the size of the x component."""
self.size[0]=sx
def getSy(self):
"""Return the size of the y component."""
return self.size[1]
def setSy(self,sy):
"""Set the size of the y component."""
self.size[1]=sy
def getXmin(self):
"""Return the minimum of the x component."""
return self.position[0]-self.size[0]/2
def setXmin(self,xmin):
"""Set the minimum of the x component."""
self.position[0]=xmin+self.size[0]/2
def getYmin(self):
"""Return the minimum of the y component."""
return self.position[1]-self.size[1]/2
def setYmin(self,ymin):
"""Set the minimum of the y component."""
self.position[1]=ymin+self.size[1]/2
def getXmax(self):
"""Return the maximum of the x component."""
return self.position[0]+self.size[0]/2
def setXmax(self,xmax):
"""Set the maximum of the x component."""
self.position[0]=xmax-self.size[0]/2
def getYmax(self):
"""Return the maximum of the y component."""
return self.position[1]+self.size[1]/2
def setYmax(self,ymax):
"""Set the maximum of the y component."""
self.position[1]=ymax-self.size[1]/2
corners=property(getCorners,setCorners,"Allow the user to manipulate the corners as an attribute for simplicity.")
rect=property(getRect,setRect,"Allow the user to manipulate the rect of the rectangle easily.")
coordonnates=property(getCoordonnates,setCoordonnates,"Allow the user to manipulate the coordonnates of the rectangle easily for simplicity.")
x=property(getX,setX,"Allow the user to manipulate the x component easily.")
y=property(getY,setY,"Allow the user to manipulate the y component easily.")
sx=property(getSx,setSx,"Allow the user to manipulate the size in x component easily.")
sy=property(getSy,setSy,"Allow the user to manipulate the size in y component easily.")
xmin=property(getXmin,setXmin,"Allow the user to manipulate the minimum of x component easily.")
xmax=property(getXmax,setXmax,"Allow the user to manipulate the maximum of x component easily.")
ymin=property(getYmin,setYmin,"Allow the user to manipulate the minimum of y component easily.")
ymax=property(getYmax,setYmax,"Allow the user to manipulate the maximum of y component easily.")
def getCornersFromCoordonnates(coordonnates):
"""Return the corners (top_left_corner,bottom_right_corner) using the coordonnates (position+size)."""
"""[x,y,sx,sy] -> [mx,my,Mx,My]"""
x,y,sx,sy=coordonnates
mx,my=x-sx/2,y-sy/2
Mx,My=x+sx/2,y+sy/2
corners=(mx,my,Mx,My)
return corners
def getCoordonnatesFromCorners(corners):
"""Return the coordonnates (position+size) using the corners (top_left_corner,bottom_right_corner)."""
"""[mx,my,Mx,My] -> [x,y,sx,sy]"""
mx,my,Mx,My=corners
sx,sy=Mx-mx,My-my
x,y=mx+sx/2,my+sy/2
coordonnates=(x,y,sx,sy)
return coordonnates
def getCoordonnatesFromRect(rect):
"""Return the coordonnates (position,size) using the rect (top_left_corner,size)."""
"""[x,y,sx,sy] -> [mx,my,sx,sy]"""
mx,my,sx,sy=rect
x,y=mx+sx/2,my+sy/2
coordonnates=[x,y,sx,sy]
return coordonnates
def getRectFromCoordonnates(coordonnates):
"""Return the rect (top_left_corner,size) using the coordonnates (position,size)."""
"""[mx,my,sx,sy] -> [x,y,sx,sy]"""
x,y,sx,sy=coordonnates
mx,my=x-sx/2,y-sy/2
rect=[mx,my,sx,sy]
return rect
def getRectFromCorners(corners):
"""Return the rect (top_left_corner,size) using the corners (top_left_corner,bottom_right_corner)."""
"""[mx,my,Mx,My] -> [mx,my,sx,sy]"""
mx,my,Mx,My=corners
sx,sy=Mx-mx,My-my
rect=[mx,my,sx,sy]
return rect
def getCornersFromRect(rect):
"""Return the (top_left_corner,bottom_right_corner) using the corners rect (top_left_corner,size)."""
"""[mx,my,Mx,My] -> [mx,my,sx,sy]"""
mx,my,sx,sy=rect
Mx,My=mx+sx,my+sy
corners=[mx,my,Mx,My]
return corners
def crossRect(self,other):
"""Determine the rectangle resulting of the intersection of two rectangles."""
if self.xmax<other.xmin or self.xmin>other.xmax: return
if self.ymax<other.ymin or self.ymin>other.ymax: return
xmin=max(self.xmin,other.xmin)
ymin=max(self.ymin,other.ymin)
xmax=min(self.xmax,other.xmax)
ymax=min(self.ymax,other.ymax)
#print([xmin,ymin,xmax,ymax])
return Rect.createFromCorners([xmin,ymin,xmax,ymax])
def resize(self,n=1):
"""Allow the user to resize the rectangle."""
for i in range(2):
self.size[i]*=n
|
e9432b4362be20638c2d72af1fb3a37f3e67c889 | MarcPartensky/Python-Games | /Game Structure/geometry/version5/mysyracuse.py | 1,528 | 3.53125 | 4 | from myabstract import Point,Segment
class Branch:
def __init__(self,n=1,g=0):
"""Create a branch."""
self.n=n
self.g=g
def children(self):
"""Return the childen branches of the branch."""
children=[Branch(self.n*2,self.g+1)]
a=(self.n-1)//3
if a%2==1:
children.append(Branch(a,self.g+1))
return children
def show(self,surface):
"""Show the branch to the surface."""
p=self.point()
for c in self.children():
pc=c.point()
s=Segment(p,pc)
s.show(surface)
def point(self):
"""Return the point associated to the branch."""
return Point(self.n,self.g)
class Tree:
"""Syracuse tree."""
def __init__(self,limit=10):
"""Create a syracuse tree."""
self.branches=[]
self.limit=limit
def __call__(self,branch=Branch()):
"""Calculate the branches recursively."""
if branch.g<self.limit:
for c in branch.children():
self.branches.append(c)
self(c)
def show(self,surface):
"""Show the tree on the surface."""
for branch in self.branches:
branch.show(surface)
if __name__=="__main__":
from mysurface import Surface
surface=Surface()
tree=Tree()
tree()
while surface.open:
surface.check()
surface.control()
surface.clear()
surface.show()
tree.show(surface)
surface.flip()
|
4a25f75e797b7ca5915b7c8689482a6f329a8af1 | MarcPartensky/Python-Games | /Game Structure/geometry/version3/mypoint.py | 6,376 | 4.09375 | 4 | from math import pi,sqrt,atan,cos,sin
import random
mean=lambda x:sum(x)/len(x)
import mycolors
class Point:
def random(min=-1,max=1,radius=0.1,fill=False,color=mycolors.WHITE):
"""Create a random point using optional minimum and maximum."""
x=random.uniform(min,max)
y=random.uniform(min,max)
return Point(x,y,radius=radius,fill=fill,color=color)
def turnPoints(angles,points):
"""Turn the points around themselves."""
l=len(points)
for i in range(l-1):
points[i].turn(angles[i],points[i+1:])
def showPoints(surface,points):
"""Show the points on the surface."""
for point in points:
point.show(surface)
def __init__(self,*args,mode=0,size=[0.1,0.1],width=1,radius=0.1,fill=False,color=mycolors.WHITE):
"""Create a point using x, y, radius, fill and color."""
args=list(args)
if len(args)==1:
args=args[0]
if type(args)==list or type(args)==tuple:
self.x=args[0]
self.y=args[1]
else:
raise Exception("The object used to define the point has not been recognised.")
elif len(args)==2:
if (type(args[0])==int and type(args[1])==int) or (type(args[0]==float) and type(args[1])==float):
self.x=args[0]
self.y=args[1]
else:
raise Exception("The list of objects used to define the point has not been recognised.")
else:
raise Exception("The list object used to define the point has not been recognised because it contains too many components.")
self.mode=mode
self.size=size
self.width=width
self.radius=radius
self.fill=fill
self.color=color
def __call__(self):
"""Return the coordonnates of the points."""
return [self.x,self.y]
def __position__(self):
"""Return the coordonnates of the points."""
return [self.x,self.y]
def __contains__(self,other):
"""Return bool if objects is in point."""
ox,oy=other[0],other[1]
if self.radius>=sqrt((ox-self.x)**2+(oy-self.y)**2):
return True
else:
return False
def __getitem__(self,index):
"""Return x or y value using given index."""
if index==0:
return self.x
if index==1:
return self.y
def __setitem__(self,index,value):
"""Change x or y value using given index and value."""
if index==0:
self.x=value
if index==1:
self.y=value
def rotate(self,angle=pi,point=[0,0]):
"""Rotate the point using the angle and the center of rotation.
Uses the origin for the center of rotation by default."""
v=Vector(self.x-point[0],self.y-point[1])
v.rotate(angle)
new_point=v(point)
self.x,self.y=new_point
def turn(self,angle=pi,points=[]):
"""Turn the points around itself."""
for point in points:
point.rotate(angle,self)
def move(self,*step):
"""Move the point using given step."""
self.x+=step[0]
self.y+=step[1]
def showCross(self,window,color=None,size=None,width=None):
"""Show the point under the form of a cross using the window."""
if not color: color=self.color
if not size: size=self.size
if not width: width=self.width
x,y=self
sx,sy=size
xmin=x-sx/2
ymin=y-sy/2
xmax=x+sx/2
ymax=y+sy/2
window.draw.line(window.screen,color,[xmin,ymin],[xmax,ymax],width)
window.draw.line(window.screen,color,[xmin,ymax],[xmax,ymin],width)
def showCircle(self,window,color=None,radius=None,fill=None):
"""Show a point under the form of a circle using the window."""
if not color: color=self.color
if not radius: radius=self.radius
if not fill: fill=self.fill
window.draw.circle(window.screen,color,[self.x,self.y],radius,not(fill))
def show(self,window,mode=None,color=None,size=None,width=None,radius=None,fill=None):
"""Show the point on the window."""
if not mode: mode=self.mode
if mode==0 or mode=="circle":
self.showCircle(window,color=color,radius=radius,fill=fill)
if mode==1 or mode=="cross":
self.showCross(window,color=color,size=size,width=width)
def showText(self,window,text,size=20,color=mycolors.WHITE):
"""Show the name of the point on the window."""
window.print(text,self,size=size,color=color)
def __add__(self,other):
"""Add the components of 2 objects."""
return Point(self.x+other[0],self.y+other[1])
def __sub__(self,other):
"""Substract the components of 2 objects."""
return Point(self.x-other[0],self.y-other[1])
def __iter__(self):
"""Iterate the points of the form."""
self.iterator=0
return self
def __next__(self):
"""Return the next point threw an iteration."""
if self.iterator < 2:
if self.iterator==0: value=self.x
if self.iterator==1: value=self.y
self.iterator+=1
return value
else:
raise StopIteration
def truncate(self):
"""Truncate the position of the point by making the x and y components integers."""
self.x=int(self.x)
self.y=int(self.y)
def __str__(self):
"""Return the string representation of a point."""
return "Point:"+str(self.__dict__)
if __name__=="__main__":
from mysurface import Surface
from myvector import Vector
surface=Surface(fullscreen=True)
p1=Point(0,0,color=mycolors.RED,fill=True)
p2=Point(5,0,color=mycolors.GREEN,fill=True)
p3=Point(10,0,color=mycolors.BLUE,fill=True)
p4=Point(15,0,color=mycolors.YELLOW,fill=True)
p5=Point(20,0,color=mycolors.ORANGE,fill=True)
points=[p1,p2,p3,p4,p5]
points=[Point(5*i,0,radius=0.2) for i in range(10)]
angles=[i/1000 for i in range(1,len(points))]
while surface.open:
surface.check()
surface.control()
surface.clear()
surface.show()
Point.turnPoints(angles,points)
Point.showPoints(surface,points)
surface.flip()
|
7c3ba27c237a61201655c18fd2520838b5215778 | MarcPartensky/Python-Games | /Mandelbrot/mandelbrot1.py | 1,621 | 3.640625 | 4 | import numpy as np
from matplotlib import pyplot as plt
from matplotlib import colors
#%matplotlib inline
settings=[-2.0,0.5,-1.25,1.25,3,3,80]
def mandelbrot(z,maxiter):
c = z
for n in range(maxiter):
if abs(z) > 2:
return n
z = z*z + c
return maxiter
def mandelbrot_set(xmin,xmax,ymin,ymax,width,height,maxiter):
r1 = np.linspace(xmin, xmax, width)
r2 = np.linspace(ymin, ymax, height)
return (r1,r2,[mandelbrot(complex(r, i),maxiter) for r in r1 for i in r2])
def mandelbrot_image(xmin,xmax,ymin,ymax,width=3,height=3,maxiter=80,cmap='hot'):
print("Initiating the mandelbrot image.")
dpi = 72 #Zoom of the image
img_width = dpi * width #Find the width of the image using the zoom and the width of the set
img_height = dpi * height #Same operation for the height
x,y,z = mandelbrot_set(xmin,xmax,ymin,ymax,img_width,img_height,maxiter) #Find the set
print("The set is done.")
print(type(z[0]))
fig, ax = plt.subplots(figsize=(width, height),dpi=72) #get plt components
ticks = np.arange(0,img_width,3*dpi) #find the steps
x_ticks = xmin + (xmax-xmin)*ticks/img_width #split the x axis
plt.xticks(ticks, x_ticks)
y_ticks = ymin + (ymax-ymin)*ticks/img_width #split the y axis
plt.yticks(ticks, y_ticks)
print("Image settings are done.")
norm = colors.PowerNorm(0.3) #Cool colors i guess
ax.imshow(z,cmap=cmap,origin='lower',norm=norm) #create a dope heat map
print("Image is done.")
mandelbrot_image(-2.0,0.5,-1.25,1.25,maxiter=80,cmap='gnuplot2')
#img=Image.fromarray(ms,'RGB')
#img.show()
|
237174569b314b5ad7b2df0f9d0cc2bc80a5a3f2 | MarcPartensky/Python-Games | /Game Structure/geometry/version3/myvector.py | 8,935 | 3.71875 | 4 | from mydirection import Direction
from mypoint import Point
from math import cos,sin
from cmath import polar
import mycolors
import random
class Vector:
def random(min=-1,max=1,color=mycolors.WHITE,width=1,arrow=[0.1,0.5]):
"""Create a random vector using optional min and max."""
x=random.uniform(min,max)
y=random.uniform(min,max)
return Vector(x,y,color=color,width=width,arrow=arrow)
def createFromPolarCoordonnates(norm,angle,color=mycolors.WHITE,width=1,arrow=[0.1,0.5]):
"""Create a vector using norm and angle from polar coordonnates."""
x,y=Vector.cartesian([norm,angle])
return Vector(x,y,color=color,width=width,arrow=arrow)
def createFromSegment(segment,color=mycolors.WHITE,width=1,arrow=[0.1,0.5]):
"""Create a vector from a segment."""
return Vector.createFromTwoPoints(segment.p1,segment.p2,color=color,width=width,arrow=arrow)
def createFromTwoPoints(point1,point2,color=mycolors.WHITE,width=1,arrow=[0.1,0.5]):
"""Create a vector from 2 points."""
x=point2.x-point1.x
y=point2.y-point1.y
return Vector(x,y,color=color,width=width,arrow=arrow)
def createFromPoint(point,color=mycolors.WHITE,width=1,arrow=[0.1,0.5]):
"""Create a vector from a single point."""
return Vector(point.x,point.y,color=color,width=width,arrow=arrow)
def createFromLine(line,color=mycolors.WHITE,width=1,arrow=[0.1,0.5]):
"""Create a vector from a line."""
angle=line.angle()
x,y=Vector.cartesian([1,angle])
return Vector(x,y,color=color,width=width,arrow=arrow)
def polar(position):
"""Return the polar position [norm,angle] using cartesian position [x,y]."""
return list(polar(complex(position[0],position[1])))
def cartesian(position):
"""Return the cartesian position [x,y] using polar position [norm,angle]."""
return [position[0]*cos(position[1]),position[0]*sin(position[1])]
def __init__(self,*args,color=(255,255,255),width=1,arrow=[0.1,0.5]):
"""Create a vector."""
args=list(args)
if len(args)==1:
args=args[0]
if type(args)==Point:
self.x=args.x
self.y=args.y
elif type(args)==list or type(args)==tuple:
if type(args[0])==Point and type(args[1])==Point:
self.x=args[1].x-args[0].x
self.y=args[1].y-args[0].y
elif (type(args[0])==int or type(args[0])==float) and (type(args[1])==int or type(args[1])==float):
self.x=args[0]
self.y=args[1]
else:
raise Exception("The list of objects used to define the vector has not been recognised.")
else:
raise Exception("The object used to define the vector has not been recognised.")
self.color=color
self.width=width
self.arrow=arrow
def show(self,p,window,color=None,width=None):
"""Show the vector."""
if not color: color=self.color
if not width: width=self.width
q=self(p)
v=-self.arrow[0]*self #wtf
v1=v%self.arrow[1]
v2=v%-self.arrow[1]
a=v1(q)
b=v2(q)
window.draw.line(window.screen,color,p(),q(),width)
window.draw.line(window.screen,color,q(),a(),width)
window.draw.line(window.screen,color,q(),b(),width)
def __iter__(self):
"""Iterate the points of the form."""
self.iterator=0
return self
def __next__(self):
"""Return the next point threw an iteration."""
if self.iterator<2:
if self.iterator==0: value=self.x
if self.iterator==1: value=self.y
self.iterator+=1
return value
else:
raise StopIteration
def __neg__(self):
"""Return the negative vector."""
x=-self.x
y=-self.y
return Vector(x,y,width=self.width,color=self.color)
def colinear(self,other):
"""Return if two vectors are colinear."""
return self.x*other.y-self.y*other.x==0
__floordiv__=colinear
def scalar(self,other):
"""Return the scalar product between two vectors."""
return self.x*other.x+self.y*other.y
def cross(self,other):
"""Determine if a vector crosses another using dot product."""
return self.scalar(other)==0
def __imul__(self,factor):
"""Multiply a vector by a given factor."""
if type(factor)==int or type(factor)==float:
self.x*=factor
self.y*=factor
else:
raise Exception("Type "+str(type(factor))+" is not valid. Expected float or int types.")
def __mul__(self,factor,color=None,width=None,arrow=None):
"""Multiply a vector by a given factor."""
if not color: color=self.color
if not width: width=self.width
if not arrow: arrow=self.arrow
if type(factor)==int or type(factor)==float:
return Vector(self.x*factor,self.y*factor,color=color,width=width,arrow=arrow)
else:
raise Exception("Type "+str(type(factor))+" is not valid. Expected float or int types.")
__rmul__=__mul__ #Allow front extern multiplication using back extern multiplication with scalars
def __truediv__(self,factor):
"""Multiply a vector by a given factor."""
if type(factor)==Vector:
pass
else:
x=self.x/factor
y=self.y/factor
return Vector(x,y,width=self.width,color=self.color)
def __add__(self,other):
"""Add two vectors together."""
return Vector(self.x+other.x,self.y+other.y,width=self.width,color=self.color)
def __iadd__(self,other):
"""Add a vector to another."""
self.x+=other.x
self.y+=other.y
return self
def rotate(self,angle):
"""Rotate a vector using the angle of rotation."""
n,a=Vector.polar([self.x,self.y])
a+=angle
self.x=n*cos(a)
self.y=n*sin(a)
def __mod__(self,angle):
"""Return the rotated vector using the angle of rotation."""
n,a=Vector.polar([self.x,self.y])
a+=angle
return Vector(n*cos(a),n*sin(a),color=self.color,width=self.width,arrow=self.arrow)
__imod__=__mod__
def __getitem__(self,index):
"""Return x or y value using given index."""
if index==0:
return self.x
if index==1:
return self.y
def __setitem__(self,index,value):
"""Change x or y value using given index and value."""
if index==0:
self.x=value
if index==1:
self.y=value
def __call__(self,*points):
"""Return points by applying the vector on those."""
new_points=[point+self for point in points]
if len(points)==1:
return new_points[0]
else:
return new_points
def apply(self,point):
"""Return the point after applying the vector to it."""
return self+point
def allApply(self,points):
"""Return the points after applying the vector to those."""
new_points=[point+self for point in points]
return new_points
def angle(self):
"""Return the angle of a vector with the [1,0] direction in cartesian coordonnates."""
return Vector.polar([self.x,self.y])[1]
def norm(self):
"""Return the angle of a vector with the [1,0] direction in cartesian coordonnates."""
return Vector.polar([self.x,self.y])[0]
def __xor__(self,other):
"""Return the angle between two vectors."""
return self.angle()-other.angle()
def __invert__(self):
"""Return the unit vector."""
a=self.angle()
position=Vector.cartesian([1,a])
return Vector(position)
def __str__(self):
"""Return a string description of the vector."""
text="Vector:"+str(self.__dict__)
return text
if __name__=="__main__":
from mysurface import Surface
window=Surface(fullscreen=True)
p1=Point(5,1)
p2=Point(5,4)
p3=Point(3,2)
v1=Vector.createFromTwoPoints(p1,p2)
v4=Vector.random(color=mycolors.YELLOW)
v3=~v1
v3.color=mycolors.ORANGE
print(tuple(v3))
x,y=v1 #Unpacking test
print("x,y:",x,y)
print(v1) #Give a string representation of the vector
v2=0.8*v1 #Multiply vector by scalar 0.8
p4=v2(p1)
v2.color=(255,0,0)
p4.color=(0,255,0)
while window.open:
window.check()
window.clear()
window.show()
window.control() #Specific to surfaces
v1.show(p1,window)
v2%=0.3 #Rotate the form by 0.3 radian
v2.show(p1,window)
v3.show(p1,window)
window.print("This is p1",tuple(p1))
p2.show(window)
p4.show(window)
window.flip()
|
e4f909f0ecdf3f3529efe9de530ab31df9e4c1ed | MarcPartensky/Python-Games | /Game Structure/geometry/version4/myabstract.py | 74,221 | 3.9375 | 4 | from math import pi,sqrt,atan,cos,sin
from cmath import polar
from mytools import timer
import math
import random
import mycolors
average=mean=lambda x:sum(x)/len(x)
digits=2 #Number of digits of precision of the objects when displayed
class Point:
"""Representation of a point that can be displayed on screen."""
def origin(d=2):
"""Return the origin."""
return Point([0 for i in range(d)])
null=neutral=zero=origin
def random(corners=[-1,-1,1,1],radius=0.02,fill=False,color=mycolors.WHITE):
"""Create a random point using optional minimum and maximum."""
xmin,ymin,xmax,ymax=corners
x=random.uniform(xmin,xmax)
y=random.uniform(ymin,ymax)
return Point(x,y,radius=radius,fill=fill,color=color)
def distance(p1,p2):
"""Return the distance between the two points."""
return math.sqrt(sum([(c1-c2)**2 for (c1,c2) in zip(p1.components,p2.components)]))
def turnPoints(angles,points):
"""Turn the points around themselves."""
l=len(points)
for i in range(l-1):
points[i].turn(angles[i],points[i+1:])
def showPoints(surface,points):
"""Show the points on the surface."""
for point in points:
point.show(surface)
def createFromVector(vector):
"""Create a point from a vector."""
return Point(vector.x,vector.y)
def __init__(self,*components,mode=0,size=[0.1,0.1],width=1,radius=0.02,fill=False,color=mycolors.WHITE,conversion=True):
"""Create a point using its components and optional radius, fill, color and conversion."""
if components!=():
if type(components[0])==list:
components=components[0]
self.components=list(components)
self.mode=mode
self.size=size
self.width=width
self.radius=radius
self.fill=fill
self.color=color
self.conversion=conversion
def __len__(self):
"""Return the number of components of the point."""
return len(self.components)
def setX(self,value):
"""Set the x component."""
self.components[0]=value
def getX(self):
"""Return the x component."""
return self.components[0]
def delX(self):
"""Delete the x component and so shifting to a new one."""
del self.components[0]
def setY(self,value):
"""Set the y component."""
self.components[1]=value
def getY(self):
"""Return the y component."""
return self.components[1]
def delY(self):
"""Delete the y component."""
del self.components[1]
x=property(getX,setX,delX,"Allow the user to manipulate the x component easily.")
y=property(getY,setY,delY,"Allow the user to manipulate the y component easily.")
def __eq__(self,other):
"""Determine if two points are equals by comparing its components."""
return abs(self-other)<10e-10
def __ne__(self,other):
"""Determine if two points are unequals by comparing its components."""
return tuple(self)!=tuple(other)
def __position__(self):
"""Return the coordonnates of the points."""
return [self.x,self.y]
def __contains__(self,other):
"""Determine if an object is in the point."""
x,y=other
return self.radius>=sqrt((x-self.x)**2+(y-self.y)**2)
def __getitem__(self,index):
"""Return x or y value using given index."""
return self.components[index]
def __setitem__(self,index,value):
"""Change x or y value using given index and value."""
self.components[index]=value
def __abs__(self):
"""Return the distance of the point to the origin."""
return Vector.createFromPoint(self).norm
def __tuple__(self):
"""Return the components in tuple form."""
return tuple(self.components)
def __list__(self):
"""Return the components."""
return self.components
def rotate(self,angle=pi,point=None):
"""Rotate the point using the angle and the center of rotation.
Uses the origin for the center of rotation by default."""
if not point: point=Point.origin(d=self.dimension)
v=Vector.createFromTwoPoints(point,self)
v.rotate(angle)
self.components=v(point).components
def turn(self,angle=pi,points=[]):
"""Turn the points around itself."""
for point in points:
point.rotate(angle,self)
def move(self,*step):
"""Move the point using given step."""
self.x+=step[0]
self.y+=step[1]
def around(self,point,distance):
"""Determine if a given point is in a radius 'distance' of the point."""
return self.distance(point)<=distance
def showCross(self,window,color=None,size=None,width=None,conversion=None):
"""Show the point under the form of a cross using the window."""
if not color: color=self.color
if not size: size=self.size
if not width: width=self.width
if not conversion: conversion=self.conversion
x,y=self
sx,sy=size
xmin=x-sx/2
ymin=y-sy/2
xmax=x+sx/2
ymax=y+sy/2
window.draw.line(window.screen,color,[xmin,ymin],[xmax,ymax],width,conversion)
window.draw.line(window.screen,color,[xmin,ymax],[xmax,ymin],width,conversion)
def showCircle(self,window,color=None,radius=None,fill=None,conversion=None):
"""Show a point under the form of a circle using the window."""
if not color: color=self.color
if not radius: radius=self.radius
if not fill: fill=self.fill
if not conversion: conversion=self.conversion
window.draw.circle(window.screen,color,[self.x,self.y],radius,fill,conversion)
def show(self,window,color=None,mode=None,fill=None,radius=None,size=None,width=None,conversion=None):
"""Show the point on the window."""
if not mode: mode=self.mode
if mode==0 or mode=="circle":
self.showCircle(window,color,radius,fill,conversion)
if mode==1 or mode=="cross":
self.showCross(window,color,size,width,conversion)
def showText(self,context,text,text_size=20,color=mycolors.WHITE):
"""Show the text next to the point on the window."""
context.print(text,self.components,text_size,color=color)
def __add__(self,other):
"""Add two points."""
return Point([c1+c2 for (c1,c2) in zip(self.components,other.components)])
def __iadd__(self,other):
"""Add a point to the actual point."""
self.components=[c1+c2 for (c1,c2) in zip(self.components,other.components)]
__radd__=__add__
def __sub__(self,other):
"""Add a point to the actual point."""
return Point([c1-c2 for (c1,c2) in zip(self.components,other.components)])
def __isub__(self,other):
"""Add a point to the actual point."""
self.components=[c1-c2 for (c1,c2) in zip(self.components,other.components)]
__rsub__=__sub__
def __sub__(self,other):
"""Substract the components of 2 objects."""
return Point(self.x-other[0],self.y-other[1])
def __ge__(self,other):
"""Determine if a point is farther to the origin."""
return self.x**2+self.y**2>=other.x**2+other.y**2
def __gt__(self,other):
"""Determine if a point is farther to the origin."""
return self.x**2+self.y**2>other.x**2+other.y**2
def __le__(self,other):
"""Determine if a point is the nearest to the origin."""
return self.x**2+self.y**2<=other.x**2+other.y**2
def __lt__(self,other):
"""Determine if a point is the nearest to the origin."""
return self.x**2+self.y**2<other.x**2+other.y**2
def __iter__(self):
"""Iterate the points of the form."""
self.iterator=0
return self
def __next__(self):
"""Return the next point threw an iteration."""
if self.iterator<len(self.components):
self.iterator+=1
return self.components[self.iterator-1]
else:
raise StopIteration
def truncate(self):
"""Truncate the position of the point by making the x and y components integers."""
for i in range(self.dimension):
self.components[i]=int(self.components[i])
def __str__(self):
"""Return the string representation of a point."""
return "p("+",".join([str(round(c,digits)) for c in self.components])+")"
def getPosition(self):
"""Return the components."""
return self.components
def setPosition(self,position):
"""Set the components."""
self.components=position
def getDimension(self):
"""Return the dimension of the point."""
return len(self.components)
def setDimension(self,dimension):
"""Set the dimension of the point by setting to 0 the new components."""
self.components=self.components[:dimension]
self.components+=[0 for i in range(dimension-len(self.components))]
def delDimension(self):
"""Delete the components of the points."""
self.components=[]
position=property(getPosition,setPosition,"Same as component although only component should be used.")
dimension=property(getDimension,setDimension,delDimension,"Representation of the dimension point which is the length of the components.")
class Direction:
"""Base class of lines and segments."""
def __init__(self): #position,width,color):
pass
class Vector:
def null(d=2):
"""Return the null vector."""
return Vector([0 for i in range(d)])
neutral=zero=null
def random(corners=[-1,-1,1,1],color=mycolors.WHITE,width=1,arrow=[0.1,0.5]):
"""Create a random vector using optional min and max."""
xmin,ymin,xmax,ymax=corners
x=random.uniform(xmin,xmax)
y=random.uniform(ymin,ymax)
return Vector(x,y,color=color,width=width,arrow=arrow)
def sum(vectors):
"""Return the vector that correspond to the sum of all the vectors."""
result=Vector.null()
for vector in vectors:
result+=vector
return result
def average(vectors):
"""Return the vector that correspond to the mean of all the vectors."""
return Vector.sum(vectors)/len(vectors)
mean=average
def collinear(*vectors,e=10e-10):
"""Determine if all the vectors are colinear."""
l=len(vectors)
if l==2:
v1=vectors[0]
v2=vectors[1]
return abs(v1.x*v2.y-v1.y-v2.x)<e
else:
for i in range(l):
for j in range(i+1,l):
if not Vector.collinear(vectors[i],vectors[j]):
return False
return True
def sameDirection(*vectors,e=10e-10):
"""Determine if all the vectors are in the same direction."""
l=len(vectors)
if l==2:
v1=vectors[0]
v2=vectors[1]
return (abs(v1.angle-v2.angle)%(2*math.pi))<e
else:
for i in range(l):
for j in range(i+1,l):
if not Vector.sameDirection(vectors[i],vectors[j]):
return False
return True
def createFromPolarCoordonnates(norm,angle,color=mycolors.WHITE,width=1,arrow=[0.1,0.5]):
"""Create a vector using norm and angle from polar coordonnates."""
x,y=Vector.cartesian([norm,angle])
return Vector(x,y,color=color,width=width,arrow=arrow)
def createFromSegment(segment,color=mycolors.WHITE,width=1,arrow=[0.1,0.5]):
"""Create a vector from a segment."""
return Vector.createFromTwoPoints(segment.p1,segment.p2,color=color,width=width,arrow=arrow)
def createFromTwoPoints(point1,point2,color=mycolors.WHITE,width=1,arrow=[0.1,0.5]):
"""Create a vector from 2 points."""
return Vector([c2-c1 for (c1,c2) in zip(point1.components,point2.components)],color=color,width=width,arrow=arrow)
def createFromTwoTuples(tuple1,tuple2,color=mycolors.WHITE,width=1,arrow=[0.1,0.5]):
"""Create a vector from 2 tuples."""
return Vector([c2-c1 for (c1,c2) in zip(tuple1,tuple2)],color=color,width=width,arrow=arrow)
def createFromPoint(point,color=mycolors.WHITE,width=1,arrow=[0.1,0.5]):
"""Create a vector from a single point."""
return Vector(point.x,point.y,color=color,width=width,arrow=arrow)
def createFromLine(line,color=mycolors.WHITE,width=1,arrow=[0.1,0.5]):
"""Create a vector from a line."""
angle=line.angle
x,y=Vector.cartesian([1,angle])
return Vector(x,y,color=color,width=width,arrow=arrow)
def polar(position):
"""Return the polar position [norm,angle] using cartesian position [x,y]."""
return list(polar(complex(position[0],position[1])))
def cartesian(position):
"""Return the cartesian position [x,y] using polar position [norm,angle]."""
return [position[0]*cos(position[1]),position[0]*sin(position[1])]
def __init__(self,*args,color=mycolors.WHITE,width=1,arrow=[0.1,0.5]):
"""Create a vector."""
if len(args)==1: args=args[0]
self.components=list(args)
self.color=color
self.width=width
self.arrow=arrow
def setNull(self):
"""Set the components of the vector to zero."""
self.components=[0 for i in range(len(self.components))]
#X component
def setX(self,value):
"""Set the x component."""
self.components[0]=value
def getX(self):
"""Return the x component."""
return self.components[0]
def delX(self):
"""Delete the x component and so shifting to a new one."""
del self.components[0]
#Y component
def setY(self,value):
"""Set the y component."""
self.components[1]=value
def getY(self):
"""Return the y component."""
return self.components[1]
def delY(self):
"""Delete the y component."""
del self.components[1]
#Angle
def getAngle(self):
"""Return the angle of a vector with the [1,0] direction in cartesian coordonnates."""
return Vector.polar(self.components)[1]
def setAngle(self,value):
"""Change the angle of the points without changing its norm."""
n,a=Vector.polar(self.components)
self.components=Vector.cartesian([n,value])
def delAngle(self):
"""Set to zero the angle of the vector."""
self.setAngle(0)
#Norm
def getNorm(self):
"""Return the angle of a vector with the [1,0] direction in cartesian coordonnates."""
return Vector.polar(self.components)[0]
def setNorm(self,value):
"""Change the angle of the points without changing its norm."""
n,a=Vector.polar(self.components)
self.components=Vector.cartesian([value,a])
#Position
def getPosition(self):
"""Return the components."""
return self.components
def setPosition(self,position):
"""Set the components."""
self.components=position
def delPosition(self):
"""Set the vector to the null vector."""
self.components=[0 for i in range(len(self.components))]
x=property(getX,setX,delX,doc="Allow the user to manipulate the x component easily.")
y=property(getY,setY,delY,doc="Allow the user to manipulate the y component easily.")
norm=property(getNorm,setNorm,doc="Allow the user to manipulate the norm of the vector easily.")
angle=property(getAngle,setAngle,doc="Allow the user to manipulate the angle of the vector easily.")
position=property(getPosition,setPosition,doc="Same as components.")
def show(self,context,p=Point.neutral(),color=None,width=None):
"""Show the vector."""
if not color: color=self.color
if not width: width=self.width
q=self(p)
v=-self*self.arrow[0] #wtf
v1=v%self.arrow[1]
v2=v%-self.arrow[1]
a=v1(q)
b=v2(q)
context.draw.line(context.screen,color,p.components,q.components,width)
context.draw.line(context.screen,color,q.components,a.components,width)
context.draw.line(context.screen,color,q.components,b.components,width)
def showFromTuple(self,context,t=(0,0),**kwargs):
"""Show a vector from a tuple."""
p=Point(*t)
self.show(context,p,**kwargs)
def showText(self,surface,point,text,color=None,size=20):
"""Show the text next to the vector."""
if not color: color=self.color
v=self/2
point=v(point)
surface.print(text,tuple(point),color=color,size=size)
def __len__(self):
"""Return the number of components."""
return len(self.components)
def __iter__(self):
"""Iterate the points of the form."""
self.iterator=0
return self
def __next__(self):
"""Return the next point threw an iteration."""
if self.iterator<len(self.components):
self.iterator+=1
return self.components[self.iterator-1]
else:
raise StopIteration
def __neg__(self):
"""Return the negative vector."""
return Vector([-c for c in self.components])
def colinear(self,other,e=10e-10):
"""Return if two vectors are colinear."""
return abs(self.x*other.y-self.y*other.x)<e
__floordiv__=colinear
def scalar(self,other):
"""Return the scalar product between two vectors."""
return self.x*other.x+self.y*other.y
def cross(self,other):
"""Determine if a vector crosses another using dot product."""
return self.scalar(other)==0
def __mul__(self,factor):
"""Multiply a vector by a given factor."""
if type(factor)==int or type(factor)==float:
return Vector([c*factor for c in self.components])
else:
raise NotImplementedError
raise Exception("Type "+str(type(factor))+" is not valid. Expected float or int types.")
__imul__=__rmul__=__mul__ #Allow front extern multiplication using back extern multiplication with scalars
def __truediv__(self,factor):
"""Multiply a vector by a given factor."""
if type(factor)==Vector:
raise NotImplementedError
else:
return Vector([c/factor for c in self.components])
def __add__(self,other):
"""Add two vector together."""
return Vector([c1+c2 for (c1,c2) in zip(self.components,other.components)])
def __sub__(self,other):
"""Sub two vector together."""
return Vector([c1-c2 for (c1,c2) in zip(self.components,other.components)])
__iadd__=__radd__=__add__
__isub__=__rsub__=__sub__
def rotate(self,angle):
"""Rotate a vector using the angle of rotation."""
n,a=Vector.polar([self.x,self.y])
a+=angle
self.x=n*cos(a)
self.y=n*sin(a)
def __mod__(self,angle):
"""Return the rotated vector using the angle of rotation."""
n,a=Vector.polar([self.x,self.y])
a+=angle
return Vector(n*cos(a),n*sin(a),color=self.color,width=self.width,arrow=self.arrow)
__imod__=__mod__
def __getitem__(self,index):
"""Return x or y value using given index."""
return self.position[index]
def __setitem__(self,index,value):
"""Change x or y value using given index and value."""
self.position[index]=value
def __call__(self,*points):
"""Return points by applying the vector on those."""
if points!=():
if type(points[0])==list:
points=points[0]
if len(points)==0:
raise Exception("A vector can only be applied to a point of a list of points.")
elif len(points)==1:
return points[0]+self
else:
return [point+self for point in points]
def applyToPoint(self,point):
"""Return the point after applying the vector to it."""
return self+point
def applyToPoints(self,points):
"""Return the points after applying the vector to those."""
return [point+self for point in points]
def __xor__(self,other):
"""Return the angle between two vectors."""
return self.angle-other.angle
def __invert__(self):
"""Return the unit vector."""
a=self.angle
x,y=Vector.cartesian([1,a])
return Vector(x,y)
def __str__(self):
"""Return a string description of the vector."""
return "v("+",".join([str(round(c,digits)) for c in self.components])+")"
def __tuple__(self):
"""Return the components in tuple form."""
return tuple(self.components)
def __list__(self):
"""Return the components."""
return self.components
class Segment(Direction):
def null():
"""Return the segment whoose points are both the origin."""
return Segment([Point.origin() for i in range(2)])
def random(corners=[-1,-1,1,1],width=1,color=mycolors.WHITE):
"""Create a random segment."""
p1=Point.random(corners)
p2=Point.random(corners)
return Segment([p1,p2],width=width,color=color)
def __init__(self,*points,width=1,color=mycolors.WHITE):
"""Create the segment using 2 points, width and color."""
if points!=(): #Extracting the points arguments under the same list format
if type(points[0])==list:
points=points[0]
if len(points)==1: points=points[0]
if len(points)!=2: raise Exception("A segment must have 2 points.")
self.points=list(points)
self.width=width
self.color=color
def __str__(self):
"""Return the string representation of a segment."""
return "s("+str(self.p1)+","+str(self.p2)+")"
def __call__(self,t=1/2):
"""Return the point C of the segment so that Segment(p1,C)=t*Segment(p1,p2)."""
return (t*self.vector)(self.p1)
def sample(self,n,include=True):
"""Sample n points of the segment.
It is also possible to include the last point if wanted."""
return [self(t/n) for t in range(n+int(include))]
__rmul__=__imul__=__mul__=lambda self,t: Segment(self.p1,self(t))
def getCenter(self):
"""Return the center of the segment in the general case."""
return Point(*[(self.p1[i]+self.p2[i])/2 for i in range(min(len(self.p1.components),len(self.p2.components)))])
def setCenter(self,np):
"""Set the center of the segment."""
p=self.getCenter()
v=Vector.createFromTwoPoints(p,np)
print("v",v)
for i in range(len(self.points)):
self.points[i]=v(self.points[i])
def getAngle(self):
"""Return the angle of the segment."""
return self.vector.angle
def setAngle(self):
"""Set the angle of the segment."""
self.vector.angle=angle
def show(self,window,color=None,width=None):
"""Show the segment using window."""
if not color: color=self.color
if not width: width=self.width
window.draw.line(window.screen,color,[self.p1.x,self.p1.y],[self.p2.x,self.p2.y],width)
#self.showInBorders(window,color,width)
def showInBorders(self,window,color=None,width=None):
"""Show the segment within the boundaries of the window."""
#It it really slow and it doesn't work as expected.
xmin,ymin,xmax,ymax=window.getCorners()
p=[Point(xmin,ymin),Point(xmax,ymin),Point(xmax,ymax),Point(xmin,ymax)]
f=Form(p)
if (self.p1 in f) and (self.p2 in f):
window.draw.line(window.screen,color,[self.p1.x,self.p1.y],[self.p2.x,self.p2.y],width)
elif (self.p1 in f) and not (self.p2 in f):
v=Vector.createFromTwoPoints(self.p1,self.p2)
hl=HalfLine(self.p1,v.angle)
p=f.crossHalfLine(hl)
if p:
print(len(p))
p=p[0]
window.draw.line(window.screen,color,[self.p1.x,self.p1.y],[p.x,p.y],width)
elif not (self.p1 in f) and (self.p2 in f):
v=Vector.createFromTwoPoints(self.p2,self.p1)
hl=HalfLine(self.p2,v.angle)
p=f.crossHalfLine(hl)
if p:
print(len(p))
p=p[0]
window.draw.line(window.screen,color,[p.x,p.y],[self.p2.x,self.p2.y],width)
else:
ps=f.crossSegment(self)
if len(ps)==2:
p1,p2=ps
window.draw.line(window.screen,color,[p1.x,p1.y],[p2.x,p2.y],width)
def __contains__(self,point,e=10e-10):
"""Determine if a point is in a segment."""
if point==self.getP1(): return True
v1=Vector.createFromTwoPoints(self.p1,point)
v2=self.getVector()
return (abs(v1.angle-v2.angle)%(2*math.pi)<e) and (v1.norm<=v2.norm)
def __len__(self):
"""Return the number of points."""
return len(self.points)
def __iter__(self):
"""Iterate the points of the form."""
self.iterator=0
return self
def __next__(self):
"""Return the next point through an iteration."""
if self.iterator<len(self.points):
if self.iterator==0: value=self.p1
if self.iterator==1: value=self.p2
self.iterator+=1
return value
else:
raise StopIteration
def __getitem__(self,index):
"""Return the point corresponding to the index given."""
return [self.points][index]
def __setitem__(self,index,value):
"""Change the value the point corresponding value and index given."""
self.points[index]=value
def getLine(self,correct=True):
"""Return the line through the end points of the segment."""
return Line(self.p1,self.angle,self.width,self.color,correct=correct)
def getVector(self):
"""Return the vector that goes from p1 to p2."""
return Vector.createFromTwoPoints(self.p1,self.p2)
def setVector(self,vector):
"""Set the vector that goes from p1 to p2."""
self.p2=vector(self.p1)
def getLength(self):
"""Return the length of the segment."""
return self.vector.norm
def setLength(self,length):
"""Set the length of the segment."""
self.vector.norm=length
def rotate(self,angle,point=None):
"""Rotate the segment using an angle and an optional point of rotation."""
if not point: point=self.middle
self.p1.rotate(angle,point)
self.p2.rotate(angle,point)
def __or__(self,other):
"""Return bool for (2 segments are crossing)."""
if isinstance(other,Segment): return self.crossSegment(other)
if isinstance(other,Line): return self.crossLine(other)
if isinstance(other,HalfLine): return other.crossSegment(self)
if isinstance(other,Form): return form.crossSegment(self)
def getXmin(self):
"""Return the minimum of x components of the 2 end points."""
return min(self.p1.x,self.p2.x)
def getYmin(self):
"""Return the minimum of y components of the 2 ends points."""
return min(self.p1.y,self.p2.y)
def getXmax(self):
"""Return the maximum of x components of the 2 end points."""
return max(self.p1.x,self.p2.x)
def getYmax(self):
"""Returnt the maximum of y components of the 2 end points."""
return max(self.p1.y,self.p2.y)
def getMinima(self):
"""Return the minima of x and y components of the 2 end points."""
xmin=self.getXmin()
ymin=self.getYmin()
return (xmin,ymin)
def getMaxima(self):
"""Return the maxima of x and y components of the 2 end points."""
xmax=self.getXmax()
ymax=self.getYmax()
return (xmax,ymax)
def getCorners(self):
"""Return the minimum and maximum of x and y components of the 2 end points."""
minima=self.getMinima()
maxima=self.getMaxima()
return minima+maxima
def parallel(self,other):
"""Determine if the line is parallel to another object (line or segment)."""
return (other.angle==self.angle)
def crossSegment(self,other,e=10**-14):
"""Return the intersection point of the segment with another segment."""
sl=self.getLine()
ol=other.getLine()
point=sl.crossLine(ol)
if point:
if point in self and point in other:
return point
def crossLine(self,other):
"""Return the intersection point of the segment with a line."""
if self.parallel(other): return None
line=self.getLine()
point=other.crossLine(line)
if point is not None:
if point in self and point in other:
return point
def getP1(self):
"""Return the first point of the segment."""
return self.points[0]
def setP1(self,p1):
"""Set the first point of the segment."""
self.points[0]=p1
def getP2(self):
"""Return the second point of the segment."""
return self.points[1]
def setP2(self,p2):
"""Set the second point of the segment."""
self.points[1]=p2
p1=property(getP1,setP1,"Allow the user to manipulate the first point of the segment easily.")
p2=property(getP2,setP2,"Allow the user to manipulate the second point of the segment easily.")
middle=center=property(getCenter,setCenter,"Representation of the center of the segment.")
vector=property(getVector,setVector,"Representation of the vector of the segment.")
angle=property(getAngle,setAngle,"Representation of the angle of the segment.")
length=property(getLength,setLength,"Representation of the length of the segment.")
class Line(Direction):
def random(min=-1,max=1,width=1,color=mycolors.WHITE):
"""Return a random line."""
point=Point.random(min,max)
angle=random.uniform(min,max)
return Line(point,angle,width,color)
def createFromPointAndVector(point,vector,width=1,color=mycolors.WHITE):
"""Create a line using a point and a vector with optional features."""
return Line(point,vector.angle,width=1,color=color)
def createFromTwoPoints(point1,point2,width=1,color=mycolors.WHITE):
"""Create a line using two points with optional features."""
vector=Vector.createFromTwoPoints(point1,point2)
return Line(point1,vector.angle,width=1,color=color)
def __init__(self,point,angle,width=1,color=mycolors.WHITE,correct=True):
"""Create the line using a point and a vector with optional width and color.
Caracterizes the line with a unique system of components [neighbour point, angle].
The neighbour point is the nearest point to (0,0) that belongs to the line.
The angle is the orientated angle between the line itself and another line parallel
to the x-axis and crossing the neighbour point. Its range is [-pi/2,pi/2[ which makes it unique."""
self.point=point
self.angle=angle
self.width=width
self.color=color
if correct: self.correct()
def __eq__(self,l):
"""Determine if two lines are the same."""
return l.point==self.point and l.angle==self.angle
def correctAngle(self):
"""Correct angle which is between [-pi/2,pi/2[."""
self.angle=(self.angle+math.pi/2)%math.pi-math.pi/2
def correctPoint(self,d=2):
"""Correct the point to the definition of the neighbour point."""
self.point=self.projectPoint(Point.origin(d))
def correct(self):
"""Correct the line."""
self.correctAngle()
self.correctPoint()
def getCompleteCartesianCoordonnates(self):
"""Return a,b,c according to the cartesian equation of the line: ax+by+c=0."""
"""Because there are multiple values of a,b,c for a single line, the simplest combinaision is returned."""
v=self.vector
p1=self.point
p2=v(self.point)
if v.x==0:
a=1
b=0
c=-p1.x
else:
a=-(p1.y-p2.y)/(p1.x-p2.x)
b=1
c=-(a*p1.x+b*p1.y)
return (a,b,c)
def getReducedCartesianCoordonnates(self):
"""Return a,b according to the reduced cartesian equation of the line: y=ax+b."""
return (self.slope,self.ordinate)
def getAngle(self):
"""Return the angle of the line."""
return self.angle
def setAngle(self,angle):
"""Set the angle of the line."""
self.angle=angle
self.correctAngle()
def delAngle(self):
"""Set the angle of the line to zero."""
self.angle=0
#angle=property(getAngle,setAngle,delAngle,"Representation of the angle of the line after correction.")
def rotate(self,angle,point=Point(0,0)):
"""Rotate the line.""" #Incomplete
self.angle+=angle
self.correctAngle()
def getPoint(self):
"""Return the neighbour point."""
return self.point
def setPoint(self,point):
"""Set the neighbour point to another one."""
self.point=point
self.correctPoint()
def delPoint(self):
"""Set the neighbour point to the origin."""
self.point=Point.origin()
#point=property(getPoint,setPoint,delPoint,"Representation of the neighbour point of the line after correction.")
def getUnitVector(self):
"""Return the unit vector of the line."""
return Vector.createFromPolarCoordonnates(1,self.angle)
def setUnitVector(self,vector):
"""Set the unit vector of the line."""
self.angle=vector.angle
def getNormalVector(self):
"""Return the normal vector of the line."""
vector=self.getUnitVector()
vector.rotate(math.pi/2)
return vector
def setNormalVector(self,vector):
"""Set the normal vector of the line."""
self.angle=vector.angle+math.pi/2
def getSlope(self):
"""Return the slope of the line."""
return math.tan(angle)
def setSlope(self,slope):
"""Set the slope of the line by changing its angle and point."""
self.angle=math.atan(slope)
def getOrdinate(self):
"""Return the ordinate of the line."""
return self.point.y-self.slope*self.point.x
def setOrdinate(self,ordinate):
"""Set the ordinate of the line by changing its position."""
self.slope
self.angle
self.point
def getFunction(self):
"""Return the affine function that correspond to the line."""
return lambda x:self.slope*x+self.ordinate
def setFunction(self,function):
"""Set the function of the line by changing its slope and ordinate."""
self.ordinate=function(0)
self.slope=function(1)-function(0)
def getReciproqueFunction(self):
"""Return the reciproque of the affine function that correspond to the line."""
return lambda y:(y-self.ordinate)/self.slope
def evaluate(self,x):
"""Evaluate the line as a affine function."""
return self.function(x)
def devaluate(self,y):
"""Evaluate the reciproque function of the affine funtion of the line."""
return self.getReciproqueFunction(y)
def __or__(self,other):
"""Return the point of intersection between the line and another object."""
if isinstance(other,Line): return self.crossLine(other)
if isinstance(other,Segment): return self.crossSegment(other)
if isinstance(other,HalfLine): return other.crossLine(self)
if isinstance(other,Form): return other.crossLine(self)
def crossSegment(self,other,e=10**-13):
"""Return the point of intersection between a segment and the line."""
#Extract the slopes and ordinates
line=other.getLine()
point=self.crossLine(line)
if not point: return None
x,y=point
#Determine if the point of intersection belongs to both the segment and the line
xmin,ymin,xmax,ymax=other.getCorners()
#If it is the case return the point
if xmin-e<=x<=xmax+e and ymin-e<=y<=ymax+e:
return Point(x,y,color=self.color)
#By default if nothing is returned the function returns None
def crossLine(self,other):
"""Return the point of intersection between two lines with vectors calculation."""
a,b=self.point
c,d=other.point
m,n=self.vector
o,p=other.vector
if n*o==m*p: return None #The lines are parallels
x=(a*n*o-b*m*o-c*m*p+d*m*o)/(n*o-m*p)
y=(x-a)*n/m+b
return Point(x,y)
def parallel(self,other):
"""Determine if the line is parallel to another object (line or segment)."""
return other.angle==self.angle
def __contains__(self,point,e=10e-10):
"""Determine if a point belongs to the line."""
v1=self.vector
v2=Vector.createFromTwoPoints(self.point,point)
return v1.colinear(v2,e)
def getHeight(self,point):
"""Return the height line between the line and a point."""
return Line(point,self.normal_vector.angle)
def distanceFromPoint(self,point):
"""Return the distance between a point and the line."""
return Vector.createFromTwoPoints(point,self.crossLine(self.getHeight(point))).norm
def projectPoint(self,point):
"""Return the projection of the point on the line."""
vector=self.getNormalVector()
angle=vector.angle
line=Line(point,angle,correct=False)
projection=self.crossLine(line)
return projection
def projectSegment(self,segment):
"""Return the projection of a segment on the line."""
p1,p2=segment
p1=self.projectPoint(p1)
p2=self.projectPoint(p2)
return Segment(p1,p2,segment.width,segment.color)
def getSegmentWithinXRange(self,xmin,xmax):
"""Return the segment made of the points of the line which x component is
between xmin and xmax."""
yxmin=self.evaluate(xmin)
yxmax=self.evaluate(xmax)
p1=Point(xmin,yxmin)
p2=Point(xmax,yxmax)
return Segment(p1,p2)
def getSegmentWithinYRange(self,ymin,ymax):
"""Return the segment made of the points of the line which y component is
between ymin and ymax."""
xymin=self.devaluate(ymin)
xymax=self.devaluate(ymax)
p1=Point(xymin,ymin)
p2=Point(xymax,ymax)
return Segment(p1,p2,width=self.width,color=self.color)
def oldgetSegmentWithinCorners(self,corners):
"""Return the segment made of the poins of the line which are in the area
delimited by the corners."""
xmin,ymin,xmax,ymax=corners
yxmin=self.evaluate(xmin)
yxmax=self.evaluate(xmax)
xymin=self.devaluate(ymin)
xymax=self.devaluate(ymax)
nxmin=max(xmin,xymin)
nymin=max(ymin,yxmin)
nxmax=min(xmax,xymax)
nymax=min(ymax,yxmax)
p1=Point(nxmin,nymin)
p2=Point(nxmax,nymax)
return Segment(p1,p2,width=self.width,color=self.color)
def getSegmentWithinCorners(self,corners):
"""Return the segment made of the poins of the line which are in the area
delimited by the corners."""
xmin,ymin,xmax,ymax=corners
p1=Point(xmin,ymin)
p2=Point(xmax,ymin)
p3=Point(xmax,ymax)
p4=Point(xmin,ymax)
s1=Segment(p1,p2)
s2=Segment(p2,p3)
s3=Segment(p3,p4)
s4=Segment(p4,p1)
segments=[s1,s2,s3,s4]
points=[]
for segment in segments:
cross=self.crossSegment(segment)
if cross:
points.append(cross)
if len(points)==2:
return Segment(*points)
def getPointsWithinCorners(self,corners):
"""Return the segment made of the poins of the line which are in the area
delimited by the corners."""
xmin,ymin,xmax,ymax=corners
p1=Point(xmin,ymin)
p2=Point(xmax,ymin)
p3=Point(xmax,ymax)
p4=Point(xmin,ymax)
v1=Vector(p1,p2)
v2=Vector(p2,p3)
v3=Vector(p3,p4)
v4=Vector(p4,p1)
l1=Line.createFromPointAndVector(p1,v1)
l2=Line.createFromPointAndVector(p2,v2)
l3=Line.createFromPointAndVector(p3,v3)
l4=Line.createFromPointAndVector(p4,v4)
lines=[l1,l3]
points=[]
for line in lines:
cross=self.crossLine(line)
if cross:
points.append(cross)
if not points:
lines=[l2,l4]
for line in lines:
cross=self.crossLine(line)
if cross:
points.append(cross)
return points
def show(self,surface,width=None,color=None):
"""Show the line on the surface."""
if not color: color=self.color
if not width: width=self.width
corners=surface.getCorners()
segment=self.getSegmentWithinCorners(corners)
if segment:
p1,p2=segment
segment.show(surface,width=width,color=color)
vector=unit_vector=property(getUnitVector,setUnitVector,"Allow the client to manipulate the unit vector easily.")
normal_vector=property(getNormalVector,setNormalVector,"Allow the client to manipulate the normal vector easily.")
slope=property(getSlope,setSlope,"Allow the client to manipulate the slope of the line easily.")
ordinate=property(getOrdinate,setOrdinate,"Allow the client to manipulate the ordinate of the line easily.")
function=property(getFunction,setFunction,"Allow the client to manipulate the function of the line.")
#reciproque_function=property(getReciproqueFunction,setReciproqueFunction,"Allow the user to manipulate easily the reciproque function.")
class HalfLine(Line):
def createFromLine(line):
"""Create a half line."""
return HalfLine(line.point,line.angle)
def __init__(self,point,angle,color=mycolors.WHITE,width=1):
"""Create a half line."""
super().__init__(point,angle,color=color,width=width,correct=False)
def getLine(self,correct=True):
"""Return the line that correspond to the half line."""
return Line(self.point,self.angle,correct=correct)
def getPoint(self):
"""Return the point of the half line."""
return self.point
def setPoint(self,point):
"""Set the point of the half line."""
self.point=point
def show(self,surface,width=None,color=None):
"""Show the line on the surface."""
if not color: color=self.color
if not width: width=self.width
xmin,ymin,xmax,ymax=surface.getCorners()
points=[Point(xmin,ymin),Point(xmax,ymin),Point(xmax,ymax),Point(xmin,ymax)]
form=Form(points)
points=form.crossHalfLine(self)
points+=[self.point]*(2-len(points))
if len(points)>0:
surface.draw.line(surface.screen,color,points[0],points[1],width)
def __contains__(self,point,e=10e-10):
"""Determine if a point is in the half line."""
v1=self.vector
v2=Vector.createFromTwoPoints(self.point,point)
return abs(v1.angle-v2.angle)<e
def __or__(self,other):
"""Return the intersection point between the half line and another object."""
if isinstance(other,Line): return self.crossLine(other)
if isinstance(other,Segment): return self.crossSegment(other)
if isinstance(other,HalfLine): return self.crossHalfLine(other)
if isinstance(other,Form): return form.crossHalfLine(self)
def crossHalfLine(self,other):
"""Return the point of intersection of the half line with another."""
ml=self.getLine(correct=False)
ol=other.getLine(correct=False)
point=ml.crossLine(ol)
if point:
if (point in self) and (point in other):
return point
def crossLine(self,other):
"""Return the point of intersection of the half line with a line."""
ml=self.getLine(correct=False)
point=ml.crossLine(other)
if point:
if (point in self) and (point in other):
return point
def crossSegment(self,other):
"""Return the point of intersection of the half line with a segment."""
ml=self.getLine(correct=False)
ol=other.getLine(correct=False)
point=ml.crossLine(ol)
if point:
if (point in self) and (point in other):
return point
def __str__(self):
"""Return the string representation of a half line."""
return "hl("+str(self.point)+","+str(self.angle)+")"
class Form:
def random(corners=[-1,-1,1,1],n=random.randint(1,10),**kwargs):
"""Create a random form using the point_number, the minimum and maximum position for x and y components and optional arguments."""
points=[Point.random(corners) for i in range(n)]
form=Form(points,**kwargs)
form.makeSparse()
return form
def anyCrossing(forms):
"""Determine if any of the forms are crossing."""
if len(forms)==1:forms=forms[0]
l=len(forms)
for i in range(l):
for j in range(i+1,l):
if forms[i].crossForm(forms[j]):
return True
return False
def allCrossing(forms):
"""Determine if all the forms are crossing."""
if len(forms)==1:forms=forms[0]
l=len(forms)
for i in range(l):
for j in range(i+1,l):
if not forms[i].crossForm(forms[j]):
return False
return True
def cross(*forms):
"""Return the points of intersection between the crossing forms."""
if len(forms)==1:forms=forms[0]
l=len(forms)
points=[]
for i in range(l):
for j in range(i+1,l):
points.extend(forms[i].crossForm(forms[j]))
return points
def intersectionTwoForms(form1,form2):
"""Return the form which is the intersection of two forms."""
if form1==None: return form2
if form2==None: return form1
if form1==form2==None: return None
points=form1.crossForm(form2)
if not points: return None
for point in form1.points:
if point in form2:
points.append(point)
for point in form2.points:
if point in form1:
points.append(point)
form=Form(points)
form.makeSparse()
return form
def intersection(forms):
"""Return the form which is the intersection of all the forms."""
result=forms[0]
for form in forms[1:]:
result=Form.intersectionTwoForms(result,form)
return result
def unionTwoForms(form1,form2):
"""Return the union of two forms."""
intersection_points=set(form1.crossForm(form2))
if intersection_points:
all_points=set(form1.points+form2.points)
points=all_points.intersection(intersection_points)
return [Form(points)]
else:
return [form1,form2]
def union(forms):
"""Return the union of all forms."""
"""This function must be recursive."""
if len(forms)==2:
return Form.unionTwoForms(forms[0],forms[1])
else:
pass
result=forms[0]
for form in forms[1:]:
result.extend(Form.union(form,result))
return result
def __init__(self,points,fill=False,point_mode=0,point_size=[0.01,0.01],point_radius=0.01,point_width=1,point_fill=False,side_width=1,color=None,point_color=mycolors.WHITE,side_color=mycolors.WHITE,area_color=mycolors.WHITE,cross_point_color=mycolors.WHITE,cross_point_radius=0.01,cross_point_mode=0,cross_point_width=1,cross_point_size=[0.1,0.1],point_show=True,side_show=True,area_show=False):
"""Create the form object using points."""
self.points=points
self.point_mode=point_mode
self.point_size=point_size
self.point_width=point_width
self.point_radius=point_radius
self.point_color=point_color or color
self.point_show=point_show
self.point_fill=point_fill
self.side_width=side_width
self.side_color=side_color or color
self.side_show=side_show
self.area_color=area_color or color
self.area_show=area_show or fill
self.cross_point_color=cross_point_color
self.cross_point_radius=cross_point_radius
self.cross_point_mode=cross_point_mode
self.cross_point_width=cross_point_width
self.cross_point_size=cross_point_size
def __str__(self):
"""Return the string representation of the form."""
return "f("+",".join([str(p) for p in self.points])+")"
def setFill(self,fill):
"""Set the form to fill its area when shown."""
self.area_show=fill
def getFill(self):
"""Return if the area is filled."""
return self.area_show
fill=property(getFill,setFill,doc="Allow the user to manipulate easily if the area is filled.")
def __iadd__(self,point):
"""Add a point to the form."""
self.points.append(point)
return self
def __isub__(self,point):
"""Remove a point to the form."""
self.points.remove(point)
return self
def __mul__(self,n):
"""Return a bigger form."""
vectors=[n*Vector(*(p-self.center)) for p in self.points]
return Form([vectors[i](self.points[i]) for i in range(len(self.points))])
def __imul__(self,n):
"""Return a bigger form."""
vectors=[n*Vector(*(p-self.center)) for p in self.points]
self.points=[vectors[i](self.points[i]) for i in range(len(self.points))]
return self
__rmul__=__mul__
def __iter__(self):
"""Iterate the points of the form."""
self.iterator=0
return self
def __next__(self):
"""Return the next point threw an iteration."""
if self.iterator < len(self.points):
iterator=self.iterator
self.iterator+=1
return self.points[iterator]
else:
raise StopIteration
def __eq__(self,other):
"""Determine if 2 forms are the same which check the equalities of their components."""
return sorted(self.points)==sorted(other.points)
def getCenter(self):
"""Return the point of the center."""
mx=mean([p.x for p in self.points])
my=mean([p.y for p in self.points])
return Point(mx,my,color=self.point_color,radius=self.point_radius)
def setCenter(self,center):
"""Set the center of the form."""
p=center-self.getCenter()
for point in self.points:
point+=p
def getSegments(self):
""""Return the list of the form sides."""
l=len(self.points)
return [Segment(self.points[i%l],self.points[(i+1)%l],color=self.side_color,width=self.side_width) for i in range(l)]
def setSegments(self,segments):
"""Set the segments of the form by setting its points to new values."""
self.points=[s.p1 for s in segments][:-1]
def showAll(self,surface,**kwargs):
"""Show the form using a window."""
#,window,point_color=None,side_color=None,area_color=None,side_width=None,point_radius=None,color=None,fill=None,point_show=None,side_show=None
if not "point_show" in kwargs: kwargs["point_show"]=self.point_show
if not "side_show" in kwargs: kwargs["side_show"]=self.side_show
if not "area_show" in kwargs: kwargs["area_show"]=self.area_show
if kwargs["area_show"]: self.showAllArea(surface,**kwargs)
if kwargs["side_show"]: self.showAllSegments(surface,**kwargs)
if kwargs["point_show"]: self.showAllPoints(surface,**kwargs)
def showFast(self,surface,point=None,segment=None,area=None):
"""Show the form using the surface and optional objects to show."""
if point: self.showPoints(surface)
if segment: self.showSegments(surface)
if area: self.showArea(surface)
def show(self,surface):
"""Show the form using the surface and optional objects to show."""
if self.area_show: self.showArea(surface)
if self.side_show: self.showSegments(surface)
if self.point_show: self.showPoints(surface)
def showFastArea(self,surface,color=None):
"""Show the area of the form using optional parameters such as the area
of the color."""
if not color: color=self.area_color
ps=[tuple(p) for p in self.points]
if len(ps)>1: surface.draw.polygon(surface.screen,color,ps,False)
def showAllArea(self,surface,**kwargs):
"""Show the area of the form using optional parameters such as the area
of the color. This function is slower than the previous one because it
checks if the dictionary or attributes contains the area_color."""
if not "area_color" in kwargs: kwargs["area_color"]=self.area_color
ps=[tuple(p) for p in self.points]
if len(ps)>1: surface.draw.polygon(surface.screen,kwargs["area_color"],ps,False)
def showArea(self,surface):
"""Show the area of the form."""
ps=[tuple(p) for p in self.points]
if len(ps)>1: surface.draw.polygon(surface.screen,self.area_color,ps,False)
def showPoints(self,surface):
"""Show the points."""
for point in self.points:
point.show(surface)
def showFastPoints(self,surface,
color=None,
mode=None,
radius=None,
size=None,
width=None,
fill=None):
"""Show the points of the form using optional parameters."""
if not color: color=self.point_color
if not radius: radius=self.point_radius
if not mode: mode=self.point_mode
if not size: size=self.point_size
if not width: width=self.point_width
if not fill: fill=self.point_fill
for point in self.points:
point.show(surface,color,mode,fill,radius,size,width)
def showAllPoints(self,surface,**kwargs):
"""Show the points of the form using optional parameters.
This method is slower than the previous one because it checks if the
dictionary of attributes contains the arguments."""
if not "point_color" in kwargs: kwargs["point_color"]= self.point_color
if not "point_radius" in kwargs: kwargs["point_radius"]= self.point_radius
if not "point_mode" in kwargs: kwargs["point_mode"]= self.point_mode
if not "point_size" in kwargs: kwargs["point_size"]= self.point_size
if not "point_width" in kwargs: kwargs["point_width"]= self.point_width
if not "point_fill" in kwargs: kwargs["point_fill"]= self.point_fill
for point in self.points:
point.show(surface,
color=kwargs["point_color"],
mode=kwargs["point_mode"],
fill=kwargs["point_fill"],
radius=kwargs["point_radius"],
size=kwargs["point_size"],
width=kwargs["point_width"])
@timer
def showFastSegments(self,surface,color=None,width=None):
"""Show the segments of the form."""
if not color: color=self.segment_color
if not width: width=self.segment_width
for segment in self.segments:
segment.show(surace,color,width)
def showSegments(self,surface):
"""Show the segments without its parameters."""
for segment in self.segments:
segment.show(surface)
def showAllSegments(self,surface,**kwargs):
"""Show the segments of the form."""
if not "side_color" in kwargs: kwargs["side_color"]=self.side_color
if not "side_width" in kwargs: kwargs["side_width"]=self.side_width
for segment in self.segments:
segment.show(surface,color=kwargs["side_color"],width=kwargs["side_width"])
def showFastCrossPoints(self,surface,color=None,mode=None,radius=None,width=None,size=None):
"""Show the intersection points of the form crossing itself."""
points=self.crossSelf()
if not color: color=self.cross_point_color
if not mode: mode=self.cross_point_mode
if not radius: radius=self.cross_point_radius
if not width: width=self.cross_point_width
if not size: size=self.cross_point_size
for point in points:
point.show(surface,color=color,mode=mode,radius=radius,width=width,size=size)
def showCrossPoints(self,surface):
"""Show the intersection points of the form crossing itself."""
for point in self.cross_points:
point.show(surface)
def __or__(self,other):
"""Return the points of intersections with the form and another object."""
if isinstance(other,HalfLine): return self.crossHalfLine(other)
if isinstance(other,Line): return self.crossLine(other)
if isinstance(other,Segment): return self.crossSegment(other)
if isinstance(other,Form): return self.crossForm(other)
def crossForm(self,other):
"""Return the bool: (2 sides are crossing)."""
points=[]
for myside in self.sides:
for otherside in other.sides:
point=myside.crossSegment(otherside)
if point: points.append(point)
return points
def crossDirection(self,other):
"""Return the list of the points of intersection between the form and a segment or a line."""
points=[]
for side in self.sides:
cross=side|other
if cross: points.append(cross)
return points
def crossHalfLine(self,other):
"""Return the list of points of intersection in order between the form and a half line."""
points=[]
for segment in self.segments:
cross=other.crossSegment(segment)
if cross: points.append(cross)
hp=other.point
objects=[(p,Point.distance(p,hp)) for p in points]
objects=sorted(objects,key=lambda x:x[1])
return [p for (p,v) in objects]
def crossLine(self,other):
"""Return the list of the points of intersection between the form and a line."""
points=[]
for segment in self.segments:
cross=segment.crossLine(other)
if cross: points.append(cross)
return points
def crossSegment(self,other):
"""Return the list of the points of intersection between the form and a segment."""
points=[]
for side in self.sides:
point=side.crossSegment(other)
if point:
points.append(point)
return points
def crossSelf(self,e=10e-10):
"""Return the list of the points of intersections between the form and itself."""
results=[]
l=len(self.segments)
for i in range(l):
for j in range(i+1,l):
point=self.segments[i].crossSegment(self.segments[j])
if point:
if point in self.points:
results.append(point)
return results
def convex(self):
"""Return the bool (the form is convex)."""
x,y=self.center
angles=[]
l=len(self.points)
for i in range(l-1):
A=self.points[(i+l-1)%l]
B=self.points[i%l]
C=self.points[(i+1)%l]
u=Vector.createFromTwoPoints(A,B)
v=Vector.createFromTwoPoints(C,B)
angle=v^u
if angle>pi:
return True
return False
def getSparse(self): #as opposed to makeSparse which keeps the same form and return nothing
"""Return the form with the most sparsed points."""
cx,cy=self.center
list1=[]
for point in self.points:
angle=Vector.createFromTwoPoints(point,self.center).angle
list1.append((angle,point))
list1=sorted(list1,key=lambda x:x[0])
points=[element[1] for element in list1]
return Form(points,fill=self.fill,side_width=self.side_width,point_radius=self.point_radius,point_color=self.point_color,side_color=self.side_color,area_color=self.area_color)
def makeSparse(self):
"""Change the form into the one with the most sparsed points."""
self.points=self.getSparse().points
def __contains__(self,point):
"""Return the boolean: (the point is in the form)."""
h=HalfLine(point,0)
ps=self.crossHalfLine(h)
return len(ps)%2==1
def rotate(self,angle,point=None):
"""Rotate the form by rotating its points from the center of rotation.
Use center of the shape as default center of rotation.""" #Actually not working
if not point: point=self.center
for i in range(len(self.points)):
self.points[i].rotate(angle,point)
def move(self,step):
"""Move the object by moving all its points using step."""
for point in self.points:
l=min(len(step),len(point.position))
for i in range(l):
point.position[i]=step[i]
def setPosition(self,position):
"""Move the object to an absolute position."""
self.center.position=position
def getPosition(self,position):
"""Return the position of the geometric center of the form."""
return self.center.position
def addPoint(self,point):
"""Add a point to the form."""
self.points.append(point)
def addPoints(self,points):
"""Add points to the form."""
self.points.extend(points)
__append__=addPoint
__extend__=addPoints
def removePoint(self,point):
"""Remove a point to the form."""
self.point.remove(point)
__remove__=removePoint
def update(self,keys):
"""Update the points."""
for point in self.points:
point.update(keys)
def __getitem__(self,index):
"""Return the point of index index."""
return self.points[index]
def __setitem__(self,index,value):
"""Change the points of a form."""
self.points[index]=value
def area(self):
"""Return the area of the form using its own points.
General case in 2d only for now..."""
l=len(self.points)
if l<3: #The form has no point, is a single point or a segment, so it has no area.
return 0
elif l==3: #The form is a triangle, so we can calculate its area.
a,b,c=[Vector.createFromSegment(segment) for segment in self.sides]
A=1/4*sqrt(4*a.norm**2*b.norm**2-(a.norm**2+b.norm**2-c.norm**2)**2)
return A
else: #The form has more points than 3, so we can cut it in triangles.
area=0
C=self.center
for i in range(l):
A=self.points[i]
B=self.points[(i+1)%l]
triangle=Form([A,B,C])
area+=Form.area(triangle)
return area
def __len__(self):
"""Return number of points."""
return len(self.points)
def __xor__(self,other):
"""Return the list of forms that are in the union of 2 forms."""
if type(other)==Form: other=[other]
return Form.union(other+[self])
def __and__(self,other):
"""Return the list of forms that are in the intersection of 2 forms."""
points=form.crossForm(other)
points+=[point for point in self.points if point in other]
points+=[point for point in other.points if point in self]
if points: return Form(points)
#Color
def setColor(self,color):
"""Color the whole form with a new color."""
self.point_color=color
self.side_color=color
self.area_color=color
def getColor(self):
"""Return the color of the segments because it is the more widely used."""
return self.side_color
def delColor(self):
"""Set the color of the form."""
self.side_color=mycolors.WHITE
self.point_color=mycolors.WHITE
self.area_color=mycolors.WHITE
def setPointColor(self,color):
"""Set the color of the points of the form."""
for point in self.points:
point.color=color
def setPointMode(self,mode):
"""Set the mode of the points."""
for point in self.points:
point.mode=mode
def setPointFill(self,fill):
"""Set the fill of the points."""
for point in self.points:
self.fill=fill
def setPointKey(self,key,value):
"""Set the value of the points with the key and the value."""
for point in self.points:
point.__dict__[key]=value
def setPointKeys(self,keys,values):
"""Set the values of the points with the keys and the values."""
l=min(len(keys),len(values))
for i in range(l):
for point in self.points:
point.__dict__[keys[i]]=values[i]
getCrossPoints=crossSelf
#points= property(getPoints,setPoints,"Represents the points.") #If I do this, the program will be very slow...
sides=segments= property(getSegments,setSegments,"Represents the segments.")
center=point= property(getCenter,setCenter,"Represents the center.")
color= property(getColor,setColor,delColor,"Represents the color.")
cross_points= property(getCrossPoints, "Represents the point of intersections of the segments.")
#cross_points= property(getCrossPoints,setCrossPoints,delCrossPoints, "Represents the point of intersections of the segments.")
#point_color= property(getPointColor,setPointColor,delPointColor,"Represents the color of the points.")
#point_mode= property(getPointMode,setPointMode,delPointMode,"Represents the mode of the points.")
#point_fill= property(getPointFill,setPointFill,delPointFill,"Represents the fill of the circle that represents the point.")
#point_radius= property(getPointRadius,setPointRadius,delPointRadius,"Represents the radius of the circle that represents the point.")
#point_size= property(getPointSize,setPointSize,delPointSize,"Represents the size of the cross that represents the point.")
#point_width= property(getPointWidth,setPointWidth,delPointWidth,"Represents the width of the cross that represents the point.")
#segment_color= property(getSegmentColor,setSegmentColor,delSegmentColor,"Represents the color of the segments.")
#segment_width= property(getSegmentWidth,setSegmentWith,delSegmentWidth,"Represents the width of the segments.")
class Circle:
def random(min=-1,max=1,fill=0,color=mycolors.WHITE,border_color=None,area_color=None,center_color=None,radius_color=None,radius_width=1,text_color=None,text_size=20):
"""Create a random circle."""
point=Point.random(min,max)
radius=1
return Circle.createFromPointAndRadius(point,radius,color,fill)
def createFromPointAndRadius(point,radius,**kwargs):
"""Create a circle from point."""
return Circle(*point,radius=radius,**kwargs)
def __init__(self,*args,radius,fill=False,color=mycolors.WHITE,border_color=None,area_color=None,center_color=None,radius_color=None,radius_width=1,text_color=None,text_size=20):
"""Create a circle object using x, y and radius and optional color and width."""
if len(args)==1: args=args[0]
self.position=args
self.radius=radius
self.fill=fill
if color:
if not border_color: border_color=color
if not area_color: area_color=color
if not radius_color: radius_color=color
if not text_color: text_color=color
self.border_color=border_color
self.area_color=area_color
self.center_color=center_color
self.radius_color=radius_color
self.radius_width=radius_width
self.text_color=text_color
self.text_size=text_size
def getX(self):
"""Return the x component of the circle."""
return self.position[0]
def setX(self,value):
"""Set the x component of the circle."""
self.position[0]=value
def getY(self):
"""Return the y component of the circle."""
return self.position[1]
def setY(self,value):
"""Set the y component of the circle."""
self.position[1]=value
def getPoint(self):
"""Return the point that correspond to the center of the circle."""
return Point(self.position)
def setPoint(self,point):
"""Set the center point of the circle by changing the position of the circle."""
self.position=point.position
x=property(getX,setX,"Allow the user to manipulate the x component easily.")
y=property(getY,setY,"Allow the user to manipulate the y component easily.")
center=point=property(getPoint,setPoint,"Allow the user to manipulate the point easily.")
def center(self):
"""Return the point that correspond to the center of the circle."""
return Point(self.position)
def show(self,window,color=None,border_color=None,area_color=None,fill=None):
"""Show the circle on screen using the window."""
if color:
if not area_color: area_color=color
if not border_color: border_color=color
if not border_color: border_color=self.border_color
if not area_color: area_color=self.area_color
if not fill: fill=self.fill
if fill: window.draw.circle(window.screen,area_color,[self.x,self.y],self.radius,True)
window.draw.circle(window.screen,border_color,[self.x,self.y],self.radius)
def showCenter(self,window,color=None,mode=None):
"""Show the center of the screen."""
if not color: color=self.center_color
if not mode: mode=self.center_mode
self.center.show(window,mode=mode,color=color)
def showText(self,window,text,color=None,size=None):
"""Show a text next to the circle."""
if not color: color=self.text_color
if not size: size=self.text_size
self.center.showText(window,text,color=color,size=size)
def showRadius(self,window,color=None,width=None):
"""Show the radius of the circle."""
if not color: color=self.radius_color
if not width: width=self.radius_width
vector=Vector.createFromPolarCoordonnates(self.radius,0,color=color)
vector.show(window,self.center,width=width)
vector.showText(surface,self.center,"radius",size=20)
def __call__(self):
"""Return the main components of the circle."""
return [self.position,self.radius]
def isCrossingCircle(self,other):
"""Determine if two circles are crossing."""
vector=Vector.createFromTwoPoints(self.center,other.center)
return vector.norm<self.radius+other.radius
def crossCircle(self,other):
"""Return the intersections points of two circles if crossing else
return None."""
if self.isCrossingCircle(other):
s=Segment(self.center,other.center)
m=s.middle
n=math.sqrt(self.radius**2-(s.norm/2)**2)
a=s.angle+math.pi/2
v1=Vector.createFromPolarCoordonnates(n,a)
v2=Vector.createFromPolarCoordonnates(n,-a)
p1=v1(m)
p2=v2(m)
return [p1,p2]
if __name__=="__main__":
from mycontext import Surface
surface=Surface(name="Abstract Demonstration",fullscreen=True)
p1=Point(10,0,radius=0.05,color=mycolors.YELLOW)
p2=Point(20,20,radius=0.05,color=mycolors.YELLOW)
#origin=Point(0,0)
origin=Point.origin()
l1=HalfLine(origin,math.pi/4)
l2=Line(p1,math.pi/2,correct=False)
s1=Segment(p1,p2)
print(Point.null)
while surface.open:
#Surface specific commands
surface.check()
surface.control()
surface.clear()
surface.show()
#Actions
l1.rotate(0.01,p2)
l2.rotate(-0.02,p1)
s1.rotate(0.03)
p=l1|l2
o=Point(0,0)
p3=l2.projectPoint(o)
f=Form([p1,p2,p3],area_color=mycolors.RED,fill=True)
#Show
surface.draw.window.print("l1.angle: "+str(l1.angle),(10,10))
surface.draw.window.print("l2.angle: "+str(l2.angle),(10,30))
surface.draw.window.print("f.area: "+str(f.area()),(10,50))
f.show(surface)
f.center.show(surface)
s1.show(surface)
o.show(surface,color=mycolors.GREY)
o.showText(surface,"origin")
p3.showText(surface,"origin's projection")
p3.show(surface,color=mycolors.LIGHTGREY)
if p:
p.show(surface,color=mycolors.RED)
p.showText(surface,"intersection point",color=mycolors.RED)
p1.show(surface)
p1.showText(surface,"p1")
p2.show(surface)
p2.showText(surface,"p2")
l1.show(surface,color=mycolors.GREEN)
l1.point.show(surface,color=mycolors.LIGHTGREEN,mode="cross",width=3)
l1.vector.show(surface,l1.point,color=mycolors.LIGHTGREEN,width=3)
l2.show(surface,color=mycolors.BLUE)
l2.point.show(surface,color=mycolors.LIGHTBLUE,mode="cross",width=3)
l2.vector.show(surface,l2.point,color=mycolors.LIGHTBLUE,width=3)
#Flipping the screen
surface.flip()
|
2114723258f1a9a8d3b0281676020098d7629943 | MarcPartensky/Python-Games | /Game Structure/geometry/version5/modulo.py | 1,888 | 3.6875 | 4 | import math
class Modulo:
def __init__(self, n, a=None):
"""'n' is the number, and 'a' is the modulo"""
if a == None:
self.a = float("inf")
else:
self.a = a
self.n = n % self.a
# Type conversions
def __str__(self):
return str(self.n)
def __int__(self):
return self.n
def __float__(self):
return float(self.n)
# Operations
# Addition
def __add__(self, other):
return (self.n + other.n) % self.a
__radd__ = __add__
def __iadd__(self, other):
self.n = (self.n + other.n) % self.a
return self
# Subtraction
def __sub__(self, other):
return (self.n - other.n) % self.a
__rsub__ = __sub__
def __isub__(self, other):
self.n = (self.n - other.n) % self.a
return self
# Multiplication
def __mul__(self, m):
return (self.n * float(m)) % self.a
__rmul__ = __mul__
def __imul__(self, m):
self.n = (self.n * float(m)) % self.a
return self
# True division
def __truediv__(self, m):
return (self.n / float(m)) % self.a
__rtruediv__ = __truediv__
def __itruediv__(self, m):
self.n = (self.n / float(m)) % self.a
return self
# Floor division
def __floordiv__(self, m):
return (self.n // float(m)) % self.a
__rfloordiv__ = __floordiv__
def __ifloordiv__(self, m):
self.n = (self.n // float(m)) % self.a
return self
# Exponentiation
def __pow__(self, m):
return (self.n ** float(m)) % self.a
__rpow__ = __pow__
def __ipow__(self, m):
self.n = (self.n ** float(m)) % self.a
return self
if __name__ == "__main__":
a = Modulo(5, 2 * math.pi)
b = Modulo(202, 2 * math.pi)
c = Modulo(62)
print(((a + b - c * a) * 5 / 2) ** 2) |
5d304023128714c95e67ec1ed77c8d4f1b3f33a9 | MarcPartensky/Python-Games | /Intersection/myposition.py | 2,382 | 3.546875 | 4 | from math import sqrt,cos,sin
from cmath import polar
from numpy import array,dot
class Position:
base="xyztabcdefhijklmnopqrsuvw"
angle_base="ab"
def __init__(self,*data,base=None,system="cartesian"):
"""Save a position using cartesian coordonnates."""
self.system=system
if self.system is "cartesian": self.data=array(data)
if self.system is "polar": self.data=polar(list(data))
if base: self.base=base
else: self.base=Position.base[:len(self.data)]
def __call__(self):
return list(self.data)
def __str__(self,system="cartesian"):
"""Gives a representation of the position."""
if system is "cartesian":
return " ".join([str(self.base[i])+"="+str(self.data[i]) for i in range(len(self.data))])
if system is "polar":
pass
x=lambda self:self.data[self.base.index("x")]
y=lambda self:self.data[self.base.index("y")]
z=lambda self:self.data[self.base.index("z")]
t=lambda self:self.data[self.base.index("t")]
__repr__=__str__
__add__=lambda self,other:self.data+other.data
__sub__=lambda self,other:self.data-other.data
def __mul__(self,other):
if type(other) is Position:
return Position(dot(self.data,other.data))
else:
return Position([self.data*other])
def __sub__(self,other):
pass
def __len__(self):
"""Return number of dimension of the position."""
return len(self.data)
def polar(self,position=None):
"""Return an array of the polar coordonnates using optionnal position."""
if not position: position=self.data
position=list(position)
if len(position)==2:
return array(polar(complex(*position)))
else:
raise Exception(str(position)+" is not a cartesian position.")
def cartesian(self,position=None):
"""Return an array of the cartesian position using optional polar position."""
if not position: position=self.data
if len(position)==2:
return array([position[0]*cos(position[1]),position[0]*sin(position[1])])
else:
raise Exception(str(position)+" is not a polar position.")
a=Position(2,6)
b=Position(2,4)
print((a*b).data)
print(a.polar())
print(a.cartesian())
print(Position.polar(a.data))
print(a)
|
6a5961313d688e4136885a19f2cd33e6592ff4cd | LanHikari22/Mutu-chan | /Commands/botcmd.py | 3,002 | 3.765625 | 4 |
class BotCMD:
"""
abstraction class of a bot command. Create this for every command except very fundemental ones
Override methods as necessary.
"""
# execution activation command for when listening for mention commands
command = None
# defined error_code constants
SUCCESS = 0 # success! you can execute this successfully.
COMMAND_MISMATCH = -1 # not even the command matches.
COMMAND_MATCH = 1 # in case the command matches, the error code is always positive! This isn't a success.
INVALID_ARGV_FORMAT = -2# in case the argv is not a list of strings...
def __init__(self, command:str):
self.command = command
def execute(self, argv):
"""action of command, if argv is None, you shall deal with the consequences"""
print("*executes abstract magic!*")
def get_error_code(self, command, argv=None):
"""
determines whether the command can activate.
This can be based on whether the given command matches the activation command,
but it also can be based on argument vector checks and making sure that the arguments are valid.
:param command; command thought to be the activation command
:param argv: argument vector, contains command and extra arguments for the command
:returns: 0 if successful, -1 if command doesn't match, or an error code indicating why it shouldn't activate.
"""
if self.command == command:
return self.COMMAND_MATCH
else:
return self.COMMAND_MISMATCH
def get_error_msg(self, error_code:int):
"""
this should be syncronized with the errorcodes returned by should_activate()
it helps prompting the user why their input was wrong.
:param errorcode: error code indicating why a certain command/argument vector are not valid input
:returns: a specified message per every define error code, or None if none are found
"""
error_msg = ""
if error_code == self.COMMAND_MISMATCH:
error_msg = "Command Mismatch"
elif error_code == self.COMMAND_MATCH:
error_msg = "Command Match"
elif error_code == self.INVALID_ARGV_FORMAT:
error_msg = "Invalid argv Format: must be a list of strings"
else:
error_msg = None
return error_msg
@staticmethod
def get_help_format():
"""
defines the help_format of this command. ex. "<number> <number>". does not contains command.
:return: the format the command should be in
"""
return "applyMagic --on Target"
@staticmethod
def get_help_doc():
"""
a little more detail into what a command does. This should be fairly basic. If sophisticated help is required,
implement that separately.
:return: documentation about the usage of a command
"""
return "I'm just an abstract wand~ in an astract world~" |
58529d86ce20df905e85e7641408699ba48a0aa2 | YpchenLove/py-example | /8-list.py | 416 | 3.765625 | 4 | # l = [1, 2, 3, 4, 5]
# print(l[0])
# print(l[1: 2])
# print(l[-2: -1])
# print(l[:])
# print(l[0:5:2])
l = [1, 2, 1, 1, 3, 4, 5, -1]
l2 = [7, 8, 9]
print(l[-1:]) # [5]
print(l[-1::-1]) # [5, 4, 3, 2, 1]
print(len(l))
print(max(l))
print(min(l))
print(l.count(1))
l.append(88)
print(l)
l.pop()
print(l)
l.remove(5)
print(l)
l.reverse()
print(l)
l.sort(reverse=False)
print(l)
l.index(-1)
print(l, 12)
|
a4682975b00b3a87be7e293ae844bd921e3d4db7 | zjipsen/chef-scheduler | /chef.py | 652 | 3.6875 | 4 | class Chef:
days_in_week = 5
def __init__(self, name, unavailable=[], since=6, times=0, vacation=False):
self.name = name
self.unavailable = unavailable
self.since = since
self.times = times
self.init_since = since
self.init_times = times
self.vacation = vacation
def cook(self):
self.since = max(self.since - 6, 0)
self.times += 1
def dont_cook(self):
self.since += 1
def __str__(self):
return " " + self.name + self.padding_to_six()
def padding_to_six(self):
return " " * (6 - len(self.name) + 1)
NOBODY = Chef("-") |
6e9541ca3a2030a5fdcbd1f28d4937afe60ae03e | MeitarEitan/Devops0803 | /1.py | 449 | 3.671875 | 4 | my_first_name = "Meitar"
age = 23
is_male = False
hobbies = ["Ski", "Guitar", "DevOps"]
eyes = ("brown", "blue", "green") # cant change (tuple)
# myself = ["aviel", "buskila", 30, "identig"]
myself = {"first_name": my_first_name, "last_name": "Eitan", "age": age} # dictionary
print("Hello World!")
print(my_first_name)
print(age)
print(is_male)
print(hobbies[1])
hobbies[1] = "Travel"
print(hobbies[1])
print(hobbies)
print(myself["first_name"])
|
ee0ca87dc7393247fc507193b6ef22c4c97c1293 | MeitarEitan/Devops0803 | /9.py | 343 | 3.796875 | 4 | def saveNames():
inputUser = input("Enter your name:")
myNewFile = open("names.txt", "a")
myNewFile.write(inputUser + "\n")
myNewFile.close()
def printNames():
file = open("names.txt", "r")
for name in file.readlines():
print(name, end=" ")
file.close()
saveNames()
saveNames()
saveNames()
printNames()
|
17c0945cae7677615b0f2b181b12505ebfadb0fd | varunpsr/python-ds | /binary-search-tree.py | 2,061 | 4.0625 | 4 | class Node:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def __str__(self):
if self is not None:
return f"{self.value}"
else:
return "None"
class BinarySearchTree:
def __init__(self):
self.root = None
def add_node(self, node):
print(f"Adding node: {node}\n")
if self.root is None:
self.root = node
print(f"Added root node: {self.root}")
else:
current_node = self.root
while True:
if node.value < current_node.value:
if current_node.left is None:
current_node.left = node
print(f"Adding {node} to left of {current_node}")
break
current_node = current_node.left
else:
if current_node.right is None:
current_node.right = node
print(f"Adding {node} to right of {current_node}")
break
current_node = current_node.right
def print_preorder(self, node):
if node is not None:
print(node)
self.print_preorder(node.left)
self.print_preorder(node.right)
def print_postorder(self, node):
if node is not None:
self.print_postorder(node.left)
self.print_postorder(node.right)
print(node)
def print_inorder(self, node):
if node is not None:
self.print_inorder(node.left)
print(node)
self.print_inorder(node.right)
root = Node(7)
two = Node(2)
five = Node(5)
nine = Node(9)
eleven = Node(11)
bst = BinarySearchTree()
bst.add_node(root)
bst.add_node(two)
bst.add_node(five)
bst.add_node(nine)
bst.add_node(eleven)
bst.print_preorder(bst.root)
bst.print_inorder(bst.root)
bst.print_postorder(bst.root) |
6e49ad323b536ee1e669d1ce643959b66da67823 | python-fisika-uin/Fundamental | /fundamental001.py | 1,367 | 3.8125 | 4 | # Sintaks Sekuensial
print('Hello World!')
nama = 'Eko S.W'
usia = 40
Usia = 50 #ini berbeda dengan usia (huruf kecil)
print(nama, 'Usia=', usia)
# Sintaks bercabang
if usia <= 40:
print('Masih muda')
print('Usia belajar')
print('Usia mencari jatidiri')
else:
print('Tak muda lagi')
print('Banyakin tobat')
print('Pikir anak cucu')
#sintaksis perulangan
jumlah_anak = 2
for iterasi in range(1, jumlah_anak+1):
print('Halo anak ke', iterasi)
# contoh lain: menghitung 1+2+3+4+5 = 15
jumlah_bilangan = 5
total_penjumlahan = 0
for bilangan in range(1, jumlah_bilangan+3):
total_penjumlahan = total_penjumlahan + bilangan
print('Hasil penjumlahan', total_penjumlahan)
# cara membaca baris ke 27
"""
1. total_penjumlahan = 0 + 1 = 1
2. total_penjumlahan = 1 + 2 = 3
3. total_penjumlahan = 3 + 3 = 6
4. total_penjumlahan = 6 + 4 = 10
5. total_penjumlahan = 10 + 5 = 15
6. total_penjumlahan = 15 + 6 = 21
7. total_penjumlahan = 21 + 7 = 28
"""
#tipe data array
uang_untuk_anak = [] #tipe data array
uang_untuk_anak.append(10000)
uang_untuk_anak.append(5000)
uang_untuk_anak.append(50000)
# berapa rata2 uang untuk tiap anak?
jumlah_total_uang = 0
for uang in uang_untuk_anak:
jumlah_total_uang = jumlah_total_uang + uang
print('Jumlah total uang', jumlah_total_uang)
rata_rata_uang = jumlah_total_uang / 3
print('Rata-rata uang', rata_rata_uang)
|
bc8744b8265be788f974f5bd0a5c9b24f26da35d | xinzheshen/py3-practice | /src/cookbook/09_yuanbiancheng/decoretor0.py | 735 | 3.546875 | 4 | import time
from functools import wraps
def timethis(func):
'''
Decorator that reports the execution time.
'''
# 注意加不加@wraps的区别
@wraps(func)
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
end = time.time()
print(func.__name__, end-start)
return result
return wrapper
@timethis
def hello(msg: str):
"""
print the message after sleep 2s
"""
time.sleep(2)
print(msg)
hello("decoretor")
print(hello.__name__)
print(hello.__doc__)
print(hello.__module__)
print(hello.__annotations__)
print(hello.__wrapped__("hi"))
from inspect import signature
# 打印参数签名信息
print(signature(hello)) |
03175236c641b680cf7e47e78e13c6f3bece9a72 | Aptegit/Assignment1 | /new_testcode.py | 751 | 4.09375 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
obill =float(input('How much is your original bill? ')) #input string
# In[2]:
print(type(obill)) #to check the data type of variable
# In[3]:
tip = int(input('What percentage is your tip?')) #input string
# In[4]:
print(type(tip)) #to check the data type of variable
# In[5]:
f1 = obill*tip #calculating percentage using standard percentage formula
ftip= float("{:.2f}".format(f1/100))
print (ftip)
print('Your tip based on ' + str(tip) + ' % is ' + str(ftip) + ' $ . ')
# In[6]:
fbill = obill + ftip #adding tip percent value to the original bill
#print(type(obill))
#print(type(ftip))
print('Your total bill is : ' + str(fbill) + ' $ . ')
|
f7202c99351112f2da3783118059f6d02c040d1d | jameswong95/ICT1008 | /block_stack.py | 1,341 | 3.890625 | 4 | class Stack:
top = -1
def __init__(self):
self.top = -1
# this stack is implemented with Python list (array)
self.data = []
def size(self):
return len(self.data)
def push(self, value):
# increment the size of data using append()
self.data.append(value)
self.top += 1
def pop(self):
self.top -= 1
return self.data.pop()
def isEmpty(self):
size = self.size()
if size == 0:
return True
else:
return False
def peek(self):
if not self.isEmpty():
return self.data[self.size()-1]
else:
return False
def peekAt(self, pos):
return self.data[pos]
def copyTo(self):
stack = Stack()
for ele in self.data:
stack.push(ele)
return stack
def toString(self):
string1 = ""
size = len(self.data)
if size > 0:
for i in reversed(xrange(size)):
string1 += str(self.data[i])
elif size is 0:
string1 += " "
return string1
def printStack(self):
print self.data
def contains(self, value):
for i in range(len(self.data)):
if self.data[i] is value:
return i
return -1
|
8e803130fffcc7f8139e4125c2e1fa451becba71 | binjun/LeetCode | /longestpalindromicsubstring.py | 1,196 | 4.0625 | 4 | # -*- coding: utf-8 -*-
"""
Given a string s, find the longest palindromic substring in s.
You may assume that the maximum length of s is 1000.
Example1:
Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.
Example2:
Input: "cbbd"
Output: "bb"
"""
import unittest
class Solution(object):
def longestPalindrome(self, s):
"""
:type s: str
:rtype: str
"""
ret = ""
length = len(s)
if length <= 1:
return ret
for i in range(length, 1, -1):
for j in range(length - i + 1):
substring = s[j:i+j]
#print "substring = %s" % substring
if substring == substring[::-1]:
ret = substring
break
else:
continue
break
return ret
solution = Solution()
class myUnittest(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def testcase1(self):
self.assertEqual(solution.longestPalindrome("babad"), "bab")
def testcase2(self):
self.assertEqual(solution.longestPalindrome("cbbd"), "bb")
unittest.main()
|
2512fbd72639a9c9d35adad3ddbb2c4e9b032ace | shivam-72/simple-python | /PYTHON FUN/lovecalculator.py | 798 | 3.890625 | 4 | print("Welcome to the Love Calculator!")
name1 = input("What is your name? \n")
name2 = input("What is their name? \n")
name1.lower()
name2.lower()
name3 = name1+name2
T = name3.count("t")
R = name3.count("r")
U = name3.count("u")
E = name3.count("e")
total = str(T+R+U+E)
L = name3.count("l")
O = name3.count("o")
V = name3.count("v")
E = name3.count("e")
total2 = str(L+O+V+E)
total3 = total+total2
value = int(total3)
if value >= 0 and value <= 25:
print(f'your score is {total3}, you are decent couple')
elif value > 25 and value <= 50:
print(f'your score is {total3}, you are alright together')
elif value > 50 and value <= 75:
print(f'youour score is {total3}, you love is unconditional')
else:
print(f' your score is {total3}, purest form of love')
|
e547651f91838d65f910be328522ef1e196652a4 | salemmp/memorize-words | /words.py | 1,626 | 3.71875 | 4 | import os
import sys
import time
lista = {"hello":"hola",
"word":"palabra",
"phone":"celular",
"hand":"mano",
"how":"como",
"people":"gente",
"leave":"salir",
"key":"tecla",
"understand":"entender",
"can":"poder",
"we":"nosotros",
"he":"el",
"she":"ella",
"low":"bajo",
"high":"alto",
"someone":"alguien",
"head":"cabeza",
"table":"mesa",
"room":"cuarto",
"bathroom":"baño"}
#contador
aciertos = 0
#obtenemos llaves
llaves = lista.keys()
#################################################
for x in llaves:
valor = lista.get(x)
respuesta = input (x +" is? ")
if respuesta == valor:
print("correcto!!!")
aciertos = aciertos + 1
time.sleep(1)
os.system("cls")
else:
print("incorrecto")
time.sleep(0.3)
os.system("cls")
##################################################################
if (aciertos >= 1) and (aciertos <5):
print(str(aciertos)+ '/20')
salida = input("Mal , sigue estudiando")
if (aciertos >=5) and (aciertos<10):
print(str(aciertos)+ '/20')
salida = input("puedes mejorar")
if aciertos >=10 and aciertos <15:
print(str(aciertos)+ '/20')
salida = input("intermedio.. nada mal")
if aciertos >=15 and aciertos <20:
print(str(aciertos)+ '/20')
salida = input("muy bien ! sigue asi")
if aciertos == 20:
print(str(aciertos)+ '/20')
salida = input("Excelente!! ") |
a383e4a8701f7c9ab85f7295dc309bb4609902f9 | lianhuo-yiyu/python-study | /study9 str/main.py | 464 | 4.09375 | 4 | #str的驻留机制 指相同的字符串只会占据一个内存空间,一个字符串只被创建一次,之后新的变量是获得之前的字符串的地址
a = 'python'
b = "python"
c = """python"""
print(id(a))
print(id(b))
print(id(c))
s1 = ''
s2 = ''
print(s1 == s2)
print(s1 is s2)
print(id(s1))
print(id(s2))
#理论上有特殊字符串不驻留,下面这个cmd不驻留,pycharm进行了优化
z1 = 'a%'
z2 = 'a%'
print(id(z1))
print(id(z2)) |
94c2379bf1ab91f31e7fcb57dee06b37b00d3a14 | lianhuo-yiyu/python-study | /study6 dict/main.py | 824 | 4.09375 | 4 | #字典 { } 可变序列 dict 以键值对的方式存储数据 {name : hhh}:前面的叫键,:后面的叫值 字典是无序的序列 字典存储是key时经过hash计算
#字典的键key不允许重复,只有值可以重复,后面的键值会覆盖相同的键名 列表可以按照自己的想法找地方插入元素,dict不行,它是无序的 字典空间换时间,内存浪费大
zidian = {'name' : 'python' , "nianling" : 24}
print(zidian)
c = dict(name = 'python', nian = 100)
print(type(c))
print(c)
#字典中的值获取
print(zidian['nianling'])
#print(zidian['nian'])
print(c.get('nian'))
print(c.get('nianling'))
print(c.get('nianling', 'bucunzai')) #可以让返回的none值变成不存在
#列表可以按位置插入
lst =[5,6,9,7,5,0,5]
lst.insert(1, -1)
print(lst)
|
1f5f1540137ef46b49d62027955fa15f46dc14e1 | lianhuo-yiyu/python-study | /STUDY10 函数/递归函数.py | 393 | 3.875 | 4 | # Python 学习 1
# 2020/11/28 17:12
#递归函数 一个函数调用自己
#递归用来计算阶乘
def fac(n):
if n ==1:
return 1
else:
return n *fac(n - 1)
print(fac(6))
def text(n):
for i in range(1,n):
if i == 1 :
print('1')
elif i == 2 :
print('1','1')
elif i != 1 and i !=2 :
print(555 + i)
print(text(5))
|
5cd01bde10307074f0c003b09c034b799fb36965 | lianhuo-yiyu/python-study | /STUDY10 函数/main.py | 1,775 | 4.0625 | 4 | #函数的原理与利用
#函数的创建
#def 函数名([输入参数]):
# 函数体
# [return xxx]
def cale(a,b):
# c = a + b
c = a - b
return c
result = cale(10,20)
print(result)
#函数调用时的参数传递 创建的时候函数括号里面是def hhh(形参,形参), 在函数的调用处,括号里面的是实参,实际参数 形参和实参的名字可以不相同
#参数的传递(实参的值传给形参)
#1 位置实参 如上例,按存放的第一个第二个位置传递
#2 关键字传参,就是将形参自行按需求赋值
result2 = cale(b=20, a=33)
result3 = cale(b = -10, a = 33)
print(result2)
print(result3)
#在函数调用过程中,进行参数的传递。如果参数是不可变对象,在函数的中的修改值出了函数就会变回去,不会影响实参的值,如果是可变的对象,那么参数的改变会一直存在,函数调用过后值也是被修改过的
def lit(a, b):
b.append(30)
a = list(a)
print('函数里面的数据类型为',type(a))
print(b)
a = 'python'
b = [10, 30, 50]
lit(a,b)
print(a)
print('函数外面的数据类型',type(a))
print(b)
#函数的返回值 return
#函数没有返回值 即函数调用过后,不用为调用该函数的函数提供出输入的数据
def fun():
print('hhh')
fun()
#函数返回的只有一个返回值,也就是被调用的函数只做了一项运算有一个结果需要提供出去,return 结果,直接返回该结果的数据类型
def fun1():
return 'hehehe'
res = fun1()
print(res)
print(fun1()) #整个函数就代表那一个数值
def fun2():
return 'aa','bb' #返回多个数值,所有的返回值作为一个元组出现
res2 = fun2()
print(res2)
print(fun2())
|
ea03689b8be9bd5fab6af7d4e20d2ceae0d8e88b | reesporte/euler | /3/p3.py | 534 | 4.125 | 4 | """
project euler problem 3
"""
def is_prime(num):
if num == 1:
return False
i = 2
while i*i <= num:
if num % i == 0:
return False
i += 1
return True
def get_largest_prime_factor(num):
largest = 0
i = 2
while i*i <= num:
if num%i == 0:
if is_prime(i):
largest = i
i += 1
return largest
def main():
print("the largest prime factor is:", get_largest_prime_factor(600851475143))
if __name__ == '__main__':
main()
|
8063a87ba1e389e833699bfdc6378698ae8490a7 | reesporte/euler | /19/p_19.py | 1,608 | 4.03125 | 4 | """
project euler problem 19
"""
def is_leap_year(year):
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
return True
return False
def get_days_in_month(month, year):
months = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
if month == 2 and is_leap_year(year):
return 29
return months[month-1] # month - 1 bc it's in a list, index starts at 0
def sunday_as_first_of_month(jan_day, year):
"""
given what day the 1st of january of any year is, counts the number of sundays
that are the first of the month in that year
mon = 0 ... sun = 6
"""
count = 0
months = [0]*13
months[1] = jan_day
if months[1] == 6:
count += 1
for month in range(2, 13):
months[month] = (months[month-1] + get_days_in_month(month-1, year)) % 7
if months[month] == 6:
count += 1
return count
def boring_way():
"""
boring way that doesnt take a lot of creativity using built-in functions
"""
from datetime import date
for year in range(1901, 2001):
count = 0
for month in range(1, 13):
day = date(year, month, 1)
if day.weekday() == 6:
count += 1
print(count)
def main():
jan_day = [0] * 101
jan_day[0] = 0
count = 0
for i in range(1, 100):
if jan_day[i-1] == 6:
jan_day[i] = 0
else:
jan_day[i] = jan_day[i-1] + 1
for i in range(1901, 2001):
count += sunday_as_first_of_month(jan_day[i-1900], i)
print(count)
if __name__ == '__main__':
main()
|
567820cdb4e2c97509d232fe441e2f9b6a58a34b | jayden-nguyen/Homework2--NguyenQuangHuy | /homework4/serious2.py | 1,364 | 3.9375 | 4 | prices = {"banana" : 4,
"apple" : 2,
"orange" : 1.5,
"pear" : 3}
li = prices.keys()
purchased = {
"banana": 5,
"orange":3
}
print("YOU BOUGHT 5 BANANAS AND 3 ORANGES")
choice = "yes"
while choice.lower() != "no":
choice = input("Do you want more(yes or no, press no to exit)? ")
if choice.lower() == "yes":
fruit = input("what's type of fruit? ")
fruit = fruit.lower()
if fruit in li:
if fruit.lower() == "banana" or fruit == "orange":
quant = int(input("how many?"))
quant += purchased[fruit]
purchased[fruit]=quant
else:
quant = int(input("how many?"))
purchased[fruit] = quant
else:
print("We don't have it")
print("you bought "+str(quant)+" "+fruit+"s")
elif choice.lower()=='no':
break
else:
print("IVALID,Please input again")
print("**********************************************")
purchased_items = list(purchased.items())
total = 0
print("THIS IS YOUR BILL")
for i in range(len(purchased_items)):
print(purchased_items[i][0],"quantity: ",purchased_items[i][1]," price: ",prices[purchased_items[i][0]])
total += purchased_items[i][1] * prices[purchased_items[i][0]]
print("total is:")
print(str(total)+"$")
|
d0131c5e298483388d06683c5f60046a570ba2eb | ErickHernandez/ProyectoCompiladores | /pyfiles/gcd.py | 290 | 4.09375 | 4 | # Program to compute the GCD
# Funcion que calcula el maximo comun divisor
def gcd(a, b):
if b == 0:
return a
else:
return gcd(b, a % b)
x = input("Introduzca un numero: ")
y = input("Introduzca otro numero: ")
z = gcd(x, y)
print "El maximo comun divisor es ", z
|
ed5d3fc73cc8479689a580b926346d098d467c71 | sajjanparida/DS-Algorithms | /Sorting/tripletwithlessthansum.py | 406 | 3.90625 | 4 |
# program to find the count of triplets with sum less than given number
def triplets_sum(arr,n,req_sum):
c=0
arr.sort()
for k in range(0,n-2):
i=k+1
j=n-1
while i<j:
if arr[k] + arr[i] + arr[j] < req_sum:
c += j-i
i += 1
else:
j -=1
return c
arr=[-2,0,1,3]
print(triplets_sum(arr,4,2))
|
2fc28c8c55ff62b44ecf16f3094d41dee4c3a012 | sajjanparida/DS-Algorithms | /LinkedList/Introduction.py | 428 | 3.953125 | 4 |
class Node:
def __init__(self,data):
self.data=data
self.next=None
class LinkedList:
def __init__(self):
self.head=None
def printList(self):
temp=self.head
while(temp):
print(temp.data)
temp = temp.next
llist = LinkedList()
first=Node(1)
second=Node(2)
third=Node(3)
llist.head = first
first.next=second
second.next=third
llist.printList()
|
c050dc01202dce89bf26ea6f125d3410d2177a50 | sajjanparida/DS-Algorithms | /Sorting/subarraysumcount.py | 390 | 3.6875 | 4 |
def countOfSubarray(arr,n):
i=-1
count=0
sum=0
freq={}
freq[sum]=1
while i < n-1:
i +=1
sum += arr[i]
if freq.get(sum) != None:
count += freq[sum]
freq[sum]=freq[sum]+1
else:
freq[sum]=1
return count
arr=[0,0,5,5,0,0]
print("The subarray with 0 sum is : {} ".format(countOfSubarray(arr,6))) |
2529bc8fce8c1186cf9325d6ef1479f22adb9e1f | sajjanparida/DS-Algorithms | /Sorting/productarraypuzzle.py | 622 | 3.703125 | 4 | def productExceptSelf(nums, n):
#code here
zeroflag=0
product=1
if n==1:
return 1
for i in range(0,n):
if nums[i]!= 0 :
product *= nums[i]
else:
zeroflag += 1
if zeroflag==1:
for i in range(0,n):
if nums[i]==0:
nums[i] = product
else:
nums[i]=0
elif zeroflag>1:
for i in range(0,n):
nums[i]=0
else:
for i in range(0,n):
nums[i]=product//nums[i]
return nums
nums=[1,0,5,0,7]
print(productExceptSelf(nums,5)) |
f6063a11518b1fcc2bc653ed3f505dddc9ad4dbf | sajjanparida/DS-Algorithms | /Arrays/Three_way_partition.py | 925 | 4.09375 | 4 | # Given an array of size n and a range [a, b]. The task is to partition the array around the range such that array is divided into three parts.
# 1) All elements smaller than a come first.
# 2) All elements in range a to b come next.
# 3) All elements greater than b appear in the end.
# The individual elements of three sets can appear in any order. You are required to return the modified array
def three_way_partition(arr,n,a,b):
l=0
r=n-1
i=0
while i < r:
if (arr[i] < a):
arr[i],arr[l]= arr[l],arr[i]
l += 1
i += 1
print("l: {} , i : {}".format(l,i))
elif arr[i] > b:
arr[i],arr[r] =arr[r],arr[i]
r -= 1
print("r: {} , i : {}".format(r,i))
else:
i += 1
return arr
arr=[76,8 ,75, 22, 59, 96, 30, 38, 36]
print("Output array is {}".format(three_way_partition(arr,9,44,62)))
|
bbeb124cd35e865c17ae7a9691022031b81ba553 | jonahtjandra/sudoku-solver | /Sudoku.py | 2,939 | 4.15625 | 4 | class Sudoku:
def __init__(self, board:'list[list]') -> None:
if (len(board) != 9 or len(board[0]) != 9): raise "Expected a 9 by 9 board"
self.board = board
self.iterations = []
# for printing out the 2d list representation of the board
def display(self, board:'list[list]'):
if (len(board) != 9):
print("Not a valid 9x9 sudoku board!")
return
x = 0
for i in range(len(board)+4):
if (i==0 or i==4 or i==8 or i==12):
print('-------------------------')
continue
y = 0
for j in range(len(board)+4):
if (j == 0 or j==4 or j==8):
print('|', end=' ')
elif (j == 12):
print('|')
else:
print(board[x][y], end=' ')
y += 1
x += 1
# method to check if a certain number, n, is valid to be
# place at a certain x and y coordinate in the board
def isPossible(self, x:int, y:int, n:int) -> bool:
if (x > 8 and y > 8 and n >= 0 and n <= 9):
return False
#horizontal check
for i in range(9):
if (self.board[x][i] == n and i != y):
return False
#vertical check
for i in range(9):
if (self.board[i][y] == n and i != x):
return False
#square check
square_x = x // 3
square_y = y // 3
for i in range(3):
for j in range(3):
if (self.board[square_x * 3 + i][square_y * 3 + j] == n and x != square_x * 3 + i and y != square_y * 3 + j):
return False
#possible placement
return True
# Method to check if solution is correct
def isSolution(self) -> bool:
for i in range(9):
for j in range(9):
if (not(self.isPossible(self.board, i, j, self.board[i][j]))):
return False
return True
# Method to find the next empty coordinate in the board
# Returns false if there are no empty space left (solved)
def nextEmpty(self, loc:list) -> bool:
for i in range(9):
for j in range(9):
if (self.board[i][j] == '.'):
loc[0] = i
loc[1] = j
return True
return False
# Method to solve the board
# Returns false if board is not solveable
def solve(self) -> bool:
loc = [0,0]
if (not self.nextEmpty(loc)):
return True
i = loc[0]
j = loc[1]
for n in range(1,10):
if (self.isPossible(i, j, n)):
self.board[i][j] = n
self.display(self.board)
if (self.solve()):
return True
self.board[i][j] = '.'
return False
|
18d4f634488453133535b594fdff3fb8d851f6af | Yokohama-Miyazawa/uec_django | /presen/veiw_tetris.py | 3,312 | 3.734375 | 4 | import tkinter as tk
from random import choice
class Game():
WIDTH = 300
HEIGHT = 500
def start(self):
self.speed = 150
self.new_game = True
self.root = tk.Tk()
self.root.title("Tetris")
self.canvas = tk.Canvas(
self.root,
width=Game.WIDTH,
height=Game.HEIGHT
)
self.canvas.pack()#表示される
self.timer()
self.root.mainloop()
def timer(self):
if self.new_game == True:#最初の図形を作るため
self.current_shape = Shape(self.canvas)
self.new_game = False
if not self.current_shape.fall():
self.current_shape = Shape(self.canvas)#新しく図形を作る
self.root.after(self.speed,self.timer)#.speedミリ秒後.timerを起動
class Shape:
BOX_SIZE = 20
START_POINT = Game.WIDTH / 2 / BOX_SIZE * BOX_SIZE - BOX_SIZE#画面の真ん中のブロックの位置
SHAPES = (
((0, 0), (1, 0), (0, 1), (1, 1)), # 四角
((0, 0), (1, 0), (2, 0), (3, 0)), # 棒
((2, 0), (0, 1), (1, 1), (2, 1)), # L字
)
def __init__(self,canvas):
#ランダムにブロックを選び、windowにブロックを表示する
self.boxes = []
self.shape = choice(Shape.SHAPES)#ランダムに形を選ぶ
self.canvas = canvas
for point in self.shape:
#point => テトリス画面上の座標
box = canvas.create_rectangle(#ブロックの1つ1つの形成
point[0] * Shape.BOX_SIZE + Shape.START_POINT,
point[1] * Shape.BOX_SIZE,
point[0] * Shape.BOX_SIZE + Shape.BOX_SIZE + Shape.START_POINT,
point[1] * Shape.BOX_SIZE + Shape.BOX_SIZE
)
self.boxes.append(box)#boxesにブロックを入れる
def fall(self):#図形を下に移動
if not self.can_move_shape(0, 1):
return False
else:
for box in self.boxes:
self.canvas.move(box, 0 * Shape.BOX_SIZE, 1 * Shape.BOX_SIZE)
return True
def can_move_box(self, box, x, y):#ボックスが動けるかチェック
x = x * Shape.BOX_SIZE
y = y * Shape.BOX_SIZE
coords = self.canvas.coords(box)
# 画面からブロックが行き過ぎるとFalse
if coords[3] + y > Game.HEIGHT: return False
if coords[0] + x < 0: return False
if coords[2] + x > Game.WIDTH: return False
# 他のボックスに重なるとFalse
overlap = set(self.canvas.find_overlapping(
(coords[0] + coords[2]) / 2 - x,
(coords[1] + coords[3]) / 2 - y,
(coords[0] + coords[2]) / 2 + x,
(coords[1] + coords[3]) / 2 + y
))
other_items = set(self.canvas.find_all()) - set(self.boxes)
# print(other_items)
# print(overlap)
if overlap & other_items:
return False
return True
def can_move_shape(self, x, y):#図形が移動できるかチェック
for box in self.boxes:
if not self.can_move_box(box, x, y): return False
return True
if __name__ == "__main__":
game = Game()
game.start()
|
4e3ae8718dd37281e9b8dbf85d2df92c555efd48 | 50417/phd | /learn/challenges/020-highest-product.py | 953 | 3.5 | 4 | #!/usr/bin/env python3
from collections import deque
from typing import List
def approach1(lst: List[int]) -> int:
if not isinstance(lst, list):
raise TypeError
if len(lst) < 3:
raise ValueError
if any(x is None for x in lst):
raise TypeError
best = deque(sorted(lst[:3]))
for x in lst[3:]:
if x > min(best):
# TODO: insert into sorted best
del best[best.index(min(best))]
best.append(x)
return best[0] * best[1] * best[2]
if __name__ == "__main__":
try:
approach1(2)
assert False
except TypeError:
pass
try:
approach1([2, 2])
assert False
except ValueError:
pass
try:
approach1([1, 2, 3, None, 2])
assert False
except TypeError:
pass
examples = [
([1, 2, 3], 6),
([1, 8, 8], 64),
([1, 8, 1, 8], 64),
([1, 8, 1, 2, 8], 128),
]
for ins, outs in examples:
print(ins, outs, approach1(ins))
assert approach1(ins) == outs
|
54d2e882b8d9a188ffdef473ad3e6372c1d3f0fd | 50417/phd | /learn/challenges/018-list-binary-tree.py | 2,489 | 3.8125 | 4 | #!/usr/bin/env python3
from collections import deque
from typing import List
class Node(object):
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def __lt__(self, rhs: "Node"):
return self.data < rhs.data
def __eq__(self, rhs: "Node"):
return self.data == rhs.data
def __le__(self, rhs: "Node"):
return self.__eq__(self, rhs) or self.__lt__(self, rhs)
def __gt__(self, rhs: "Node"):
return not self.__le__(self, rhs)
def __ge__(self, rhs: "Node"):
return self.__eq__(self, rhs) or self.__gt__(self, rhs)
class Graph(object):
def __init__(self, root=None):
self.root = root
def insert(self, data, root=None):
if root is None:
root = self.root
newnode = Node(data)
if self.root is None:
self.root = newnode
else:
if data <= root.data:
if root.left:
return self.insert(data, root.left)
else:
root.left = newnode
else:
if root.right:
return self.insert(data, root.right)
else:
root.right = newnode
return newnode
@property
def elements(self) -> List:
elements = []
q = deque([])
if self.root:
q.append(self.root)
while len(q):
node = q.popleft()
elements.append(node.data)
if node.left:
q.append(node.left)
if node.right:
q.append(node.right)
return elements
@property
def levels(self) -> List[List]:
levels = []
q = deque()
if self.root:
q.append((0, self.root))
while len(q):
depth, node = q.popleft()
if len(levels) <= depth:
levels.append([])
levels[depth].append(node.data)
if node.left:
q.append((depth + 1, node.left))
if node.right:
q.append((depth + 1, node.right))
return levels
if __name__ == "__main__":
g = Graph()
assert g.elements == []
assert g.levels == []
g.insert(5)
assert g.elements == [5]
assert g.levels == [[5]]
g.insert(4)
assert g.elements == [5, 4]
assert g.levels == [[5], [4]]
g.insert(5)
assert g.elements == [5, 4, 5]
assert g.levels == [[5], [4], [5]]
g.insert(2)
assert g.root.left.right.data == 5
assert g.root.left.left.data == 2
assert g.elements == [5, 4, 2, 5]
assert g.levels == [[5], [4], [2, 5]]
g.insert(10)
g.insert(7)
g.insert(6)
assert g.elements == [5, 4, 10, 2, 5, 7, 6]
assert g.levels == [[5], [4, 10], [2, 5, 7], [6]]
|
b490ccfe7a99436aa96f5e9ad6d04c83caaba021 | YinglunYin/MachineLearning-CS6140 | /2-Linear&RidgeRegression/src/problem2.py | 4,487 | 3.75 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Feb 14 12:32:58 2018
CS6140 Assignment2 Gradient Descent Problem2
@author: Garrett
"""
from sklearn import linear_model
import math
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# reader
def dataset_reader(file):
return np.array(pd.read_csv(file, header=None), dtype=np.float64)
# normalize X data using z-score and then add x0
def normalize(X):
mean = np.mean(X, 0)
std = np.std(X, 0)
X_norm = (X - mean) / std
X_norm = add_x0(X_norm)
return X_norm, mean, std
# normalize X testing data using mean and deviation of training data
def test_normalize(X, mean, std):
X_norm = (X - mean) / std
X_norm = add_x0(X_norm)
return X_norm
# add x0 to data
def add_x0(X):
return np.column_stack([np.ones([X.shape[0], 1]), X])
# predict y_hat using X and w
def predict(X, w):
return X.dot(w)
# sum of squared errors
def sse(X, y, w):
y_hat = predict(X, w)
return ((y_hat - y) ** 2).sum()
# root mean squared error
def rmse(X, y, w):
return math.sqrt(sse(X, y, w) / y.size)
# cost function of regression
def cost_function(X, y, w):
return sse(X, y, w) / 2
# derivative vector of the cost function
def cost_derivatives(X, y, w):
y_hat = predict(X, w)
return (y_hat - y).dot(X)
def plot_rmse(rmse_sequence):
# Data for plotting
s = np.array(rmse_sequence)
t = np.arange(s.size)
fig, ax = plt.subplots()
ax.plot(t, s)
ax.set(xlabel='iterations', ylabel='rmse',
title='rmse trend')
ax.grid()
plt.legend(bbox_to_anchor=(1.05,1), loc=2, shadow=True)
plt.show()
# implement gradient descent to calculate w
def gradient_descent(X, y, w, learningrate, tolerance, maxIteration=1000):
rmse_sequence = []
last = float('inf')
for i in range(maxIteration):
w = w - learningrate * cost_derivatives(X, y, w)
cur = rmse(X, y, w)
diff = last - cur
last = cur
rmse_sequence.append(cur)
if diff < tolerance:
# print(i)
break
plot_rmse(rmse_sequence)
return w
# k fold validation
def k_fold_validation(dataset, learningrate, tolerance, folds=10):
np.random.shuffle(dataset)
end = 0
size = math.floor(dataset.shape[0] / folds)
rmse_train = []
rmse_test = []
sse_train = []
sse_test = []
for k in range(folds):
start = end
end = start + size
dataset_test = dataset[start: end]
left = dataset[0: start]
right = dataset[end: ]
dataset_train = np.vstack([left, right])
X_train = dataset_train[:, 0:-1]
y_train = dataset_train[:, -1]
X_train, mean, std = normalize(X_train)
X_test = dataset_test[:, 0:-1]
y_test = dataset_test[:, -1]
X_test = test_normalize(X_test, mean, std)
w = np.ones(X_train.shape[1], dtype=np.float64) * 0
w = gradient_descent(X_train, y_train, w, learningrate, tolerance)
rmse_train.append(rmse(X_train, y_train, w))
rmse_test.append(rmse(X_test, y_test, w))
sse_train.append(sse(X_train, y_train, w))
sse_test.append(sse(X_test, y_test, w))
print('RMSE for training data:')
print(rmse_train)
print('Mean:')
print(np.mean(rmse_train))
print('RMSE for testing data:')
print(rmse_test)
print('Mean:')
print(np.mean(rmse_test))
print()
print('SSE for training data:')
print('Mean:')
print(np.mean(sse_train))
print('Standard Deviation:')
print(np.std(sse_train))
print('SSE for testing data:')
print('Mean:')
print(np.mean(sse_test))
print('Standard Deviation:')
print(np.std(sse_test))
def test_housing():
print('Housing:')
dataset = dataset_reader('housing.csv')
k_fold_validation(dataset, 0.1e-3, 0.5e-2)
print()
def test_yacht():
print('Yacht:')
dataset = dataset_reader('yachtData.csv')
k_fold_validation(dataset, 0.1e-2, 0.1e-2)
print()
def test_concrete():
print('Concrete:')
dataset = dataset_reader('concreteData.csv')
k_fold_validation(dataset, 0.7e-3, 0.1e-3)
print()
def main():
test_housing()
test_yacht()
test_concrete()
if __name__ == '__main__':
main() |
fd289fe5c232aa58735368aff954409d808adf02 | Black-Eagle-1/driving | /driving.py | 248 | 3.84375 | 4 | country = input('你所在的國家: ')
age = input('你的年齡: ')
age = int(age)
if country == '美國' and age >= 16:
print('你可以開車')
elif country == '台灣' and age >= 18:
print('你可以開車')
else:
print('你不能開車')
|
11ec0890ed9eb2c6540f1c8c34eb778c8302fd46 | wxmsummer/algorithm | /leetcode/hot/605_canPlaceFlowers.py | 851 | 4.0625 | 4 | # 605.种花问题
from typing import List
class Solution:
# 模拟法,如果该位置、该位置的前一个位置、该位置的后一个位置没种,就种上
def canPlaceFlowers(self, flowerbed: List[int], n: int) -> bool:
length = len(flowerbed)
count = 0
for i in range(length):
# 注意数组越界
if flowerbed[i] == 1 or (i > 0 and flowerbed[i-1]==1) or (i < length - 1 and flowerbed[i+1] == 1):
continue
else:
flowerbed[i] = 1
count += 1
print('flower:', flowerbed)
return True if count >= n else False
if __name__ == '__main__':
obj = Solution()
print(obj.canPlaceFlowers([1,0,0,0,1], 1))
print(obj.canPlaceFlowers([1,0,0,0,1], 2))
print(obj.canPlaceFlowers([1,0,0,0,0,1], 2)) |
87f761c182e6d122e69d9d5d9c44d896fd729655 | wxmsummer/algorithm | /leetcode/offer/offer14_cuttingRope.py | 759 | 3.90625 | 4 | # 剪绳子
import math
# 数学证明
# 任何大于1的数都可由2和3相加组成
# 当n>=5时,将它剪成2或3的绳子段,2(n-2) > n,3(n-3) > n,都大于他未拆分前的情况,
# 当n>=5时,3(n-3) >= 2(n-2),所以我们尽可能地多剪3的绳子段
# 当绳子长度被剪到只剩4时,2 * 2 = 4 > 1 * 3,所以没必要继续剪
class Solution:
def cuttingRope(self, n: int) -> int:
if n <= 3:
return n - 1
a = n // 3
b = n % 3
if b == 0:
return int(3 ** a) % 1000000007
if b == 1:
return int(3 ** (a-1) * 4) % 1000000007
return int(3 ** a * 2) % 1000000007
if __name__ == '__main__':
obj = Solution()
print(obj.cuttingRope(120)) |
23b9938f61e413a65cee12d5501680271b7d622a | wxmsummer/algorithm | /leetcode/hot/222_countNodes.py | 1,281 | 3.6875 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# 层序遍历,暴力法
def countNodes(self, root: TreeNode) -> int:
if not root:
return 0
stack = [root]
count = 0
while stack:
node = stack.pop()
count += 1
if node.left:
stack.append(node.left)
if node.right:
stack.append(node.right)
return count
# 复杂度 O(lgn*lgn)
def countNodes(self, root: TreeNode) -> int:
if not root:
return 0
left, right = root.left, root.right
left_depth, right = 0, 0
# 求左右子树深度
while left:
left = left.left
left_depth += 1
while right:
right = right.right
right += 1
# 如果遇到满二叉树
if left_depth == right:
return (2 << left_depth) - 1
# 如果不为满二叉树,则节点数量为左子树数量加右子树数量加1,1为自身
return self.countNodes(root.left) + self.countNodes(root.right) + 1
|
eeeace6a1d48324c28845d51b89535f2527a72e2 | wxmsummer/algorithm | /leetcode/hot/77_combine.py | 742 | 3.75 | 4 | # 组合
class Solution:
def combine(self, n: int, k: int) -> list:
# 回溯法,idx为当前元素,cur为当前解
def backtrack(idx, cur):
# 如果当前解符合要求,就加入解集
if len(cur) == k:
res.append(cur[:])
# 遍历当前位置后面的元素
for i in range(idx, n+1):
print('cur:', cur)
cur.append(i)
# 开启下一层判断
backtrack(i+1, cur)
# 回溯
cur.pop()
res = []
# 注意这里是从1开始
backtrack(1, [])
return res
if __name__ == '__main__':
obj = Solution()
print(obj.combine(4, 3)) |
8c80e03f0044efa8379d202302807430cb5b5ee4 | wxmsummer/algorithm | /leetcode/hot/49_groupAnagrams.py | 658 | 3.703125 | 4 | # 字母异位词分组
class Solution:
# 将单词转换为列表后按字典序排序
# 使用dic保存分组
def groupAnagrams(self, strs:list) -> list:
dic = {}
length = len(strs)
for i in range(length):
l = list(strs[i])
l.sort()
s = ''.join(l)
if s in dic:
dic[s].append(strs[i])
else:
dic[s] = [strs[i]]
res =[]
for val in dic.values():
res.append(val)
return res
if __name__ == '__main__':
obj = Solution()
print(obj.groupAnagrams(["eat", "tea", "tan", "ate", "nat", "bat"]))
|
6d655a04136f2a2bf3f4ad5c6726e6c3cf886d5d | wxmsummer/algorithm | /leetcode/hot/383_ransom.py | 386 | 3.515625 | 4 | ransomNote = input()
magazine = input()
list_1 = list(ransomNote)
list_2 = list(magazine)
for i in range(len(list_1)):
print(list_1)
print(list_2)
if list_1[0] not in list_2:
print(0)
break
else:
list_2.remove(list_1[0])
del list_1[0]
continue
print(1)
# return not collections.Counter(ransomNote) - collections.Counter(magazine) |
c9941ccd8853940bc4b9f64f26c4783755349de7 | wxmsummer/algorithm | /leetcode/offer/offer56-1_singleNumber.py | 217 | 3.578125 | 4 | # 只出现一次的数字
class Solution:
def singleNumbers(self, nums: List[int]) -> int:
single_number = 0
for num in nums:
single_number ^= num
return single_number
|
2cb11923ce346d66cf554b7556592494c52b2d05 | wxmsummer/algorithm | /leetcode/hot/139_wordBreak.py | 1,038 | 3.5625 | 4 | class Solution:
# 记忆化递归
# @functools.lru_cache(None) 禁止开启lru缓存机制
def wordBreak(self, s: str, wordDict: list) -> bool:
import functools
@functools.lru_cache(None)
def backTrack(s):
if not s:
return True
res = False
for i in range(1, len(s)+1):
if s[:i] in wordDict:
res = backTrack(s[i:]) or res
return res
return backTrack(s)
# 动态规划
# dp[i]表示以i结尾的字串是否已经匹配
# s[i:j]表示以i开头,以j结尾的字串
def wordBreak(self, s: str, wordDict: list) -> bool:
n = len(s)
dp = [False] * (n+1)
dp[0] = True
for i in range(n):
for j in range(i+1, n+1):
if dp[i] and (s[i:j] in wordDict):
dp[j] = True
return dp[-1]
if __name__ == '__main__':
obj = Solution()
print(obj.wordBreak(s = "leetcode", wordDict = ["leet", "code"])) |
8dd9a081d4078f7161cf36acf76d189d5afb2688 | wxmsummer/algorithm | /leetcode/hot/22-2_generateParenthesis.py | 2,096 | 3.5 | 4 | class Solution():
def generateParenthesis(self, n:int) -> list:
res, tmp = [], []
# left_num 表示还能放多少个左括号, right_num 表示还能放多少右括号
def backtrack(left_num1, right_num1, left_num2, right_num2):
print('tmp:', tmp)
# 如果左括号和右括号都放完了,说明这一轮回溯完成,将结果加入结果集
if left_num1 == 0 and right_num1 == 0 and left_num2 == 0 and right_num2 == 0:
res.append(''.join(tmp))
# 左括号可以随意放,只要数量大于0
if left_num1 > 0:
tmp.append('(')
# 放了左括号之后,回溯,左括号可放数量减一
backtrack(left_num1-1, right_num1, left_num2, right_num2)
# 回溯后恢复上一状态
tmp.pop()
if left_num2 > 0:
tmp.append('[')
# 放了左括号之后,回溯,左括号可放数量减一
backtrack(left_num1, right_num1, left_num2-1, right_num2)
# 回溯后恢复上一状态
tmp.pop()
# 右括号可放的数量必须大于左括号可放的数量,即必须先放了左括号才能放右括号
if left_num1 < right_num1:
tmp.append(')')
# 回溯,右括号可放数量减一
backtrack(left_num1, right_num1-1, left_num2, right_num2)
# 恢复回溯前状态
tmp.pop()
# 右括号可放的数量必须大于左括号可放的数量,即必须先放了左括号才能放右括号
if left_num2 < right_num2:
tmp.append(']')
# 回溯,右括号可放数量减一
backtrack(left_num1, right_num1, left_num2, right_num2-1)
# 恢复回溯前状态
tmp.pop()
backtrack(n, n, n, n)
return res
if __name__ == '__main__':
obj = Solution()
print(obj.generateParenthesis(1)) |
f944157689453208684072deb6b5f99a7ddff703 | wxmsummer/algorithm | /leetcode/hot/90_subsWithDup.py | 586 | 3.65625 | 4 | # 求子集2
# nums可能包含重复元素
class Solution:
def subsetsWithDup(self, nums: list) -> list:
def backTrack(start, tmp):
res.append(tmp[:])
for i in range(start, len(nums)):
if i > start and nums[i] == nums[i-1]:
continue
tmp.append(nums[i])
backTrack(i+1, tmp)
tmp.pop()
nums.sort()
res = []
backTrack(0, [])
return res
if __name__ == '__main__':
obj = Solution()
print(obj.subsetsWithDup([1,2,2,2,2])) |
35b2f4d82df46090bec5b965bf24f1c21454834b | wxmsummer/algorithm | /leetcode/hot/976_largestPerimeter.py | 768 | 3.859375 | 4 | # 三角形的最大周长
class Solution:
def largestPerimeter(self, nums: list) -> int:
if len(nums) < 3:
return 0
nums.sort()
length = len(nums)
i, j, k = length-3, length-2, length-1
while i >= 0:
if nums[i] + nums[j] > nums[k]:
return nums[i] + nums[j] + nums[k]
else:
i -= 1
j -= 1
k -= 1
if i < 0:
return 0
return 0
if __name__ == '__main__':
obj = Solution()
print(obj.largestPerimeter([1,1]))
print(obj.largestPerimeter([2,1,2]))
print(obj.largestPerimeter([1,2,1]))
print(obj.largestPerimeter([3,2,3,4]))
print(obj.largestPerimeter([3,6,2,3])) |
1349e81c63782210f997a14b8040f55228b3e6e8 | wxmsummer/algorithm | /leetcode/offer/offer21_exchange.py | 787 | 3.78125 | 4 | # 调整数组顺序使奇数位于偶数前面
# 两次遍历
class Solution:
def exchange(self, nums: list) -> list:
newList = []
for num in nums:
if num % 2 == 1:
newList.append(num)
for num in nums:
if num % 2 == 0:
newList.append(num)
return newList
# 原数组,直接交换,双指针
class Solution:
def exchange(self, nums: List[int]) -> List[int]:
i, j = 0, len(nums) - 1
while i < j:
while i < j and nums[i] & 1 == 1: i += 1
while i < j and nums[j] & 1 == 0: j -= 1
nums[i], nums[j] = nums[j], nums[i]
return nums
if __name__ == '__main__':
obj = Solution()
print(obj.exchange([1, 2, 3, 4])) |
38a37365f1df0a0e8911266f32d4482096c2789a | wxmsummer/algorithm | /leetcode/hot/12-2_romanToInt.py | 1,067 | 3.515625 | 4 | class Solution():
# 直接遍历,逐个翻译
def romanToInt(self, s:str) -> int:
# 由大到小构造罗马字字典
dic = {'M':1000, 'CM':900, 'D':500, 'CD':400, 'C':100, 'XC':90,
'L':50, 'XL':40, 'X':10, 'IX':9, 'V':5, 'IV':4, 'I':1}
tmp, res = '', 0
if not s:
return 0
i = 0
# 遍历字符串
while i < len(s):
# tmp表示可能构成的罗马字符,如果tmp不在字典中,则继续拼下一个罗马字符
if i < len(s) - 1:
# 往前预先判断是否能构成2字符罗马字
tmp = s[i] + s[i+1]
if tmp in dic:
res += dic[tmp]
# 构成两字符罗马字,i往前走2步
i += 2
tmp = ''
else:
res += dic[s[i]]
# 不是两字符罗马数字,i往前走1步
i += 1
return res
if __name__ == '__main__':
obj = Solution()
print(obj.romanToInt('IV')) |
4f2dc89118ac9811a7705b9e003ee484bb68b3ff | wxmsummer/algorithm | /leetcode/array/binary_search.py | 643 | 3.5625 | 4 |
class Solution:
def binary_search(self, nums:list, target:int):
i, j = 0, len(nums)
while i < j:
m = (i + j) // 2
if nums[m] >= target:
j = m
else:
i = m + 1
if i == len(nums):
return -1
return i
if __name__ == '__main__':
obj = Solution()
print(obj.binary_search([2,3,3,3,3,3], 3) )
# DPRC开发
# 讲项目,提高
# 细节,对项目的深入度
# go相关
# 比较深入的点,通信协议,分布式系统,稳定性,可拓展性
# 代码,逻辑需要更清晰,思路
# 知识储备,能力体现
|
b9498d588de3e9bf2cc8893544c744f29aa7d214 | wxmsummer/algorithm | /leetcode/offer/offer31_validateStackSequences.py | 942 | 3.734375 | 4 | # 栈的压入、弹出序列
class Solution:
def validateStackSequences(self, pushed: list, popped: list) -> bool:
newList = []
# 直接模拟,每次入栈后,循环判断栈顶元素是否等于弹出序列的当前元素,将符合弹出序列顺序的栈顶元素全部弹出。
for num in pushed:
newList.append(num)
while newList and newList[-1] == popped[0]:
del newList[-1]
del popped[0]
return popped == []
class Solution:
def validateStackSequences(self, pushed: list, popped: list) -> bool:
stack, i = [], 0
for num in pushed:
stack.append(num)
while stack and stack[-1] == popped[i]:
stack.pop()
i += 1
return not stack
if __name__ == '__main__':
obj = Solution()
print(obj.validateStackSequences([2, 1, 0], [1, 2, 0] )) |
9ae4eb3dde5360d1e3487db79a7cbb64fd97e2d6 | wxmsummer/algorithm | /leetcode/hot/73_setZeroes.py | 847 | 3.703125 | 4 | # 矩阵置零
class Solution:
def setZeroes(self, matrix: list) -> None:
row_len, col_len = len(matrix), len(matrix[0])
# 使用额外的两个行数组和列数组来存储行和列中的零信息
row_list = [1] * row_len
col_list = [1] * col_len
for i in range(row_len):
for j in range(col_len):
if matrix[i][j] == 0:
row_list[i] = 0
col_list[j] = 0
# 记录好零的数量之后,遍历置零
for i in range(row_len):
if row_list[i] == 0:
for j in range(col_len):
matrix[i][j] = 0
for j in range(col_len):
if col_list[j] == 0:
for i in range(row_len):
matrix[i][j] = 0
|
26edab3caee726fcd7a5e621c59c23a4b4409cbc | CcCc1996/myprogram | /2-oop/03.py | 2,142 | 3.5 | 4 | # -*- coding: utf-8 -*-
# Author: IMS2017-MJR
# Creation Date: 2019/4/23
# 多继承的例子
# 子类可以直接拥有父类的属性和方法,私有的属性和方法除外
class Bird():
def __init__(self, name):
self.name = name
def fly(self):
print("i can fly")
class Fish():
def __init__(self, name):
self.name = name
def swim(self):
print("i can swim")
class Person():
def __init__(self, name):
self.name = name
def work(self):
print("i can do work")
class SuperMan(Person, Bird, Fish):
def __init__(self, name):
self.name = name
s = SuperMan("cjx")
s.fly()
s.swim()
s.work()
# 单继承的例子
class Flog(Fish):
def __init__(self, name):
self.name = name
f = Flog("anran")
f.swim()
# 构造函数的补充
print("*" * 50)
class A():
def __init__(self, name):
print("A")
print(name)
class B(A):
def __init__(self, name):
A.__init__(self, name) # 首先调用父类构造函数,或也可以使用super实现
super(B, self).__init__(name)
print ("这是A的构造函数")
b = B("A的名字")
# Mixin案例
class Person():
def eat(self):
print("eat")
def sleep(self):
print("sleep")
class TeacherMixin(): # 在Mixin写法中,此处不需要添加父类,表示单一的功能
def work(self):
print("work")
class StudentMixin():
def study(self):
print("study")
class TutorM(Person, TeacherMixin, StudentMixin):
pass
tt = TutorM()
print(TutorM.__mro__)
# issubclass函数实例
print("*" * 50)
class A():
pass
class B(A):
pass
class C():
pass
print(issubclass(B, A))
print(issubclass(C, A))
print(issubclass(C, object))
# isinstance函数实例
print("*" * 50)
class A():
pass
a = A()
print(isinstance(a, A))
# hasattr函数实例
print("*" * 50)
class A():
name = "hahaha"
a = A()
print(hasattr(a, "name"))
print(hasattr(a, "age"))
# 使用和help查询setattr函数用法实例
print("*" * 50)
help(setattr)
class A():
name = "hahaha"
setattr(A, "name", "我的名字是cjx")
a = A()
print(a.name) |
fe10575d95d37269565d10c9ee8ebe343edbb7b6 | francisco0522/holbertonschool-interview | /0x00-lockboxes/0-lockboxes.py | 531 | 3.796875 | 4 | #!/usr/bin/python3
""" Lockboxes """
def canUnlockAll(boxes):
"""
method that determines if all the boxes can be opened
"""
if not boxes:
return False
opened = {}
queue = [0]
while queue:
boxNum = queue.pop(0)
opened[boxNum] = 1
for key in boxes[boxNum]:
if key >= 0 and key < len(boxes) and not opened.get(key)\
and (key not in queue):
queue.append(key)
return True if (len(opened) == len(boxes)) else False
|
e4eab633f19ee8cdc500a7c8b48c8b2f7ace9fce | mp360/manitab | /scaleCan.py | 3,996 | 3.578125 | 4 | # from Tkinter import *
# # a subclass of Canvas for dealing with resizing of windows
# class ResizingCanvas(Canvas):
# def __init__(self,parent,**kwargs):
# Canvas.__init__(self,parent,**kwargs)
# self.bind("<Configure>", self.on_resize)
# self.height = self.winfo_reqheight()
# self.width = self.winfo_reqwidth()
# def on_resize(self,event):
# # determine the ratio of old width/height to new width/height
# wscale = float(event.width)/self.width
# hscale = float(event.height)/self.height
# self.width = event.width
# self.height = event.height
# # resize the canvas
# self.config(width=self.width, height=self.height)
# # rescale all the objects tagged with the "all" tag
# self.scale("all",0,0,wscale,hscale)
# def main():
# root = Tk()
# myframe = Frame(root)
# myframe.pack(fill=BOTH, expand=YES)
# mycanvas = ResizingCanvas(myframe,width=850, height=400, bg="red", highlightthickness=0)
# mycanvas.pack(fill=BOTH, expand=YES)
# # add some widgets to the canvas
# mycanvas.create_line(0, 0, 200, 100)
# mycanvas.create_line(0, 100, 200, 0, fill="red", dash=(4, 4))
# mycanvas.create_rectangle(50, 25, 150, 75, fill="blue")
# # tag all of the drawn widgets
# mycanvas.addtag_all("all")
# root.mainloop()
# if __name__ == "__main__":
# main()
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider, Button
def inputExplorer(f, sliders_properties, wait_for_validation = False):
""" A light GUI to manually explore and tune the outputs of
a function.
slider_properties is a list of dicts (arguments for Slider )
whose keys are in ( label, valmin, valmax, valinit=0.5,
valfmt='%1.2f', closedmin=True, closedmax=True, slidermin=None,
slidermax=None, dragging=True)
def volume(x,y,z):
return x*y*z
intervals = [ { 'label' : 'width', 'valmin': 1 , 'valmax': 5 },
{ 'label' : 'height', 'valmin': 1 , 'valmax': 5 },
{ 'label' : 'depth', 'valmin': 1 , 'valmax': 5 } ]
inputExplorer(volume,intervals)
"""
nVars = len(sliders_properties)
slider_width = 1.0/nVars
print slider_width
# CREATE THE CANVAS
figure,ax = plt.subplots(1)
figure.canvas.set_window_title( "Inputs for '%s'"%(f.func_name) )
# choose an appropriate height
width,height = figure.get_size_inches()
height = min(0.5*nVars,8)
figure.set_size_inches(width,height,forward = True)
# hide the axis
ax.set_frame_on(False)
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)
# CREATE THE SLIDERS
sliders = []
for i, properties in enumerate(sliders_properties):
ax = plt.axes([0.1 , 0.95-0.9*(i+1)*slider_width,
0.8 , 0.8* slider_width])
sliders.append( Slider(ax=ax, **properties) )
# CREATE THE CALLBACK FUNCTIONS
def on_changed(event) :
res = f(*(s.val for s in sliders))
if res is not None:
print res
def on_key_press(event):
if event.key is 'enter':
on_changed(event)
# figure.canvas.mpl_connect('key_press_event', on_key_press)
# AUTOMATIC UPDATE ?
if not wait_for_validation:
for s in sliders :
s.on_changed(on_changed)
# DISPLAY THE SLIDERS
plt.show()
import matplotlib.pyplot as plt
import numpy as np
from scipy.integrate import odeint
def model(state,t, a,b,c,d):
x,y = state
return [ x*(a-b*y) , -y*(c - d*x) ]
ts = np.linspace(0,10,500)
fig,ax = plt.subplots(1)
def plotDynamics(x0,y0,a,b,c,d):
ax.clear()
ax.plot(ts, odeint(model, [x0,y0], ts, args = (a,b,c,d)) )
fig.canvas.draw()
sliders = [ { 'label' : label, 'valmin': 1 , 'valmax': 5 }
for label in [ 'x0','y0','a','b','c','d' ] ]
inputExplorer(plotDynamics,sliders)
|
b78ca51e2461286da4cfbb8f16610217e3db01dc | raseribanez/Youtube-Tutorials--Python-Basics--Wordlist-Generators | /wordlist_very_basic_nonrepeat.py | 177 | 3.953125 | 4 | # Ben Woodfield
# This basic list generator DOES NOT repeat characters in each result
import itertools
res = itertools.permutations('abc',3)
for i in res:
print ''.join(i)
|
c22b162d749ad8db0d4e74228899c6a7f94e56ec | comalvirdi/CPE101 | /LAB8/list_comp/funcs_objects.py | 377 | 3.8125 | 4 | # LAB 8
# COMAL VIRDI
# EINAKIAN
# SECTION 01
from objects import *
import math
# calculates the euclidian distance between two point objects
# Object Object --> int
def distance(p1,p2):
return math.sqrt(((p1.x-p2.x)**2)+((p1.y-p2.y)**2))
def circles_overlap(c1, c2):
sumRadii = c1.radius + c2.radius
distanceCP = distance(c1.center, c2.center)
return (sumRadii>distanceCP)
|
354d51e1558a6e332bf82000e9d874b3d6c87b4b | comalvirdi/CPE101 | /LAB3/logic.py | 351 | 4 | 4 | # LAB 3
# Name: Comal Virdi
# Instructor: S. Einakian
# Section: 01
# Determines whether or not an int is even
# int --> bool
def is_even(num):
return (num % 2 == 0)
#Determines whether or not a number falls within certain intervals
#float --> bool
def in_an_interval(num):
return (-2 <= num < 9 or 22 < num < 42 or 12 < num <= 20 or 120 <= num <= 127)
|
53da6c914c6b7139abf47e3b214b47725e93c50b | comalvirdi/CPE101 | /LAB4/loops/cubesTable.py | 1,518 | 4.3125 | 4 | # CPE 101 Lab 4
# Name:
def main():
table_size = get_table_size()
while table_size != 0:
first = get_first()
increment = get_increment()
show_table(table_size, first, increment)
table_size = get_table_size()
# Obtain a valid table size from the user
def get_table_size():
size = int(input("Enter number of rows in table (0 to end): "))
while (size) < 0:
print ("Size must be non-negative.")
size = int(input("Enter number of rows in table (0 to end): "))
return size;
# Obtain the first table entry from the user
def get_first():
first = int(input("Enter the value of the first number in the table: "))
while (first) < 0:
print ("First number must be non-negative.")
first = int(input("Enter the value of the first number in the table: "))
return first;
def get_increment():
increment = int(input("Enter the increment between rows: "))
while (increment) < 0:
print ("Increment must be non-negative.")
increment = int(input("Enter the increment between rows: "))
return increment;
# Display the table of cubes
def show_table(size, first, increment):
print ("A cube table of size %d will appear here starting with %d." % (size, first))
print ("Number Cube")
sum = 0
for num in range (first, first+ size * increment, increment):
print ("{0:<7} {1:<4}" .format(num, num**3))
sum += num**3
print ("\nThe sum of cubes is:", sum, "\n")
if __name__ == "__main__":
main() |
8b1b6df83a10e673536f70ac0e157b349269e975 | yanitsa-m/udemy-ML-AZ | /reinforcement_learning/upper_confidence_bound.py | 1,374 | 3.609375 | 4 | # Upper Confidence Bound (UCB) in Python
# Reinforcement learning algorithm
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import math
# Importing the dataset
dataset = pd.read_csv('Ads_CTR_Optimisation.csv')
# Implementing UCB algorithm for advertisements data
N = 10000
d = 10
ads_selected = []
num_selections = [0] * d
sums_of_rewards = [0] * d
total_reward = 0
# compute average reward and confidence interval at each round N
# see which ad is selected as N gets close to 10000
for n in range(0, N):
ad = 0
max_upper_bound = 0
for i in range(0, d):
if (num_selections[i] > 0):
avg_reward = sums_of_rewards[i] / num_selections[i]
delta_i = math.sqrt(3/2 * math.log(n + 1) / num_selections[i])
upper_bound = avg_reward + delta_i
else:
upper_bound = 1e400
if upper_bound > max_upper_bound:
max_upper_bound = upper_bound
ad = i
ads_selected.append(ad)
num_selections[ad] = num_selections[ad] + 1
reward = dataset.values[n,ad]
sums_of_rewards[ad] = sums_of_rewards[ad] + reward
total_reward = total_reward + reward
# Visualizing the histogram for ads selected results
plt.hist(ads_selected)
plt.title('Histogram of Ads Selections - UCB')
plt.xlabel('Ads')
plt.ylabel('Number of times selected')
plt.show() |
f46f987cb4948763de2c63a6ad33ffddbe2ef8dd | yanitsa-m/udemy-ML-AZ | /regression/multiple_linear_reg.py | 2,557 | 3.921875 | 4 | """
Multiple Regression model in Python
"""
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Importing dataset - set up wd
dataset = pd.read_csv('50_Startups.csv')
X = dataset.iloc[:, :-1].values
Y = dataset.iloc[:, -1].values
# Encoding categorical data
# Encoding the Independent Variable
from sklearn.preprocessing import LabelEncoder, OneHotEncoder
labelencoder_X = LabelEncoder()
X[:, 3] = labelencoder_X.fit_transform(X[:, 3])
onehotencoder = OneHotEncoder(categorical_features = [3])
X = onehotencoder.fit_transform(X).toarray()
# Avoid dummy variable trap
X = X[:, 1:]
# Split data into training set and test set
from sklearn.cross_validation import train_test_split
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size =0.2, random_state = 0)
# Feature scaling (-1, +1) range for values
"""from sklearn.preprocessing import StandardScaler
scale_X = StandardScaler()
X_train = scale_X.fit_transform(X_train)
X_test = scale_X.transform(X_test)
scale_Y = StandardScaler()
Y_train = scale_Y.fit_transform(Y_train)
"""
# Fitting Multiple Linear Regression to train set
from sklearn.linear_model import LinearRegression
regressor = LinearRegression()
regressor.fit(X_train, Y_train)
# Predicting the test set results
y_pred = regressor.predict(X_test)
# Backward elimination to build an optimal model
# - eliminate not statistically significant IVs
# compute p-values and eliminate variables that are not stat. significant
import statsmodels.formula.api as sm
# add column of ones at beginning of matrix of features
# - lib doesn't take into account b0 constant
# (b_0*x_0 part of formula)
X = np.append( arr = np.ones((50,1)).astype(int), values = X, axis = 1)
# only contains stat. significant independent variables
X_optimal = X[:, [0,1,2,3,4,5]]
# create new model - ordinary least squares
regressor_ols = sm.OLS(endog = Y, exog = X_optimal).fit()
# examine statistical metrics to get p-values
# eliminate variables with p-value > 0.05
regressor_ols.summary()
X_optimal = X[:, [0,1,3,4,5]]
regressor_ols = sm.OLS(endog = Y, exog = X_optimal).fit()
regressor_ols.summary()
X_optimal = X[:, [0,3,4,5]]
regressor_ols = sm.OLS(endog = Y, exog = X_optimal).fit()
regressor_ols.summary()
X_optimal = X[:, [0,3,5]]
regressor_ols = sm.OLS(endog = Y, exog = X_optimal).fit()
regressor_ols.summary()
X_optimal = X[:, [0,3]]
regressor_ols = sm.OLS(endog = Y, exog = X_optimal).fit()
regressor_ols.summary()
|
94288149957696b01230c9cba3ae8c3c8257491e | gpapalois/ergasies-examinou | /exercise12 .py | 215 | 3.90625 | 4 | file = input("Δώσε ένα αρχείο ascii.")
for i in range(len(file)):
letter = file[len(file)-i -1]
number = ord(letter)
number2 = 128 - number
ascii = chr(number2)
print(ascii ,end ="") |
5c025aa292e6e3bd670d99670a744324cdc6e463 | monicarico-210/clase28febrero | /first.py | 281 | 3.9375 | 4 | print ("hola")
a=2+3j
b=1+1j
c=a*b
print(c)
x=2
print(x)
x=1.6
print(x)
print(a, b, sep="...")
print(a, b, sep="")
x=float(input("entre el valor para x: "))
print(3*x)
d=5
e=2
f=d/e
print (f)
h=d//e
print (h)
if x == d:
print("iguales")
if x > d or x < e:
print("son iguales")
|
74973b79560175b3bc94bafe84051865ff9f3a53 | ricardocodem/py-regex-exm | /ex3_findall_nome_idade.py | 301 | 3.671875 | 4 | #setup
import re
#entrada
texto = '''
Michelle tem 20 anos a sua irmã Monique tem 22 anos.
José, o avô delas, tem 77 anos e mora no apto 17.'''
#buscando idades
idades = re.findall(r"[0-9]{1,2}\s[a-z]+",texto)
print(idades)
#buscando nomes
nomes = re.findall(r"[A-Z][a-z]+\w",texto)
print(nomes) |
3000fd6a5f68d7f3ed0ae6fdeedf7421775e580a | CEASLIBRARY/Intermediate_Python | /MyPackage/uc_student.py | 1,303 | 3.921875 | 4 | # Fuction to get the first anme, last name and year of birth of a person
def demographics():
first_name = input('What is your First Name: ')
last_name = input('What is your Last Name: ')
year_of_birth = input('What is your Year of Birth: ')
return [first_name, last_name, year_of_birth]
# Fuction to return he six plus two
def uc_6_2(first_name, last_name):
if (len(last_name)>=6):
sixplus2 = last_name[0:6] + first_name[0] + first_name[-1]
else:
sixplus2 = last_name + first_name[0:(6-len(last_name)+1)] + first_name[-1]
return(sixplus2.lower())
# Student class definition
class Student:
student_count = 0
# initialisation method
def __init__(self, first_name, last_name, year_of_birth):
self.first_name = first_name
self.last_name = last_name
self.year_of_birth = year_of_birth
Student.student_count = Student.student_count + 1
self.num = Student.student_count # Save for creation of student number
# Method to return student number (year of birth + count)
def student_number(self):
return self.year_of_birth + str(self.num)
# Metod to return student UC six plus two
def student_id(self):
return uc_6_2(self.first_name, self.last_name)
|
3aa0b1d11997bdd1e2e305532851d37a490e7f87 | IvTema/Python-Programming | /lesson1.12_step7.py | 205 | 3.578125 | 4 | # https://stepik.org/lesson/5047/step/7?unit=1086
a = (input())
if (int(a[0])+int(a[1])+int(a[2])) == (int(a[-1])+int(a[-2])+int(a[-3])):
print("Счастливый")
else:
print("Обычный") |
115c5c1ae4b9ed7f13f7f974a27afa20fc1819d0 | IvTema/Python-Programming | /lesson2.1_step12.py | 141 | 3.5 | 4 | # https://stepik.org/lesson/3364/step/12?unit=947
a = int(input())
b = int(input())
c = 1
while c % a != 0 or c % b != 0:
c += 1
print(c) |
6a923de7af4f2325e939b02b4ec10118b0837170 | davidwilson826/TestRepository | /Challenge1.py | 300 | 3.65625 | 4 | done = "false"
cubes = [1]
sums = [1]
currentnum = 2
while done == "false":
cubes = cubes+currentnum**3
sums = sums+[x+currentnum**3 for x in cubes]
for x in sums.sort():
if sums.count(x) > 1 and done == "false":
print(x)
done = "true"
currentnum += 1 |
0edfe376bcc39c00986bae6a1016660ec1caec99 | robocvi/2021-1-Computacion-Distribuida- | /Practica00/src/Grafica.py | 1,596 | 3.953125 | 4 | #Computación Distribuida: Práctica 0
#Integrantes: Ocampo Villegas Roberto 316293336
# David Alvarado Torres 316167613
#Clase Gráfica, la cual contendra nuestra implementación de una Gráfica, los detalles
#de la implementación se encuentran en el readme.
class Grafica():
numVertices = 0
listaVertices = []
#Constructor de nuestra gráfica, le pasaremos el numero de vértices que tendrá
#la gráfica.
def __init__(self, n):
self.numVertices = n
i = 0
while i < n:
self.listaVertices.append([])
i += 1
#Agrega una arista nueva a la gráfica, recibe los dos vértices que se uniran.
def agregaArista(self, v1, v2):
self.listaVertices[v1].append(v2)
self.listaVertices[v2].append(v1)
#Nuestra implmentacion de BFS, recibe a la gráfica y el número del vértice del
#cual se va a empezar a recorrer la gráfica.
def bfs(g, n):
visitados = []
listaFinal = []
cola = []
for ver in g.listaVertices:
visitados.append(0)
visitados[n] = 1
cola.append(n)
while len(cola) != 0:
d = cola.pop(0)
listaFinal.append(d)
for elemento in g.listaVertices[d]:
if visitados[elemento] == 0:
visitados[elemento] = 1
cola.append(elemento)
print('La lista de vertices recorridos es: ')
print(listaFinal)
#Pequeño ejemplo el cual cuenta con 8 vértices.
g = Grafica(8)
g.agregaArista(0, 1);
g.agregaArista(0, 2);
g.agregaArista(1, 3);
g.agregaArista(1, 4);
g.agregaArista(2, 5);
g.agregaArista(2, 6);
g.agregaArista(6, 7);
bfs(g, 0)
|
e9cb86ab9b68ed4b6f0c061f48629cb0eb270316 | lguychard/loispy | /src/loispy/interpreter/procedure.py | 2,279 | 4.28125 | 4 | from environment import Environment
class Procedure(object):
"""
Represents a loisp procedure. A procedure encapsulates a body (sequence of
instructions) and a list of arguments. A procedure may be called: the body
of the procedure is evaluated in the context of an environment, and given
"""
def __init__(self, env, args, body, name=""):
"""
@param Environment env
@param list[str] args
@param function body
@param str name
"""
self.env = env
self.args = args
# Check now if the procedure has variable arguments
self.numargs = -1 if len(args) >= 1 and "..." in args[-1] else len(self.args)
if self.numargs == -1:
self.numpositional = len(self.args) -1
self.positional = self.args[:self.numpositional]
self.vararg = self.args[-1].replace("...", "")
self.body = body
self.name = name
def __call__(self, *argvals):
"""
'the procedure body for a compound procedure has already been analyzed,
so there is no need to do further analysis. Instead, we just call
the execution procedure for the body on the extended environment.'
[ABELSON et al., 1996]
"""
call_env = Environment(self.pack_args(argvals), self.env)
return self.body.__call__(call_env)
def pack_args(self, argvals):
"""
Return a dict mapping argument names to argument values at call time.
"""
if self.numargs == -1:
if len(argvals) <= self.numpositional:
raise Exception("Wrong number of arguments for '%s' (%d)" %
(self.name, len(argvals)))
_vars = dict(zip(self.positional, argvals[:self.numpositional]))
_vars.update({self.vararg : argvals[self.numpositional:]})
else:
if len(argvals) != self.numargs:
raise Exception("Wrong number of arguments for '%s' (%d)" %
(self.name, len(argvals)))
_vars = dict(zip(self.args, argvals))
return _vars
def __str__(self):
return "<Procedure %s>" % self.name if self.name else "<Procedure>"
def __repr__(self):
return self.__str__()
|
cf06a980834902dedeb9b90610423b373cb382cc | shahakshay11/Array-3 | /rotate_array_kplaces.py | 820 | 3.9375 | 4 | """
// Time Complexity : O(n) n is length of shorter array
// Space Complexity : O(1)
// Did this code successfully run on Leetcode : Yes
// Any problem you faced while coding this :
// Your code here along with comments explaining your approach
Algorithm Explanation
Reverse the array
Swap the elements from 0 to k-1
Swap the elements from k to end
"""
class Solution:
def rotate(self, nums: List[int], k: int) -> None:
def swap(i,j):
while i < j:
nums[i],nums[j] = nums[j],nums[i]
i+=1
j-=1
"""
Do not return anything, modify nums in-place instead.
"""
nums.reverse()
#swap elements from 0 to k-1
swap(0,k-1)
#swap the elements from k to end
swap(k,len(nums)-1) |
a4656e6ed4e97500a444824c2df8750cabc6fae2 | Heisenberg27074/Web-Scraping-with-Python3 | /urllibwork.py | 560 | 3.625 | 4 | @Imorting urllib modules
import urllib.request, urllib.parse, urllib.error
url=input('Enter')
#urllib.request() is used for requesting a URL and urlopen() for opening a new URL
#fhand is url handle here as in files it was file handle
#Here we do not write encode() as urllib.request.urlopen() does it automatically
fhand=urllib.request.urlopen(url)
#traversing through lines
for line in fhand :
#decode is used as the file we requested is coming fro outside the world
#strip() method to remove whitespaces from line
print(line.decode().strip())
|
2fa3fbd312b86064da4f77d85dd226575de9dcaf | Heisenberg27074/Web-Scraping-with-Python3 | /lists/maxmin.py | 724 | 4.3125 | 4 | #Rewrite the program that prompts the user for a list of
#numbers and prints out the maximum and minimum of the numbers at
#the end when the user enters “done”. Write the program to store the
#numbers the user enters in a list and use the max() and min() functions to
#compute the maximum and minimum numbers after the loop completes.
lst=list()
while(1):
snum=input("Enter a number")
if snum =='done': break
try:
num=float(snum)
lst.append(num)
except:print('Please enter a number not anything else!!!')
if len(lst)<1:print("There are no items to compare inside list, please enter some data")
else:
print('Maximum:',max(lst))
print('Minimum',min(lst))
|
2620b59600f82e82bdf14d2e8602c1a76c721659 | Heisenberg27074/Web-Scraping-with-Python3 | /diction/9.py | 253 | 3.53125 | 4 |
st=input('Enter anything u want to:')
di=dict()
for something in st:
#if something not in di:
# di[something]=1
#else:
# di[something]=di[something]+1
di[something]=di.get(something,0)+1
print(di)
|
356eff040a055c24f3b56603bcb7061b97f9f326 | Heisenberg27074/Web-Scraping-with-Python3 | /string/trawhile.py | 409 | 3.921875 | 4 | index=0
st='czeckoslowakia'
while index<len(st): #index<=len(st)-1 /same
# print(st[index])
index=index+1
#Write a while loop that starts at the last character in the
#string and works its way backwards to the first character in the string,
#printing each letter on a separate line, except backwards.
index=len(st)-1
while index>-1:
print(st[index])
index=index-1 |
c7a61e4190cec3569060c6d8b123e1181516fcb2 | Heisenberg27074/Web-Scraping-with-Python3 | /tuples/10.2.1.py | 869 | 3.875 | 4 | #Write a program to read through the mbox-short.txt and figure out the distribution by hour of the
# day for each of the messages. You can pull the hour out from the 'From ' line by finding the time
# and then splitting the string a second time using a colon.
#From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008
#Once you have accumulated the counts for each hour, print out the counts, sorted by hour as shown
# below.
wds=list()
di=dict()
fname=input("enter your file name:")
if len(fname)<1 : fname='mbox-short.txt'
fhand=open(fname)
for line in fhand:
words=line.split()
if len(words)<1 or words[0]!='From':
continue
else:
wds.append(words[5])
for w in wds:
pos=w.find(':')
hrs=w[pos-2:pos]
di[hrs]=di.get(hrs,0)+1
#print(di)
#sorting by keys
for k,v in sorted(di.items()):
print(k,v)
|
75a6883fb38db72e5775e46f6e94e49a3c4a9978 | dimitardanailov/google-python-class | /python-dict-file.py | 1,842 | 4.53125 | 5 | # https://developers.google.com/edu/python/dict-files#dict-hash-table
## Can build up a dict by starting with the empty dict {}
## and storing key / value pairs into the dict like this:
## dict[key] = value-for-that-key
dict = {}
dict['a'] = 'alpha'
dict['g'] = 'gamma'
dict['o'] = 'omega'
print dict ## {'a': 'alpha', 'o': 'omega', 'g': 'gamma'}
# Simple lookup, returns 'alpha'
print dict['a'] ## alpha
# Put new key / value into dict
dict['a'] = 6
print dict ## {'a': 6, 'o': 'omega', 'g': 'gamma'}
print 'a' in dict ## True
if 'z' in dict: print dict['z'] ## Avoid KeyError
## By default, iterating over a dict iterates over its keys
## Note that the keys are in a random order
for key in dict: print key ## prints a g o
## Exactly the same as above
for key in dict.keys(): print key
## Get the .keys list:
print dict.keys() ## ['a', 'o', 'g']
## Common case --loop over the keys in sorted order,
## accessing each key/value
for key in sorted(dict.keys()):
print key, dict[key]
## .items() is the dict expressed as (key, value) tuples
print dict.items() ## [('a', 6), ('o', 'omega'), ('g', 'gamma')]
## This loops syntax accesses the whole dict by looping
## over the .items() tuple list, accessing one (key, value)
## pair on each iteration.
for k, v in dict.items(): print k, ' > ', v
## a > 6
## o > omega
## g > gamma
## Dic formatting
hash = {}
hash['word'] = 'garfield'
hash['count'] = 42
# %d for int, %s for string
s = 'I want %(count)d copies of %(word)s' % hash
print s # I want 42 copies of garfield
## Del
var = 6
del var # var no more!
list = ['a', 'b', 'c', 'd']
del list[0] ## Delete first element
del list[-2:] ## Delete last two elements
print list ## ['b']
dict = { 'a': 1, 'b': 2, 'c': 3}
del dict['b'] ## Delete 'b' entry
print dict ## {'a': 1, 'c': 3} |
f47a6d7abe7ec178fa212157da6b64bb3b5dc084 | fdloopes/Praticas_Machine_Learning | /Python/Linear_Regression/multi_features/main.py | 3,485 | 3.953125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 4 00:50:26 2021
@author: fdlopes
This program aims to implement a linear regression in a set of property
price data by city, in order to be able to predict how much the value of
each property will be according to the size and number of rooms.
X(1) refers to the size of house in square feet
X(2) refers to the number of bedrooms
y refers to the profit, price of houses
"""
# imports
import numpy as np
import csv
import matplotlib.pyplot as plt
from functions import featureNormalize, costFunction, gradientDescent, normalEqn
# Load dataset
with open('dataset.csv',newline='') as f:
reader = csv.reader(f,delimiter=',')
data = list(reader)
# Initialization
X = np.array([np.array(data).transpose()[0],np.array(data).transpose()[1]])# Decompose the data array
y = np.array(data).transpose()[2] # Decompose the data array, get prices
m = y.size # Number of training examples
# Convert data to float
X = X.astype(np.float)
y = y.astype(np.float)
# Scale features and set them to zero mean
print('\nNormalizing Features ...\n')
[X, mu ,sigma] = featureNormalize(X)
X = [np.ones(m),X[0],X[1]]
## ================ Part 1: Gradient Descent ================
print('Running gradient descent ...\n')
# Choose some alpha value
alpha = 0.1
num_iters = 50
# Init Theta and Run Gradient Descent
theta = np.zeros(3)
# Run gradient descent
[theta, J_history] = gradientDescent(X, y, theta, alpha, num_iters)
# Plot the convergence graph
plt.rcParams['figure.figsize'] = (11,7)
plt.plot(range(J_history.size), J_history, c='b')
plt.xlabel('Number of iterations')
plt.ylabel('Cost J')
plt.show()
# Display gradient descent's result
print('Theta computed from gradient descent: \n')
print(theta)
print('\n')
# Estimate the price of a 1650 sq-ft, 3 bedrooms house
# Recall that the first column of X is all-ones. Thus, it does
# not need to be normalized.
price = 0 # You should change this
house = [1, 1650, 3]
house[1] = (house[1] - mu[0]) / sigma[0] # Features normalization
house[2] = (house[2] - mu[1]) / sigma[1] # Features normalization
price = np.dot(house,theta) # Prediction price
print('Predicted price of a 1650 sq-ft, 3 br house (using gradient descent):', price)
# ============================================================
# ================ Part 2: Normal Equations ================
print('\nSolving with normal equations...\n')
# Load dataset
with open('dataset.csv',newline='') as f:
reader = csv.reader(f,delimiter=',')
data = list(reader)
# Initialization
X = np.array([np.array(data).transpose()[0],np.array(data).transpose()[1]])# Decompose the data array
y = np.array(data).transpose()[2] # Decompose the data array, get prices
m = y.size # Number of training examples
# Convert data to float
X = X.astype(np.float)
y = y.astype(np.float)
# Add intercept term to X
X = np.stack([np.ones(m),X[0],X[1]])
# Calculate the parameters from the normal equation
theta = normalEqn(X, y)
# Display normal equation's result
print('Theta computed from the normal equations: \n')
print(theta)
print('\n')
# Estimate the price of a 1650 sq-ft, 3 br house
price = 0 # You should change this
house = [1, 1650, 3]
price = np.dot(house,theta) # Prediction price
print('Predicted price of a 1650 sq-ft, 3 br house (using normal equations):', price)
# ============================================================
|
eb3f91c0d395abf93d5c447b8883ab8e29ab4a80 | rupeshvins/Coursera-Machine-Learning-Python | /CSR ML/WEEK#2/Machine Learning Assignment#1/Python/ex1_multi.py | 2,808 | 3.59375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Jul 13 00:40:12 2018
@author: Mohammad Wasil Saleem
"""
import pandas as pd
import matplotlib.pyplot as plot
import numpy as np
import featureNormalize as fp
import gradientDescentMulti as gdm
import normalEqn as ne
# Getting the data and plotting it.
# x - profit
# y - population
URL = 'D:\ML\ML\CSR ML\WEEK#2\Machine Learning Assignment#1\Python\ex1data2.csv'
names = ['Size', 'NumberOfBedrooms', 'Price']
data = pd.read_csv(URL, names = names) # 97 X 3 row by column.
size = data['Size']
noOfVBedrooms = data['NumberOfBedrooms']
price = data['Price']
x = np.zeros((len(data),2))
x[:, 0] = size
x[:, 1] = noOfVBedrooms
y = np.zeros((len(data),1))
y[:,0] = price
m = len(y)
print('First 10 examples from the dataset: \n')
print(' x = ', x[0:10,:])
print(' y = ', y[0:10])
[X, mu, sigma] = fp.featureNormalize(x)
# increasing the shape, adding a column of ones to x
ones = np.ones((len(x),1))
X = np.hstack((ones, X))
#print(np.hstack((ones, X)))
# Gradient Descent
# 1) Try different values of alpha
# 2) prediction (With feature normalisation)
alpha = 0.009; #0.009, try 0.01, 0.009.
num_iters = 350;
# Init Theta and Run Gradient Descent
theta = np.zeros((3,1))
[theta, J_History] = gdm.gradientDescentMulti(X, y, theta, alpha, num_iters)
print('Values of theta:')
print(theta)
plot.plot(J_History)
plot.title('Convergence Graph')
plot.xlabel('No Of Iterations')
plot.ylabel('Cost J')
'''
iteration = np.zeros((num_iters, 1))
for i in range(num_iters):
iteration[i, :] = i
plot.plot(iteration, J_History)
'''
# Prediction
# Estimate the price of a 1650 sq-ft, 3 br house
# Recall that the first column of X is all-ones. Thus, it does not need to be normalized.
estimate = np.array([[1, 1650, 3]], dtype = np.float32)
estimate_norm = np.zeros((1, 3))
mu = np.mean(estimate)
sigma = np.std(estimate, ddof=1)
estimate_norm = (estimate - mu ) / sigma
estimate_norm = np.absolute(estimate_norm)
price = estimate_norm.dot(theta)
print('Predicted price of a 1650 sq-ft, 3 br house(using gradient descent)',price[0,0])
# Normal Equation
print('Solving with normal equation:')
# Again we need to load the data, since, X and y have normalised values of data(Above).
data = pd.read_csv(URL, names = names) # 97 X 3 row by column.
size = data['Size']
noOfVBedrooms = data['NumberOfBedrooms']
price = data['Price']
x = np.zeros((47,2))
x[:, 0] = size
x[:, 1] = noOfVBedrooms
y = np.zeros((47,1))
y[:,0] = price
theta = ne.NormalEquation(X, y)
print('Values of theta:')
print(theta)
estimate = np.array([[1, 1650, 3]], dtype = np.float32)
price = estimate_norm.dot(theta)
print('Predicted price of a 1650 sq-ft, 3 br house(using normal equations)', price[0,0])
|
978d281ef1061cfcb2afb78537b15b6f26553e03 | openGDA/gda-core | /uk.ac.gda.bimorph/scripts/bimorphtest/__init__.py | 668 | 3.78125 | 4 |
class Float(float):
"""Helper class for comparing calls with float arguments"""
def __new__(self, value, tol=1e-8):
return float.__new__(self, value)
def __init__(self, value, tol=1e-8):
float.__init__(self, value)
self.value = value
self.tol = tol
def __eq__(self, other):
if other is None: return False
if not isinstance(other, float): return False
return abs(other - self.value) < self.tol
def roughly(arg, tol=1e-8):
"""Create float(ish) objects for comparisons in tests"""
try:
return [roughly(i, tol) for i in arg]
except TypeError:
return Float(arg, tol=tol)
|
8c209d8fa3290af3dcbaf91942d376ded835706e | pbeth92/SSI | /prct06/multiplicar.py | 2,844 | 3.65625 | 4 | class Multiplicar():
def __init__(self, a1, a2, alg):
if self.check_bin(a1):
self.b1 = a1
self.b2 = a2
else:
self.b1 = self.convertir_binario(a1)
self.b2 = self.convertir_binario(a2)
print(self.b1)
print(self.b2)
self.a1 = self.transformar(self.b1)
self.a2 = self.transformar(self.b2)
if alg == 1:
self.m = [0, 0, 0, 1, 1, 0, 1, 1]
else:
self.m = [1, 0, 1, 0, 1, 0, 0, 1]
self.resultado = []
def check_bin(self, cadena, base=2):
try:
int(cadena, 2)
return True
except ValueError:
return False
def convertir_binario(self, num):
num = int(num, 16)
bits = bin(num)[2:]
result = self.fill_zeros(bits)
return result
def fill_zeros(self, bits):
while len(bits) % 8 != 0:
bits = '0' + bits
return bits
"""
Función transformar.
Covierte la cadena a una lista de enteros
"""
def transformar(self, cadena):
lista = []
for i in range(len(cadena)):
lista.append(int(cadena[i]))
return lista
"""
Función multiplicacion.
Realiza la multiplicación de bits
"""
def multiplicacion(self):
mv = self.a1
s_resul = []
b_sale = 0
for i in reversed(range(8)):
if b_sale == 1:
self.operar(mv)
if self.a2[i] == 1:
s_resul.append(mv[:])
b_sale = self.desplazar(mv)
self.result(s_resul)
"""
Función desplazar
desplaza los bits
"""
def desplazar(self, lista):
r = lista.pop(0)
lista.append(0)
return r
"""
Función operar
Realiza la operación de suma xor con el byte 'M' cuando se desplaza un '1'
"""
def operar(self, lista):
for i in range(len(lista)):
lista[i] = lista[i] ^ self.m[i]
"""
Función result
Suma los valores para obtener el resultado
"""
def result(self, lista):
if len(lista) == 0:
self.resultado = [0, 0, 0, 0, 0, 0, 0, 0]
else:
i = 1
self.resultado = lista[0]
while i < len(lista):
self.resultado = self.suma_xor(self.resultado, lista[i])
i += 1
def suma_xor(self, l1, l2):
for i in range(len(l1)):
l1[i] = l1[i] ^ l2[i]
return l1
def imprimir(self):
print('\nSalida:')
print(f'Primer byte: {self.b1}')
print(f'Segundo byte: {self.b2}')
print(f"Byte algoritmo: {''.join(map(str, self.m))}")
print(f"Multiplicación: {''.join(map(str, self.resultado))}")
|
767b0082ff51d6363ff88022e7debb5f943b6338 | pbeth92/SSI | /prct11/prct11.py | 567 | 3.609375 | 4 | """
Pablo Bethencourt Díaz
alu0100658705@ull.edu.es
Práctica 11: Implementar el cifrado de clave pública RSA.
"""
from rsa import RSA
def menu():
print("Algoritmo RSA. \n 1.Cifrar mensaje \n 2.Descifrar mensaje \n 3.Salir")
opc = input("Opción: ")
if opc == '1':
mensaje = input("\nIntroduzca el mensaje a cifrar: ")
cifrar = RSA(mensaje)
cifrar.cifrar_mensaje()
cifrar.imprimir()
elif opc == '2':
mensaje = input("Introduzca el mensaje a descifrar: ")
descifrar = RSA(mensaje)
descifrar.descifrar()
menu()
|
c7668e86b91ed2fbcaa51d0d4811ae448d0f2a14 | RobDBennett/DS-Unit-3-Sprint-1-Software-Engineering | /module4-software-testing-documentation-and-licensing/arithmetic.py | 1,941 | 4.21875 | 4 | #!/usr/bin/env python
# Create a class SimpleOperations which takes two arguements:
# 1. 'a' (an integer)
# 2. 'b' (an integer)
# Create methods for (a, b) which will:
# 1. Add
# 2. Subtract
# 3. Multiply
# 4. Divide
# Create a child class Complex which will inherit from SimpleOperations
# and take (a, b) as arguements (same as the former class).
# Create methods for (a, b) which will perform:
# 1. Exponentiation ('a' to the power of 'b')
# 2. Nth Root ('b'th root of 'a')
# Make sure each class/method includes a docstring
# Make sure entire script conforms to PEP8 guidelines
# Check your work by running the script
class SimpleOperations:
"""A constructor for simple math.
Parameters-
:var a: int
:var b: int
"""
def __init__(self, a, b) -> None:
self.a = a
self.b = b
def add(self):
return self.a + self.b
def subtract(self):
return self.a - self.b
def multiply(self):
return self.a * self.b
def divide(self):
if self.b == 0:
return f'Cannot divide by zero!'
else:
return self.a / self.b
class Complex(SimpleOperations):
"""A constructor for more complicated math.
:var a: int
:var b: int
"""
def __init__(self, a, b) -> None:
super().__init__(a, b)
def exponentiation(self):
return self.a ** self.b
def nth_root(self):
return round((self.a ** (1.0 / self.b)), 4)
if __name__ == "__main__":
print(SimpleOperations(3, 2).add())
print('-------------------')
print(SimpleOperations(3, 2).subtract())
print('-------------------')
print(SimpleOperations(3, 2).multiply())
print('-------------------')
print(SimpleOperations(3, 2).divide())
print('-------------------')
print(Complex(3, 2).exponentiation())
print('-------------------')
print(Complex(3, 2).nth_root())
print('-------------------')
|
26e6b4897c75fcc9aff4f845a5fc2a57a4983780 | ROOTBEER626/Tic-Tac-Toe | /FinalTTT.py | 10,308 | 3.8125 | 4 | import sys
import random
#This class will be placeholder for the board values
class mySquare():
EMPTY = ' '
X = 'X'
O = 'O'
#class to get the current player and positions
class Action:
def __init__(self, player, position):
self.player = player
self.position = position
def getPosition(self):
return self.position
def getPlayer(self):
return self.player
#represents the state of the game and handles the logic of the game
class State:
def __init__(self):
self.board = []
for i in range(9):
self.board.append(mySquare.EMPTY)#initilize the board to all empty
self.player = mySquare.X#initial player is X
self.playerToMove = mySquare.X#X is also first to move
self.score = 0#initilize score to 0
#gets the score of a board
def updateScore(self):
#for i in range(9):
#print("Board at: ", i , "is: ", self.board[i])
#Checks the rows
if ((self.board[0] == (self.board[1]) and self.board[1] == self.board[2] and self.board[0] != (mySquare.EMPTY)) or (self.board[3]==(self.board[4]) and self.board[4] == self.board[5] and self.board[3] != mySquare.EMPTY) or (self.board[6] == self.board[7] and self.board[7] == self.board[8] and self.board[6] != (mySquare.EMPTY))):
if self.playerToMove==(mySquare.X):
self.score=-1
else:
self.score=1
#checks the columns
elif ((self.board[0]==self.board[3] and self.board[3]==self.board[6] and self.board[0]!= (mySquare.EMPTY)) or (self.board[1]==(self.board[4]) and self.board[4]== self.board[7] and self.board[1]!=mySquare.EMPTY) or (self.board[2]==(self.board[5]) and self.board[5]==(self.board[8]) and self.board[2]!=(mySquare.EMPTY))):
if (self.playerToMove==(mySquare.X)):
self.score = -1
else:
self.score = 1
#checks the diagnols
elif ((self.board[0]==(self.board[4]) and self.board[4]==(self.board[8])and self.board[0]!=(mySquare.EMPTY)) or (self.board[2]==self.board[4] and self.board[4]==self.board[6] and self.board[2] !=(mySquare.EMPTY))):
if (self.playerToMove==(mySquare.X)):
self.score=-1
else:
self.score=1
elif (self.checkNoMoves):
self.score = 0
#just checks if the board is terminal with no winner but returns True or False instead of 0
def checkNoMoves(self):
for i in range(9):
if (self.board[i]==(mySquare.EMPTY)):
num +=1
if(num==0):
return True
return False
#gets the possible Actions for the X player
def getActions(self):
list = []
for i in range(9):
if (self.board[i]==(mySquare.EMPTY)):
list.append(Action(mySquare.X, i))
return list
#gets the possible Actions for the O player
def getActions1(self):
list = []
for i in range(9):
if (self.board[i] == (mySquare.EMPTY)):
list.append(Action(mySquare.O, i))
return list
def getScore(self):
return self.score
#given the action if it is the right position and is empty make the move
def getResults(self, action):
state = State()
for i in range(9):
if (i == action.getPosition() and state.board[i] == (mySquare.EMPTY)):
state.board[i] = action.getPlayer()
else:
state.board[i] = self.board[i]
if (action.getPlayer()==(mySquare.X)):
state.playerToMove = mySquare.O
else:
state.playerToMove = mySquare.X
state.updateScore()
return state
def isTerminal(self):
if (self.score == 1 or self.score == -1):
return True
num = 0
for i in range(9):
if (self.board[i]==(mySquare.EMPTY)):
num +=1
if(num==0):
return True
return False
def print(self):
s = "----\n"
s += "" + self.board[0] + "|" + self.board[1] + "|" + self.board[2] + "\n"
s += "-----\n"
s += "" + self.board[3] + "|" + self.board[4] + "|" + self.board[5] + "\n"
s += "-----\n"
s += "" + self.board[6] + "|" + self.board[7] + "|" + self.board[8] + "\n"
print(s)
class MiniMax:
def __init__(self):
self.numberOfStates = 0
self.usePruning = False
def MinValue(self, state, alpha, beta):
self.numberOfStates += 1
if (state.isTerminal()):
return state.getScore()
else:
v = float("inf")
for i in range(len(state.getActions1())):
v = min(v,self.MaxValue(state.getResults(state.getActions1()[i]),alpha, beta))
if (self.usePruning):
if (v<=alpha):
return v
beta = min(beta, v)
return v
def MinMax(self, state, usePruning):
self.usePruning = usePruning
self.numberOfState = 0
if (state.board[4] == mySquare.EMPTY):
return Action(mySquare.X, 4)
list1 = state.getActions()
key = []
value = []
for i in range(len(list1)):
v = self.MinValue(state.getResults(list1[i]), -sys.maxsize, sys.maxsize)
key.append(list1[i].getPosition())
value.append(v)
for j in range(len(key)):
flag = False
for k in range (len(key) - j - 1):
if (value[k] < value[k + 1]):
temp = value[k]
value[k] = value[k + 1]
value[k + 1] = temp
temp1 = key[k]
key[k] = key[k+1]
key[k+1] = temp1
flag = True
if (flag == False):
break
list_max = []
mark = 0
for i in range(len(key)):
if (value[0]==(value[i])):
list_max.append(key[i])
if (key[i]==4):
mark = i
r = random.randint(0, len(list_max)-1)
if (mark != 0):
r = mark
print("State space size: ", self.numberOfStates)
return Action(mySquare.X, list_max[r])
def MaxValue(self, state, alpha, beta):
self.numberOfStates += 1
if (state.isTerminal()):
return state.getScore()
else:
v = float("-inf")
for i in range(len(state.getActions())):
v = max(v, self.MinValue(state.getResults(state.getActions()[i]), alpha, beta))
if (self.usePruning):
if (v >= beta):
return v
alpha = max(alpha, v)
return v
if __name__ == '__main__':
print("The Squares are numbered as follows:")
print("1|2|3\n---\n4|5|6\n---\n7|8|9\n")
mark = False
print("Do you want to use pruning? 1=no, 2=yes ")
prune = (int)(input())
if prune == 2:
mark = True
print("Who should start? 1=you, 2=computer")
temp = (int)(input())
s = State()
s.print()
s.player = mySquare.X
if (temp == 1):
s.playerToMove = mySquare.O
else:
s.playerToMove = mySquare.X
while (True):
if (s.playerToMove == mySquare.X):
miniMax = MiniMax()
s = s.getResults(miniMax.MinMax(s, mark))
else:
print("Which square do you want to set? (1-9) ")
while(True):
temp = (int)(input())
if temp >= 1 and temp <= 9 and s.board[temp-1] == mySquare.EMPTY:
break
print("Please Enter a Valid Move")
a = Action(mySquare.O, temp -1)
s = s.getResults(a)
s.print()
if s.isTerminal():
break
print("Score is: ", s.score)
if (s.getScore()>0):
print("You Lose")
elif (s.getScore()< 0):
print("You win")
else: print("Draw") |
264890b97e175eefb09864a743fa924d8d8563a8 | TongyunHuang/LeetCode-Note | /Jan11.py | 2,520 | 3.5625 | 4 | # Jan 11
# 53. Maximum Subarray
def maxSubArray(nums):
"""
:type nums: List[int]
:rtype: int
"""
maxSum, maxIdx, arrSum, arrIdx = nums[0], 0, 0, 0
L = []
for i in range(len(nums)):
if i == 0:
L.append((0, nums[i]))
else:
newSum = L[i-1][1] + nums[i]
# new start
if nums[i] > newSum:
arrSum ,arrIdx = nums[i], i
L.append((arrIdx,arrSum))
# append the subarr
else:
arrSum, arrIdx = newSum, L[i-1][0]
L.append((L[i-1][0], arrSum))
if arrSum > maxSum:
maxSum, maxIdx = arrSum, arrIdx
return maxSum
# 58. Length of Last Word
def lengthOfLastWord( s):
"""
:type s: str
:rtype: int
"""
i = len(s)-1
length = 0
while i >= 0:
if s[i] != ' ':
length += 1
elif length != 0:
break
i -= 1
return length
# 66. Plus One
def plusOne( digits):
"""
:type digits: List[int]
:rtype: List[int]
"""
i = len(digits) -1
add = 1
while i >= 0:
if digits[i] + 1 == 10:
digits[i] = 0
if i == 0:
digits.insert(0,1)
else:
digits[i] = digits[i] +1
break
i -= 1
return digits
# 67. Add Binary
def addBinary( a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
carry = 0
result = ''
a, b = list(a), list(b)
while a or b or carry:
if a:
carry += int(a.pop())
if b:
carry += int(b.pop())
result += str(carry % 2)
carry //= 2
return result[::-1]
# 69. Sqrt(x)
def mySqrt( x):
"""
:type x: int
:rtype: int
"""
left, right = 0, x
res = 0
while right-left>1:
mid = (left + right)//2
if mid* mid < x:
left = mid
else:
right = mid
if right* right <= x:
return right
return left
# 70. Climbing Stair
def climbStairs(n):
"""
:type n: int
:rtype: int
"""
# (even ,odd)
L = []
for i in range(n):
if i == 0:
L.append((0,1))
else:
even = L[i-1][1]
odd = L[i-1][0] + L[i-1][1]
L.append((even, odd))
return L[-1][0] + L[-1][1]
# Test
test67 = addBinary('1010', '1011')
print('your answer:')
print(test67)
print('Compiler feedback:________')
assert(test67=='10101')
|
f7d2976af17d464b0ff2bf35afe67b1b49c712e3 | TongyunHuang/LeetCode-Note | /Jan18.py | 1,869 | 3.546875 | 4 | # 122. Best time to Buy and Sell Stocks
def maxProfit(prices):
"""
:type prices: List[int]
:rtype: int
"""
if len(prices) <= 0:
return 0
if len(prices) ==2:
if prices[1]-prices[0] >0:
return prices[1]-prices[0]
return 0
total = 0
localMin, localMax = prices[0], prices[0]
profit = 0
for i in range(1,len(prices)-1):
if prices[i]< prices[i-1] and prices[i] <= prices[i+1]:
localMin = prices[i]
if prices[i] > prices[i-1] and prices[i] >= prices[i+1] :
localMax = prices[i]
print("localMax = " + str(localMax) + "; localMin = " + str(localMin))
profit = localMax-localMin
print("---profit = " + str(profit))
if i== len(prices)-2 and prices[len(prices)-1] >= prices[i]:
localMax = prices[i+1]
print("localMax = " + str(localMax) + "; localMin = " + str(localMin))
profit = localMax-localMin
print("---profit = " + str(profit))
if profit >0:
total += profit
localMin = localMax
profit = 0
return total
# 125. isPalindrome
def isPalindrome(s):
"""
:type s: str
:rtype: bool
"""
i, j = 0, len(s)-1
while i <= j:
print("s[i] = "+ s[i] + "; s[j] = " + s[j])
if s[i].isalnum() and s[j].isalnum() :
print("both alpha s[i] = "+ s[i] + "; s[j] = " + s[j])
if s[i].lower() != s[j].lower():
return False
i += 1
j -= 1
elif s[i].isalnum():
j -= 1
elif s[j].isalnum():
i += 1
else:
i += 1
j -= 1
return True
# Test
test = isPalindrome(",,,,,,,,,,,,acva")
print('your answer:')
print(test)
print('Compiler feedback:________') |
45c0ab4712ef1601e7b7679fdc3ad638866415a7 | bps10/base | /files/files.py | 1,689 | 3.9375 | 4 | import glob as glob
import os
def getAllFiles(dirName, suffix = None, subdirectories = 1):
"""
Get a list of path names of all files in a directory.
:param Directory: a directory.
:type Directory: str
:param suffix: find only files with a specific ending.
:type suffix: str
:param subdirectories: indicate how deep (# of directories) you would \
like to search: 0 = working directory.
:type subdirectories: int
:returns: a list of path names.
:rtype: list
e.g. subdirectories = 1: Find all files within a directory and its
first layer of subdirectories.
"""
if suffix is None:
suffix = ''
depth = '/*'
for i in range(subdirectories):
depth += depth
f = dirName + depth + suffix
files = []
for name in glob.glob(f):
files.append(name)
return files
def make_dir(directory):
''' Check if a directory exists and make one if it does not'''
directory = os.path.dirname(directory)
if not os.path.exists(directory):
os.makedirs(directory)
# Below from PsychoPy library. Copyright (C) 2009 Jonathan Peirce
# Distributed under the terms of the GNU General Public License (GPL).
def toFile(filename, data):
"""
save data (of any sort) as a pickle file
simple wrapper of the cPickle module in core python
"""
f = open(filename, 'w')
cPickle.dump(data,f)
f.close()
def fromFile(filename):
"""
load data (of any sort) from a pickle file
simple wrapper of the cPickle module in core python
"""
f = open(filename)
contents = cPickle.load(f)
f.close()
return contents
|
5a937360687f171ef3081dbbc613ee4a9b7b7af0 | kaminosekai54/Modelisation-of-Interaction-of-O2-fish-aglae- | /functions.py | 3,516 | 3.90625 | 4 | # This file is composed of the usefull function
################################################
# import of the package
# for the mathematical computation
import numpy as np
# import for the plot
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import axes3d
# importing the odeint package to resolv our equation
from scipy.integrate import odeint
# function compute_derivative
# This function compute the derivative wanted to study the model
# @param
# @y0, a list containing the initial value for the variable of the model
# @t, a time , mostly useful for the odeint function
# @args, a list containing all the different the parameter of the model (rate, constant, etc, etc)
def compute_derivative(y0, t, args):
# initialising our value
# storing the different value of args into variables
# the variable are named according to their name in the equation
#they represent the different rates and constant
# defining our rate and constant
# alpha(fish groth rate), beta(algae rate groth), omax (max amount of o2)
alpha, beta, c, P, g, pmax, amax, omin, omax = args
# storing the different value of y into variables
# they are named according to their name into the equation
# they represent the different initial value for the model
# o (initial value of O2, p initial value of fish, a initial value of algae)
o, p, a = y0
# writing our derivative
dodt = (0.0001*o*(P * a - c*p))*(1-(o/omax))
# fo is a function of o and p we defined it to be 0 if the computation give us a result is >= 0 to make o2 have a negative influence only when its under a certain value
fo = ((o - p*c) - omin) / c
if fo >= 0 :
fo = 0
dpdt = (0.01*p*((alpha* p) * (1- (p/pmax)) + fo))
dadt = (beta * a) * (1- (a/amax)) - p*g*a
# return of the computed derivative in a list
return [dodt, dpdt, dadt]
# function draw_phase_space ,
# This function will draw a vector field representing our model
#@param,
#@y0, the list of initial value for the model (Usefull for the computations)
#@args, a list of parameter for the model (Usefull for the computation)
def draw_phase_space (y0, args):
# creating different vectors, representing our variables
t = np.linspace(1,200,10)
o_vector = np.linspace(1,200,10)
p_vector = np.linspace(1,200,10)
a_vector = np.linspace(1,200,10)
o_n,p_n,a_n = np.meshgrid(o_vector, p_vector, a_vector)
aux1 = np.zeros(o_n.shape)
aux2 = np.zeros(p_n.shape)
aux3 = np.zeros(a_n.shape)
# looping and computing our values for T = 0
for i in range (0,len(o_vector)):
for j in range (0,len(p_vector)):
for k in range (0,len(a_vector)):
dodt, dpdt, dadt = compute_derivative((o_vector[i], p_vector[j],a_vector[k]),0,args)
aux1[i,j,k] = dodt
aux2[i,j,k] = dpdt
aux3[i,j,k] = dadt
# creating the figure
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.invert_xaxis()
ax.quiver(o_n, p_n, a_n, aux1, aux2, aux3)
ax.set_xlabel("O2") # x label
ax.set_ylabel("Fish population") # y label
ax.set_zlabel("Algae population")
# solving our ODE using odeint
model = odeint(compute_derivative, y0, t, args = (args,))
ax.plot(model[:,0], model[:,1], model[:,2], 'r')
ax.set_xlabel("O2") # x label
ax.set_ylabel("Fish") # y label
ax.set_zlabel("Algae")
# showing the result
plt.show()
return "We liked this project" |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.