blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
3614f09c9a9c189e04eaddd259a306671d5e4835
netraf/skillbox-phyton
/10.py
187
3.515625
4
def salary(hour_cost, day_quantity): total = (hour_cost * 8) * day_quantity final = total - (total*.13) return final a = salary(600, 2) b = salary(1200, 6) print(a, b)
eee5215ed117d58ca22f9d58b4c19499a2443546
fagan2888/leetcode_solutions
/accepted/Median_of_Two_Sorted_Arrays.py
871
3.65625
4
## https://leetcode.com/problems/median-of-two-sorted-arrays/ ## almost feels like cheating since python's standard library ## provides a way to merge two sorted lists using heaps under ## the hood, so we do that then figure out where to index to ## get our median. ## comes in at 64th percentile in runtime and 61st percentile ## in memory class Solution: def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float: from heapq import merge merged = list(merge(nums1, nums2)) tot_len = len(merged) if tot_len % 2 == 0: ## even lengthed list; average of the two middle values idx = int(tot_len / 2) return (merged[idx]+merged[idx-1])/2.0 else: ## odd length list; just the middle value idx = int(tot_len / 2) return 1.0*merged[idx]
c885df85b495b97830552bd6fd1c7835523ef989
logancyang/lintcode
/biSearch/searchInsertPosition.py
1,091
4.09375
4
""" Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. You may assume NO duplicates in the array. Example [1,3,5,6], 5 -> 2 [1,3,5,6], 2 -> 1 [1,3,5,6], 7 -> 4 [1,3,5,6], 0 -> 0 """ class Solution: """ @param A : a list of integers @param target : an integer to be inserted @return : an integer """ def searchInsert(self, A, target): if A is None or len(A) == 0: return 0 if target > A[-1]: return len(A) start = 0 end = len(A) - 1 while start + 1 < end: mid = (start + end)/2 #print start, end, mid if A[mid] >= target: end = mid if A[mid] < target: start = mid #print start, end if A[start] >= target: return start if A[end] >= target: return end return A = [1,10,1001,201,1001,10001,10007] target = 10008 Sol = Solution() print Sol.searchInsert(A, target)
f3df13e8ea8e22ba3ab41ab851de12e81cc16088
wszy5/snake_game
/snake.py
1,581
3.6875
4
from turtle import Turtle UP = 90 DOWN = 270 RIGHT = 0 LEFT = 180 STARTING_POSITIONS = [(-20, 0), (-40, 0), (-60, 0)] class Snake: def __init__(self): self.turtles = [] self.create_snake() self.move() def create_snake(self): for position in STARTING_POSITIONS: self.add_segment(position) def add_segment(self, position): turtle = Turtle(shape="square") turtle.penup() turtle.color("white") turtle.goto(position) self.turtles.append(turtle) def extend(self): self.add_segment(self.turtles[-1].position()) def up(self): if self.turtles[0].heading() != DOWN: self.turtles[0].setheading(UP) self.move() def down(self): if self.turtles[0].heading() != UP: self.turtles[0].setheading(DOWN) self.move() def left(self): if self.turtles[0].heading() != RIGHT: self.turtles[0].setheading(LEFT) self.move() def right(self): if self.turtles[0].heading() != LEFT: self.turtles[0].setheading(RIGHT) self.move() def move(self): for seq_num in range(len(self.turtles) - 1, 0, -1): new_x = self.turtles[seq_num - 1].xcor() new_y = self.turtles[seq_num - 1].ycor() self.turtles[seq_num].goto(new_x, new_y) self.turtles[0].forward(20) def reset(self): for t in self.turtles: t.goto(x=1000, y=1000) self.turtles.clear() self.create_snake()
b23b7f7defeea82863198c9d7d4f09ce03625988
miri114/MyPyPrograms
/scoop.py
871
4.15625
4
class Scoop(): def __init__(self, flavor): self.flavor = flavor """ This function is to create and print instances of class scoop""" # def create_scoops(): # scoops = [Scoop('chocolate'), # Scoop('vanilla'), # Scoop('persimmon')] # # for scoop in scoops: # print(scoop.flavor) class Bowl(): max_scoops = 3 def __init__(self): self.scoops = [] def add_scoops(self, *new_scoops): for one_scoop in new_scoops: if len(self.scoops) < Bowl.max_scoops: self.scoops.append(one_scoop) def __repr__(self): return '\n'.join(s.flavor for s in self.scoops) s1 = Scoop('vanilla') s2 = Scoop('chocolate') s3 = Scoop('persimmon') s4 = Scoop('flavor4') s5 = Scoop('flavor5') b = Bowl() b.add_scoops(s1, s2) b.add_scoops(s3) b.add_scoops(s4, s5) print(b)
d7270da9e7e6154ca0b40aa16c44a2a6749a760a
therealmikkelw/automate-the-boring-stuff
/examples/writeExcel_example.py
631
3.75
4
import openpyxl, os # Using Workbook() method to create a new workbook object wb = openpyxl.Workbook() # List sheet names # wb.get_sheet_names() # Access sheet object sheet = wb['Sheet'] # .get_sheet_by_name('Sheet') # Assign values to cells sheet['A1'] = 42 sheet['A2'] = 'Hello' # Using create_sheet() to create a new sheet sheet2 = wb.create_sheet(index=0, title='My other sheet') # Rename the sheet using title method sheet2.title = 'My new sheet name' # Using save() method to store the workbook to harddrive os.chdir(r'C:\Users\mwj\Documents\Automate the boring stuff') wb.save('example.xlsx')
7f378b4f56867b9cfe8f6587ddb85409f01bfd6b
wangyiwen9956/ichw
/wcount.py
1,533
3.546875
4
#!/usr/bin/env python3 """wcount.py: count words from an Internet file. __author__ = "WangYiwen" __pkuid__ = "1700011805" __email__ = "wangyiwen@pku.edu.cn" """ import sys from urllib.request import urlopen def wcount(lines, topn=10): dic={} for i in """!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~""": lines2=lines.replace(i," ") lines=lines2 word_list=lines2.split() for word in word_list: word=word.lower() dic[word]=dic.get(word,0)+1 alist=list(dic.items()) all_times=[] for (word,times) in alist: all_times.append(times) all_times=list(set(all_times)) all_times.sort(reverse=True) for i in range(topn): for word in dic.keys(): if dic.get(word)==all_times[i]: print(word, "\t",dic.get(word)) if __name__ == '__main__': if len(sys.argv) == 1: print('Usage: {} url [topn]'.format(sys.argv[0])) print(' url: URL of the txt file to analyze ') print(' topn: how many (words count) to output. If not given, will output top 10 words') sys.exit(1) try: topn = 10 if len(sys.argv) == 3: topn = int(sys.argv[2]) except ValueError: print('{} is not a valid topn int number'.format(sys.argv[2])) sys.exit(1) try: with urlopen(sys.argv[1]) as f: contents = f.read() lines = contents.decode() wcount(lines, topn) except Exception as err: print(err) sys.exit(1)
41ced65cc4a2b0dce8e29947e10199bff086d970
ahadahmedkhan/Solution
/chapter6/ex 6.3.py
648
3.796875
4
glossary={ 'string':' A series of character.', 'comment':' A note in a program that the interpreter ignores.', 'list':' A collectiiion of item in a particular order.', 'loop':' Work through colection of items, one at a time.', 'dictionary':'A collection of key-value pair.', } word='string' print('\n'+word.title()+' : '+glossary['string']) word='comment' print('\n'+word.title()+' : '+glossary['comment']) word='list' print('\n'+word.title()+' : '+glossary['list']) word='loop' print('\n'+word.title()+' : '+glossary['loop']) word='dictionary' print('\n'+word.title()+' : '+glossary['dictionary'])
30dee2de70599c0c6aea3144e58a051fc02acdc1
prometheus61/lpthw
/ex5.py
622
3.84375
4
name = 'Zed A. Shaw' age = 35 # not a lie height = 74 # inches weight = 180 # lbs eyes = 'Blue' teeth = 'White' hair = 'Brown' print ("Let's talk about %(name)s. who is %(height)d inches tall" % ({'name':'Zed Shaw' , 'height':79})) print "He's %x inches tall." % height # hexadecimal values print "He's %o pounds heavy." % weight # octal value print "Actually that's not too heavy" print "He's got %s eyes and %s hair." %(eyes, hair) print "His teeth are usually %s depending on the coffee." % teeth # this line is tricky to get just right print "If I add %d, %d, and %d I get %d" %(age, height, weight, age + height + weight)
977323d5ae000f17564de518faefd9f5371eae80
shrenik77130/Repo5Batch22PythonWeb
/#8_PythonList/ListEx1.py
388
4.1875
4
#WAP to demonstrate Python List colors = ['red','orange','blue','white','black','blue'] print(colors) print("First Color = ",colors[0]) print("Second Color = ",colors[1]) print("Last Color = ",colors[-1]) print("First Two Colors :",colors[0:2]) #Ass: create list of numbers. and print last two numbers numbers = [10,20,30,40,50,60] print("Last two numbers = ",numbers[-2:])
0492d3c7fd7fec5725f9914d06e7eb0431773d79
daniel-reich/ubiquitous-fiesta
/nC7iHBbN8FEPy2EJ2_19.py
490
3.71875
4
class Rectangle: ​ def __init__(self, sideA=0, sideB=0): self.sideA = sideA self.sideB = sideB ​ def getArea(self): return self.sideA * self.sideB def getPerimeter(self): return 2 * (self.sideA + self.sideB) ​ class Circle: import math def __init__(self, radius): self.radius = radius def getArea(self): import math return math.pi * self.radius ** 2 def getPerimeter(self): import math return math.pi * 2 * self.radius
bf512b9bffdaaa3e61dbe674f05bfaaab92f7fdf
Sw4b3/DatabaseConnection
/DatabaseConnection/DatabaseConnection/DatabaseController.py
2,351
3.609375
4
import mysql.connector class DatabaseController(object): def getConnection(self): connection = mysql.connector.connect( host="localhost", user="root", passwd="", database="StudentDB" ) return connection def viewStudent(self): connection=self.getConnection() cursor = connection.cursor() cursor.execute("SELECT * FROM Students") result = cursor.fetchall() for x in result: print(x) def insertStudent(self): print("Enter First Name") name=input(); print("Enter Last Name") surname=input(); print("Enter Age Name") age=input(); print("Enter Course Name") course=input(); connection=self.getConnection() cursor = connection.cursor() sql = "INSERT INTO Students (studentName, studentSurname,studentAge, studentCourse) VALUES (%s, %s,%s,%s)" val = (name, surname,age,course) cursor.execute(sql, val) connection.commit() print(cursor.rowcount, "record inserted.") def updateStudent(self): print("Enter full name of student") fullname=input(); oldname,oldsurname=fullname.split(" ") print("Enter First Name") name=input(); print("Enter Last Name") surname=input(); print("Enter Age Name") age=input(); print("Enter Course Name") course=input(); connection=self.getConnection() cursor = connection.cursor() sql = "UPDATE Students SET studentName=%s, studentSurname=%s,studentAge=%s, studentCourse=%s WHERE studentName=%s AND studentSurname= %s" val = (name, surname,age,course,oldname,oldsurname) cursor.execute(sql, val) connection.commit() print(cursor.rowcount, "record inserted.") def deleteStudent(self): print("Enter full name of student") fullname=input(); name,surname=fullname.split(" ") connection=self.getConnection() cursor=connection.cursor(); sql="DELETE FROM students WHERE studentName=%s AND studentSurname= %s" val = (name, surname) cursor.execute(sql,val) connection.commit() print("Record deleted.")
72bc3701fa9389270beb3391f7b7270a7b012e1d
anantbarthwal/python_codes
/scope.py
72
3.515625
4
a=20 def sum(a): a=a+1 b=20 print(a) sum(a) print("a=",a)
42ba465fc5760c8ec85443ea1d48288fef9980fc
6660-Kp/cs1026
/ass2/main.py
5,283
3.9375
4
"""" Name: xinhe xia ASSIGNMENT 2 """ import volume #import a math function ac=[] #create a list name ac ap=[] #create a list name ap ae=[] #create a list name ae gg=1 while gg==1: #while gg is equal to 1 do the thing below x=input("hello i am a calculator that only can calculate volume for cube,pyramid,ellipsoid.\n"+"please enter the shape you want to calculate\n") while x.isalpha(): #while gg is equal to 1 do the thing below x=x.lower() #lower the letter if x=="c" or x=="cube": #determine if the input equal to the condition a=float(input("cube length")) #get a input from user ac.append(volume.cube(a)) #put the result to the list the calculation already down in volume.py ac.sort() #order the list x=input("what else shape that you want to calculate?\n") continue #continue the function elif x=="p" or x=="pyramid" : b=float(input("pyramid length ")) h=float(input("pyramid height ")) ap.append(volume.pyramid(b,h)) ap.sort() x=input("what else shape that you want to calculate?\n") continue elif x=="ellipsoid" or x=="e" : r1=float(input("radius1")) r2=float(input("radius2")) r3=float(input("radius3")) ae.append(volume.ellipsoid(r1,r2,r3)) ae.sort() x=input("what else shape that you want to calculate?\n") continue elif x=="q" or x=="quit": if len(ac)==0 and len(ap)==0 and len(ae)==0: print("you have reached the end of your session.\n"+"you did not perform and calculations") gg=gg+1 break #if equal break out of the loop elif len(ac)==0 and len(ap)==0: #check if ac and ap length are both 0 print("you have reached the end of your session.\n"+"the volume calculated for each shapes are: ") print("Cube :no shape entered") print("Pyramid :no shape entered") print("Ellipsoid :", end = " ") print(*ae, sep=',') #print list without [] gg=gg+1 break elif len(ae)==0 and len(ap)==0: print("you have reached the end of your session.\n"+"the volume calculated for each shapes are: ") print("Cube :", end = " ") print(*ac, sep=',') print("Pyramid :no shape entered") print("Ellipsoid :no shape entered") gg=gg+1 break elif len(ac)==0 and len(ae)==0: print("you have reached the end of your session.\n"+"the volume calculated for each shapes are: ") print("Cube :no shape entered") print("Pyramid : ", end = " ") print(*ap, sep=',') print("Ellipsoid :no shape entered") gg=gg+1 break elif len(ac)==0 : print("you have reached the end of your session.\n"+"the volume calculated for each shapes are: ") print("Cube :no shape entered") print("Pyramid : ", end = " ") print(*ap, sep=',') print("Ellipsoid :", end = " ") print(*ae, sep=',') gg=gg+1 break elif len(ae)==0 : print("you have reached the end of your session.\n"+"the volume calculated for each shapes are: ") print("Cube : ", end = " ") print(*ac, sep=',') print("Pyramid : ") print(*ap, sep=',') print("Ellipsoid :no shape entered") gg=gg+1 break elif len(ap)==0 : print("you have reached the end of your session.\n"+"the volume calculated for each shapes are: ") print("Cube : ", end = " ") print(*ac, sep=',') print("Pyramid :no shape entered") print("Ellipsoid :", end = " ") print(*ae, sep=',') gg=gg+1 break else: print("you have reached the end of your session.\n"+"the volume calculated for each shapes are: ") print("Cube : ", end = " ") print(*ac, sep=',') print("Pyramid : ", end = " ") print(*ap, sep=',') print("Ellipsoid :", end = " ") print(*ae, sep=',') gg=gg+1 break
ce798b1cf4dcd27d958da4941de35dbd23ea1aae
ajay-02/codevita_gamified
/level 3/fibonacci_tri.py
381
3.84375
4
def Hosoya( n,m): if((n==0 and m==0)or(n==1 and m==0)or(n==1 and m==1)or(n==2 and m==1)): return 1 if n>m: return Hosoya(n-1,m)+Hosoya(n-2,m) elif m==n: return Hosoya(n-1,m-1)+Hosoya(n-2,m-2) else: return 0 def printHosoya(n): for i in range(n): for j in range(i+1): print(Hosoya(i,j),end=" ") print("\n",end="") n=int(input()) printHosoya(n)
90e438c46ad170d15dd778eb7a629ca65887e1f6
felipevalentin/livraria
/livraria_classes.py
1,639
4
4
""" Classes para um sistema de biblioteca, podendo ser criado um usuário e 4 tipos de livros, sendo um deles chamado Generico que é utilizado como modelo para as heranças das outras 3 """ class Usuario: """ Cria um usuário com nome e senha pro sistema de livraria """ def __init__(self, nome, senha): self.nome = nome self.senha = senha def get_dados(self): """ Retorna os dados formatados para guardar em um texto """ return f"{self.nome}, {self.senha}" class Generico: """ Cria um livro generico, contendo nome, genero e preco, sendo genero e preco fixos """ def __init__(self, nome): self.nome = nome self.genero = "Genérico" self.preco = 30 def get_dados(self): """ Retorna os dados formatados para guardar em um texto """ return f"{self.nome}, {self.genero}" class Ficcao(Generico): """ Classe filha da classe generico, alterando os valores de genero e preco """ def __init__(self, nome): super().__init__(nome) self.genero = "Ficção" self.preco = 35 class NaoFiccao(Generico): """ Classe filha da classe generico, alterando os valores de genero e preco """ def __init__(self, nome): super().__init__(nome) self.genero = "Não Ficção" self.preco = 25 class Tecnico(Generico): """ Classe filha da classe generico, alterando os valores de genero e preco """ def __init__(self, nome): super().__init__(nome) self.genero = "Técnico" self.preco = 40
d4ab6d5c530c524ca378c4e3fe3337152e4decbf
iqballhafizi/pywinda
/ForDocumentation/docs/PyWinda/pywinda.py
21,312
3.625
4
import numpy as np import pandas as pd def cAngle(i): x=i % 360 return x class environment: """ Creates the stand-alone environment with the given unique ID. Some generic conditions are added by default. See example below. :param uniqueID: [*req*] the given unique ID. :Example: >>> Env = pywinda.environment("C_Env") >>> #Creates an environment without assigning it to any wind farm. >>> print(Env.conditions.keys()) dict_keys(['Wind degrees', 'Wind speeds',...]) >>> print(Env.conditions['Wind degrees']) [0, 1, 2, ... , 358, 359] >>> print(Env.conditions['Wind speeds']) [0, 0.5, 1, 1.5, ... , 49.5, 50.0] \---------------------------------------------------------------------------------------------------------------------------------------------------------- """ created_environments=[] def __init__(self, uniqueID): self.uID = uniqueID environment.created_environments.append(uniqueID) self.__conditionsDic={} self.__conditionsDic["Wind degrees"]=[i for i in range(0,360)] #degrees self.__conditionsDic["Wind speeds"]=[i for i in np.arange(0,50.5,0.5)]#m/s self.windSectors=None @property def conditions(self): """ Returns all the defined conditions of the environment. :param None: :Example: >>> dantysk=pywinda.windFarm("DanTysk") >>> D_Env = dantysk.addEnvironment("D_Env") >>> print(D_Env.conditions.keys()) dict_keys(['Wind degrees', 'Wind speeds',...]) >>> print(D_Env.conditions['Wind degrees']) [0, 1, 2, ... , 358, 359] >>> print(D_Env.conditions['Wind speeds']) [0, 0.5, 1, 1.5, ... , 49.5, 50.0] \---------------------------------------------------------------------------------------------------------------------------------------------------------- """ return self.__conditionsDic def makeSectors(self,n=12,sectorNames=["N_0","NNE_30","NEN_60","E_90","ESE_120","SSE_150","S_180","SSW_210","WSW_240","W_270","WNW_300","NNW_330"]):#by default the function will divide the sector in 12 regions """ Creates the given sectors to the related environment. Returns the result as a data frame. Divides the 360 degrees to given number of sectors. By default it divides to 12 sectors and assigns the 12 standard names for every sector e.g. N_0 starts from 346 degrees and ends at 15 degrees. :param n: [*opt*] the number of sectors. :param sectorNames: [*opt*] names of the sectors given by user or default names for n=12. :Example: >>> Env=pywinda.environment("C_Env") >>> print(Env.makeSectors()) N_0 NNE_30 NEN_60 E_90 ... W_270 WNW_300 NNW_330 0 346.0 16.0 46.0 76.0 ... 256.0 286.0 316.0 1 347.0 17.0 47.0 77.0 ... 257.0 287.0 317.0 2 348.0 18.0 48.0 78.0 ... 258.0 288.0 318.0 3 349.0 19.0 49.0 79.0 ... 259.0 289.0 319.0 4 350.0 20.0 50.0 80.0 ... 260.0 290.0 320.0 5 351.0 21.0 51.0 81.0 ... 261.0 291.0 321.0 6 352.0 22.0 52.0 82.0 ... 262.0 292.0 322.0 7 353.0 23.0 53.0 83.0 ... 263.0 293.0 323.0 8 354.0 24.0 54.0 84.0 ... 264.0 294.0 324.0 9 355.0 25.0 55.0 85.0 ... 265.0 295.0 325.0 10 356.0 26.0 56.0 86.0 ... 266.0 296.0 326.0 11 357.0 27.0 57.0 87.0 ... 267.0 297.0 327.0 12 358.0 28.0 58.0 88.0 ... 268.0 298.0 328.0 13 359.0 29.0 59.0 89.0 ... 269.0 299.0 329.0 14 0.0 30.0 60.0 90.0 ... 270.0 300.0 330.0 15 1.0 31.0 61.0 91.0 ... 271.0 301.0 331.0 16 2.0 32.0 62.0 92.0 ... 272.0 302.0 332.0 17 3.0 33.0 63.0 93.0 ... 273.0 303.0 333.0 18 4.0 34.0 64.0 94.0 ... 274.0 304.0 334.0 19 5.0 35.0 65.0 95.0 ... 275.0 305.0 335.0 20 6.0 36.0 66.0 96.0 ... 276.0 306.0 336.0 21 7.0 37.0 67.0 97.0 ... 277.0 307.0 337.0 22 8.0 38.0 68.0 98.0 ... 278.0 308.0 338.0 23 9.0 39.0 69.0 99.0 ... 279.0 309.0 339.0 24 10.0 40.0 70.0 100.0 ... 280.0 310.0 340.0 25 11.0 41.0 71.0 101.0 ... 281.0 311.0 341.0 26 12.0 42.0 72.0 102.0 ... 282.0 312.0 342.0 27 13.0 43.0 73.0 103.0 ... 283.0 313.0 343.0 28 14.0 44.0 74.0 104.0 ... 284.0 314.0 344.0 29 15.0 45.0 75.0 105.0 ... 285.0 315.0 345.0 [30 rows x 12 columns] \----------------------------------------------------------------------------------------------------------------------------------------------------------- """ sectorSpan = 360 / n eachS2E=[i for i in np.arange(1 - sectorSpan / 2, 360, sectorSpan)] #this makes a set of starts to end of each sector such that first sector starts from 0+1-sectorSpan / 2 goes to 360 (excluding 360) and the distance between consecutive units is equal to sectorSpan. The +1 makes sure that the sector starts and ends in the correct place. For example sector E_90 with n=12 starts from 90-30+1=61 and ends at 90+30=120 sectorsDic = {} sectorNamesToReturn=sectorNames #this by default, of course user can give his/her own names as well. if n!=12: #After user give n other than 12, user can either give sectorNames or leave it, if left the script makes names automatically by assigning half othe span of the sector as the name of the sector if len(sectorNames)==12: sectorNamesToReturn = [str(i) for i in np.arange(0,360,sectorSpan)] elif len(sectorNames)!=12: sectorNamesToReturn=sectorNames if n == len(sectorNamesToReturn) and type(n) == int and n > 0: #this makes sure n is an integer and that the number of given sectors is equal to n if defined by user. for i in range(n): sectorsDic[sectorNamesToReturn[i]]=[cAngle(temp) for temp in np.arange(eachS2E[i],eachS2E[i+1],1)] self.windSectors=sectorsDic self.__conditionsDic["Sectors"]=sectorsDic return pd.DataFrame(sectorsDic) else: print("Number of sectors and proposed number of names are not equal.") def test(self): return self.uID class windFarm: """ Creates wind farm object with the given unique name. :param uniqueID: [*req*] Unique Id of the wind farm as a string. :Example: >>> from PyWinda import pywinda as pw >>> dantyskNameByUser = pw.windFarm("DanTysk") >>> print(dantyskNameByUser) <pywinda.windFarm object at 0x000002CEC9D17E80> \----------------------------------------------------------------------------------------------------------------------------------------------------------- """ created_windfarms=[] def __init__(self,uniqueID): self.uID=uniqueID windFarm.created_windfarms.append(uniqueID) #we append the created wind farm to the list self.createdSRTs=[] #This is the store dictionary. Stores the wind turbine reference names created in a particular wind farm self.createdMRTs=[] self.farmEnvironment=None #A wind farm will have only one environment self.__numOfSRT=len(self.createdSRTs) self.__numOfMRT=len(self.createdMRTs) self.__allDistances=pd.DataFrame() @property #This helps to protect the info from direct changes by user def info(self): """ Returns a data frame containing all the information about the wind farm. :param None: :Example: >>> print(DanTysk.info) Property Value 0 Unique ID DanTysk 1 Created SRTs [D_WT1, D_WT2, D_WT3] 2 Created MRTs [D_MWT4] 3 Number of SRTs 3 4 Number of MRTs 1 \----------------------------------------------------------------------------------------------------------------------------------------------------------- """ statistics={"Property":["Unique ID","Created SRTs", "Created MRTs","Number of SRTs","Number of MRTs"], "Value":[self.uID,self.createdSRTs,self.createdMRTs,self.__numOfSRT,self.__numOfMRT]} return pd.DataFrame(statistics) @property def assets(self): """ Returns all the unique IDs of all the assets (e.g. single rotor turbines, multirotor tubines, met masts, etc.) in the wind farm. :param None: :Example: >>> DanTysk.assets ['D_WT1', 'D_WT2', 'D_WT3', 'D_MWT4'] \----------------------------------------------------------------------------------------------------------------------------------------------------------- """ self.allassets=self.createdSRTs+self.createdMRTs#keeps the record of all assets in the wind farm return self.allassets def addTurbine(self,uniqueID,turbineType="SRT",diameter=float("NaN"),hubHeigt=float("NaN"),x_horizontal=float("NaN"),y_vertical=float("NaN")): ##This function helps to create a wind turbine and keep internal (inside the class) track of its name. It is not a deep copy, rather a reference. """ By default adds a single rotor turbine (SRT) to the related windfarm. Returns the created wind turbine with the given unique ID. The wind turbine would be callable via its unique name and via the assigned variable by user. Note that the referenced unique id is temporarly stored in library. Thus when calling the turbine via unique id, it should be prefixed by library name pywinda. See example below. :param uniqueID: [*req*] Unique ID of the wind turbine as string :param turbineType: [*opt*] Type of turbine as string: 'SRT' or 'MRT' :param diameter: [*opt*] Diameter of the turbine as float :param hubHeigt: [*opt*] Hub height as a float :param x_horizontal: [*opt*] Horizontal coordinate of the turbine as float :param y_vertical: [*opt*] Vertical coordinate of the the turbine as float :Example: >>> DanTysk=pywinda.windfar("TheDanTysk") >>> WT1=DanTysk.addTurbine("D_WT1") >>> WT2=DanTysk.addTurbine("D_WT2",diameter=120) >>> WT3=DanTysk.addTurbine("D_WT3",x_horizontal=580592,y_vertical=5925253) >>> WT3.diameter=150 #Assiging WT3 diameter after creation. >>> print(WT1==pywinda.D_WT1) True \----------------------------------------------------------------------------------------------------------------------------------------------------------- """ if uniqueID in self.createdSRTs: #Checks if the given unique Id already exists in the wind farm print("A wind turbine with the same unique ID in wind farm [",str(self.uID), "] already exists. New turbine not added.") else: if type(uniqueID) == str and len(uniqueID.split())==1: if uniqueID in globals().keys(): #Checks if the given unique Id is not in conflict with user's already assigned variables. print("A wind turbine witht the same uniqe ID globally exists. New turbine not added.") else: if turbineType=="SRT": globals()[uniqueID] = toUserVariable = SRT(uniqueID,diameter=diameter,hubHeigt=hubHeigt,x_horizontal=x_horizontal,y_vertical=y_vertical) # windfarm class is dynamicall created and referenced with the unique ID to the users assigned variable. self.__numOfSRT += 1 self.createdSRTs.append(uniqueID) elif turbineType=="MRT": globals()[uniqueID] = toUserVariable = MRT(uniqueID,diameter=diameter,hubHeigt=hubHeigt,x_horizontal=x_horizontal,y_vertical=y_vertical) # windfarm class is dynamicall created and referenced with the unique ID to the users assigned variable. self.__numOfMRT += 1 self.createdMRTs.append(uniqueID) else: print("Turbine type not supported") else: print("Name should be a string without spaces.") return toUserVariable def addEnvironment(self,envName): """ Creates environment for the referenced wind farm. Parameters of the environment (e.g. temperature, pressure, wind regime etc.) can be assigned later. The environment would be callable via its unique name and the assigned variable by user. When using the unique Id, it should be prefixed witht he library name pywinda. See example. :param envName: [*req*] Environment name :Example: >>> DanTysk=pywind.windFarm("DanTysk") >>> TheEnv_Dantysk = DanTysk.addEnvironment("D_env") >>> TheEnv_Dantysk.Airdensity = 1.225 >>> print(TheEnv_Dantysk.Airdensity == pywinda.D_env.Airdensity) True \----------------------------------------------------------------------------------------------------------------------------------------------------------- """ if self.farmEnvironment!=None: #Checks if the wind farm already have an associated environment print("The wind farm [", str(self.uID), "] already has assigned environment [",str(self.farmEnvironment),"]. New environment not added.") else: if type(envName) == str and len(envName.split())==1: if envName in globals().keys(): #Checks if the given unique Id is not in conflict with user's already assigned variables. print("An environment with the same uniqe ID globally exists. New environment not added.") else: globals()[envName] = toUserVariable = environment(envName) # environment is dynamicall created and referenced with the unique ID to the users assigned variable. self.farmEnvironment=envName else: print("Name should be a string without spaces.") return toUserVariable def distances(self, assets=[]):#From this point there would be a global convention of naming the property which shares two turbines in a "from" to "to" convention. For example distanceWT1toWT2 means the distance from WT1 to WT2 """ Returns the data frame with all the distances between assets in the wind farm or between those given in the assets list. :param assets: [*opt*] Unique ID or object name of the assets :Example: >>> Curslack = windFarm("Curslack_farm") >>> WT1 = Curslack.addTurbine("C_WT1", x_horizontal=480331, y_vertical=4925387) >>> WT2 = Curslack.addTurbine("C_WT2", x_horizontal=480592, y_vertical=4925253) >>> WT3 = Curslack.addTurbine("C_WT3", x_horizontal=480886, y_vertical=4925166) >>> WT4 = Curslack.addTurbine("C_MWT4",x_horizontal=480573, y_vertical=4925712) >>> print(Curslack.distances()) Assets C_WT1 C_WT2 C_WT3 C_MWT4 C_MWT5 0 C_WT1 0.000000 293.388821 597.382624 405.202419 551.515186 1 C_WT2 293.388821 0.000000 306.602348 459.393078 421.808013 2 C_WT3 597.382624 306.602348 0.000000 629.352842 428.164688 3 C_MWT4 405.202419 459.393078 629.352842 0.000000 295.465734 4 C_MWT5 551.515186 421.808013 428.164688 295.465734 0.000000 \----------------------------------------------------------------------------------------------------------------------------------------------------------- """ if len(assets)==0: #The user should give the set of turbines here, if not the function will calculate and return all the distances between all the turbines in that wind farm. distancesDic={} distancesDic["Assets"]=self.assets for asset in self.assets: distancesDic[asset] = [] for i in range(len(self.assets)): deltax=globals()[asset].x_horizontal-globals()[self.assets[i]].x_horizontal deltay=globals()[asset].y_vertical-globals()[self.assets[i]].y_vertical distance=((deltax**2)+(deltay**2))**(0.5) distancesDic[asset].append(distance) df=pd.DataFrame(distancesDic) return df else: #This part will work for the user's given set of turbines manually print("To be done for a given set of turbines' unique names") return "Under development" def coordinates(self, assets=[]): """ Returns the data frame with all assets' x and y coordinates if the assets list is empty, otherwise only for the given set of assets. :param assets: [*opt*] Unique ID or object name of the assets :Example: >>> Curslack = windFarm("Curslack_farm") >>> WT1 = Curslack.addTurbine("C_WT1", x_horizontal=480331, y_vertical=4925387) >>> WT2 = Curslack.addTurbine("C_WT2", x_horizontal=480592, y_vertical=4925253) >>> WT3 = Curslack.addTurbine("C_WT3", x_horizontal=480886, y_vertical=4925166) >>> WT4 = Curslack.addTurbine("C_MWT4",x_horizontal=480573, y_vertical=4925712) >>> print(Curslack.coordinates()) Assets x_coor y_coor C_WT1 480331 4925387 C_WT2 480592 4925253 C_WT3 480886 4925166 C_MWT4 480573 4925712 C_MWT5 480843 4925592 \----------------------------------------------------------------------------------------------------------------------------------------------------------- """ if len(assets) == 0: coordinatesDic={} coordinatesDic["Assets"]=["x_coor","y_coor"] for asset in self.assets: coordinatesDic[asset]=[globals()[asset].x_horizontal,globals()[asset].y_vertical] toReturn=pd.DataFrame(coordinatesDic) return toReturn.set_index('Assets').transpose() else: print("To be done for a given set of turbines' unique names") return "Under development" class SRT: created_SRTs=[] def __init__(self,srtUniqueID,diameter=float("NaN"),hubHeigt=float("NaN"),x_horizontal=float("NaN"),y_vertical=float("NaN")): SRT.created_SRTs.append(srtUniqueID) self.uID = srtUniqueID self.diameter=diameter self.hubHeight=hubHeigt self.x_horizontal=x_horizontal self.y_vertical=y_vertical class MRT(SRT): pass if __name__=='__main__': ##This section is made for tests. A more comprehensive test strategy will be developed later. Here the test can only check for syntax error, but to ensure script gives true resutls test mechanism should be developed. Curslack = windFarm("Curslack_farm") WT1 = Curslack.addTurbine("C_WT1", hubHeigt=120, diameter=120, x_horizontal=480331, y_vertical=4925387) WT2 = Curslack.addTurbine("C_WT2", x_horizontal=480592, y_vertical=4925253) WT3 = Curslack.addTurbine("C_WT3", x_horizontal=480886, y_vertical=4925166) WT4 = Curslack.addTurbine("C_MWT4", turbineType="MRT", x_horizontal=480573, y_vertical=4925712) WT5 = Curslack.addTurbine("C_MWT5", turbineType="MRT", x_horizontal=480843, diameter=450, y_vertical=4925592) DanTysk=windFarm("Dantysk_name") Env = environment("C_Env") # Creates an environment without assigning it to any wind farm. print(Env.makeSectors()) TheEnv_Dantysk = DanTysk.addEnvironment("D_env") TheEnv_Dantysk.Airdensity = 1.225 print(TheEnv_Dantysk.Airdensity == D_env.Airdensity) WT1 = DanTysk.addTurbine("D_WT1") WT2 = DanTysk.addTurbine("D_WT2", diameter=120) WT3 = DanTysk.addTurbine("D_WT3", x_horizontal=580592, y_vertical=5925253) WT3.diameter = 150 # Assiging WT3 diameter after creation. print(WT1 == D_WT1) print(DanTysk.assets) print(Curslack.coordinates()) print(Curslack.distances()) print(DanTysk.info)
68afd9a53163b91642f9c0c44fd2c8155b262382
neelamy/InterviewBit
/Hashing/fourSum.py
2,358
3.796875
4
# Source : https://www.interviewbit.com/problems/4-sum/ # Given an array S of n integers, are there elements a, b, c, and d in S such # that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target. # Algo/DS : Hashing # Complexity :O(n^2) from collections import defaultdict class fourSum: def fourSum(self, A, B): sum_of_two = defaultdict(list) is_sum_used ={} # create dictionary of sum of each possible pair for i in range(len(A)): for j in range(i + 1, len(A)): n = A[i]+ A[j] # save index pair as indices are uniques where as values can be repeated if at different indices sum_of_two[n].append((i,j)) is_sum_used[n] = False res = set() # for each sum(i.e. a+b), check if c + d i.e. B -(a+b) is present in dictionary # if yes, take all unique combination of both the lists for sum1 in sum_of_two: sum2 = B - sum1 if sum2 in sum_of_two and is_sum_used[sum2] == False: for pair1 in sum_of_two[sum1]: for pair2 in sum_of_two[sum2]: # make sure same index is not used in both pairs if pair1[0] in pair2 or pair1[1] in pair2 : continue # sort the list before adding as set consider(1,2) and (2,1) as different pair # we have to eliminate all the duplicates res.add(tuple(sorted(pair1 + pair2))) # mark both sum as used so that they are not used again # eg if sum1= 1 and sum2 = 3 then sum1= 3 should be avoided is_sum_used[sum1], is_sum_used[sum2] = True, True final_result = set() # convert index values to their actual values and eliminate duplicates for quadruplets in res: final_result.add(tuple(sorted(([A[index] for index in quadruplets])))) # return sorted result return sorted(final_result) def main(): print fourSum().fourSum([23, 20, 0, 21, 3, 38, 35, -6, 2, 5, 4, 21 ], 29) # [0 2 4 23 ] [0 3 5 21 ] [0 4 5 20 ] [2 3 4 20 ] if __name__ == '__main__': main()
c76d4b500fc0602be09b117ece7c31e879342fec
tocarmeli/LeetCode
/easy/palindromeNum.py
358
3.828125
4
# https://leetcode.com/problems/palindrome-number/ # Question 9: Palindrome Number class Solution: def isPalindrome(self, x: int) -> bool: concatenatedNum = str(x) palindrome = concatenatedNum[::-1] if (palindrome == concatenatedNum): return True return False test = Solution() print(test.isPalindrome(10))
d7d321c4eee9a5ebc2bf830145b6d01e42f6ce76
lukasz-kolodzinski/backpack
/backpack.py
1,116
3.78125
4
#Simple two-players game. Player has to guess what is hidden in his mate's backpack. players = [] for x in range(2): players.append({ 'user':'', 'points':0, 'backpack':[] }) players[x]['user'] = input('Provide name for player ' + str(x + 1) + ': ') print('Enter 4 things that you are going to hide into backpack:') for y in range(4): backpack_items = input('an item name: ') players[x]['backpack'].append(backpack_items) game_on = True while game_on is True: for i in range(2): player_guess = input(players[i]['user'] + " guess what is hidden in your mate's backpack: ") second_player = players[(i+1)%2] if player_guess in second_player['backpack']: print('Bravo! You guessed a hidden item!') players[i]['points'] += 1 else: print('You did not guess what is hidden in backpack') play_again = input('Do you want to play again? Type in: YES or NO: ') if play_again == 'NO': game_on = False #TODO: Improve game logic. Add functions. Exceptions handling.
2e8e0ae56a87e7201d7701e497840c65d25c0617
sabdulmajid/Beginner-Python-Programs
/Multiples-CL.py
1,712
3.96875
4
# Multiples-CL.py # Question 1: # With FOR Loop: number = int(input('Enter a number, for which the first ten multiples of the number: ')) for counter in range(1, 11): multiple = counter * number print(number,'x', counter,'=', multiple) # With WHILE Loop: number = int(input('Enter a number, for which the first ten multiples will be shown: ')) counter = 0 while counter < 10: counter = counter + 1 multiple = counter * number print(number, 'x', counter, '=', multiple) # Question 2: # With FOR Loop: totalpass = 0 totalfail = 0 invalid = 0 for counter in range(1, 11): number = int(input('\nEnter the mark of a student ')) if 100 >= number >= 50: totalpass = totalpass + 1 print('You PASSED') elif 50 > number >= 0: totalfail = totalfail + 1 print('You FAILED') else: invalid = invalid + 1 print('The mark you have entered is invalid') print('\nThe total passes were:', totalpass) print('The total fails were:', totalfail) print('The total invalid inputs were:', invalid) # With WHILE Loop: counter = 0 totalpass = 0 totalfail = 0 invalid = 0 while counter < 10: counter = counter + 1 number = int(input('\nEnter the mark of a student ')) if 100 >= number >= 50: totalpass = totalpass + 1 print('You PASSED') elif 50 > number >= 0: totalfail = totalfail + 1 print('You FAILED') else: invalid = invalid + 1 print('The mark you have entered is invalid') print('The total passes were:', totalpass) print('The total fails were:', totalfail) print('The total invalid inputs were:', invalid)
819165f4d7b4e64a6328ba60e0d776d8fb49c7a4
realbigws/From_CA_to_FullAtom
/modeller9v8/modlib/modeller/util/matrix.py
756
4.09375
4
"""Utility methods for handling matrices""" def matrix_to_list(matrix): """Flatten a 3x3 matrix to a 9-element list""" lst = [] if isinstance(matrix, (list, tuple)) and len(matrix) == 3: for row in matrix: if isinstance(row, (list, tuple)) and len(row) == 3: lst.extend(row) else: raise ValueError("Matrix must be a 3x3 array") else: raise ValueError("Matrix must be a 3x3 array") return lst def list_to_matrix(lst): """Construct a 3x3 matrix from a 9-element list""" if isinstance(lst, (list, tuple)) and len(lst) == 9: return [lst[0:3], lst[3:6], lst[6:9]] else: raise ValueError("Expecting a 9-element list to construct a matrix")
1594a5e8aeb3ebab28d7756d94e99f6714001220
ogbr/homework
/webinar1/1_1.py
274
3.578125
4
login = input("Введите логин") print(login) password = input("Введите пароль") print(password) sum=float(input("Введите сумму к оплате")) print (f"Ваша сумма к оплате с комиссией {sum+0.1*sum:0.2f}")
aef3b5a8f43ba3dc1c77ed21478315dcc08cb6b3
geffenbrenman/Link-a-Pix-AI-final-project
/Project/xml_parser.py
2,373
3.609375
4
import xmltodict def get_xml_from_path(path): """ Create dictionary with the following items: name - Puzzle name width - Puzzle width height - Puzzle height colors - List of RGB values [str] paths - dictionary where the keys are the colors and the values are lists of lists of paths in the key color { RED : [[(i1,j1), (i2,j2)...], [(i3,j3), (i4, j4)...]...]} :param path: Path to xml file :return: The above dictionary """ with open(path, 'rb') as file: my_dict = dict(xmltodict.parse(file)['puzzle']) ret_dict = { 'name': my_dict['header']['properties']['text']['#text'], 'width': int(my_dict['data']['dimensions']['@width']), 'height': int(my_dict['data']['dimensions']['@height']), 'colors': [], 'paths': dict() } color_dict = my_dict['data']['palette']['color'] color_list = create_colors_list(color_dict) ret_dict['colors'] = color_list path_dict = my_dict['data']['solution']['path'] paths_dict = create_paths_dict(path_dict, color_list) ret_dict['paths'] = paths_dict return ret_dict def create_paths_dict(paths_dict, color_list): """ Creates a dictionary {"color" : [paths]} :param color_list: :param paths_dict: :return: """ result = {i: [] for i in range(len(color_list))} for i in range(len(paths_dict)): str_path = paths_dict[i]['#text'] color = int(paths_dict[i]['@color']) result[color].append(create_tuple_path(str_path)) return result def create_tuple_path(str_path): """ Gets a path as a string - for example : '1 2 3 4' and creates a list of tuples. :param str_path: :return: a list of tuples - [(1,2), (3,4)] """ result = [] path_list = str_path.split() for i in range(0, len(path_list), 2): result.append((int(path_list[i + 1]), int(path_list[i]))) return result def create_colors_list(color_dict): """ extract the colors from their section in the xml file, and puts them in a list :param color_dict: :return: the list of the colors """ ret = [] for i in range(len(color_dict)): ret.append('#' + color_dict[i]['@rgb']) return ret
34a84f3f1a24b655fdfe4a75fb6f49a7cb257074
Izzyrael/PythonLibrary
/01_Fundamentals/16_Inheritance_And_Polymorphism.py
2,386
4.78125
5
# Inheritance is how we can create a 'parent-child' relationship with our classes # imagine having a class that already has properties that we don't declare because they come from our 'parent' class # python allows us to do this # lets make an 'animal' class class Animal: def speak(self): return "I'm an animal" # but what is an animal? an animal is a group of mammals, fish, and other organisms. So lets dig down a little deeper class Dog(Animal): # notice how we added parenthesis to our class name... hmmm def __init__(self, name): self.name = name def get_greeting(self): return "my name is " + self.name # when we add parenthesis to our class declaration(line 16) that means the class we are defining 'DERIVES' from # what ever is in the parenthesis. that's alot of gibberish so lets see what it can do dog = Dog('max') print(dog.get_greeting()) print(dog.speak()) # but wait.. we don't have a 'speak()' function in dog? that's right! it's in our animal class. however our dog class # derives from animal, so our dog class get ALL of our functions and attributes that animal has # this is what a 'parent-child' or 'Base-sub' class relationship is # we could also continue the chain and have classes that derive from 'Dog', but that's out of scope for now # that is inheritance on a basic level, now lets talk about 'Polymorphism' # polymorphism simply is changing similar behavior between classes # let's make a new child class of Animal to see how this works class Bird(Animal): def speak(self): return 'tweet' bird = Bird() print(bird.speak()) # notice how we already have a speak function defined in our parent class 'Animal', we can OVERRIDE that method in our # parent class and change the behavior # give it a run and see what happens # but what if we want to use the parent class' method? lets make a new child class of 'Animal' and change it up class Turtle(Animal): def speak(self): return super().speak() + ' and Im a turtle' # the 'super()' keyword means 'refer to the parent class' # it works the same as the 'self' keyword # now lets make a turtle instance and see what happens when we print the turtles speak() function turtle = Turtle() print(turtle.speak()) # we can use the super() keyword for all attributes, functions, and constructors in a derived/child class
583d8a0f0a0359c17d2aa6fa4f2ad0039a25bca7
OneNobleGnome/exercises
/chapter-5.2/test_ex_5_13.py
490
3.546875
4
from ex_5_13 import find_falling_distance import unittest class TestFallingDistance(unittest.TestCase): def test_one_second(self): expected = 4.9 actual = find_falling_distance(1) self.assertEqual(expected, actual) print(find_falling_distance(1)) def test_zero_seconds(self): expected = 0 actual = find_falling_distance(0) self.assertEqual(expected, actual) print(find_falling_distance(0)) unittest.main()
33c7fef0696c9f7dc6bca36c280c5cc09b19d8e2
crizer03/Python
/1 - inheritance.py
1,570
4.28125
4
# Types of inheritance # Single A > B class A: pass class B(A): pass # Multi Level A > B > C class A: pass class B(A): pass class C(B): pass # Hierarchical A > B, A > C class A: pass class B(A): pass class C(A): pass # Multiple A > C, B > C class A: pass class B: pass class C(A, B): pass # Hybrid A > B, A > C, B > D, C > D class A: pass class B(A): pass class C(A): pass class D(B, C): pass # super() can be used in 3 ways. # - To invoke parent class methods # - To invoke parent class variables # - To invoke parent class constructor # globals() is the variables or method outside class a, b = 15, 20 def method(): print('Global method {}'.format('method')) class A: a, b = 10, 20 def __init__(self): print("Constructor from class A") def method(self, a, b): print("Method from Class A") class B(A): a, b = 100, 200 def __init__(self): print("Constructor from class B") super().__init__() # Approach 1. Calls parent class constructor A.__init__(self) # Approach 2. Directly specify the class def method(self, a, b): super().method(1, 2) # Prints parent method method() # Prints global method print(a + b) # Local variables print(self.a + self.b) # Child class variables print(super().a + super().b) # Parent class variables print(globals()['a'] + globals()['b']) # Global variables obj = B() obj.method(40,60)
c5140f7120d1527e1f968aa6ab7e6be092ee86ef
vins-stha/hy-data-analysis-with-python
/part03-e14_operations_on_series/src/operations_on_series.py
513
3.71875
4
#!/usr/bin/env python3 import pandas as pd def create_series(L1, L2): #print(L1,L2) indices = ['a','b','c'] s1 = pd.Series(L1, index =indices) s2 = pd.Series(L2, index =indices) return (s1, s2) def modify_series(s1, s2): s1["d"] =s2["b"] del(s2["b"]) return (s1, s2) def main(): L1=[2,3,4] L2=[9,8,7] s1,s2 = create_series(L1,L2) s1,s2 = modify_series(s1,s2) s1+s2 # print(s1.add(s2)) if __name__ == "__main__": main()
ff0986c0f907c2f6b425913b877f51ca4d972d10
anmolrajaroraa/core-python-july
/01-functions.py
453
3.75
4
# def fn_name(param1, param2, ..., paramn): # statement1 # statement2 # return statement def inputNumbers(): a = int(input("Enter first number: ")) b = int(input("Enter second number: ")) c = int(input("Enter third number: ")) return a, b, c, 13, 34, 5, 3, 2, 99, 33 # packing *x, y = inputNumbers() # unpacking z = inputNumbers() print("X is ", x) print("Y is ", y) print("Z is ", z) # x, y = 10, 20 # x = (10, 20)
fae1b6fbbc7ab1af258ae2f70b5887d452dff591
snowraincloud/leetcode
/529.py
1,165
3.65625
4
from typing import List class Solution: def updateBoard(self, board: List[List[str]], click: List[int]) -> List[List[str]]: if not board: return board l = len(board) w = len(board[0]) points = [] points.append((click[0], click[1])) while points: x, y = points.pop() if board[x][y] == 'M': board[x][y] = 'X' break coordinate = [(i, j) for i, j in [(x-1,y-1), (x-1, y), (x-1,y+1), (x, y-1), (x, y+1), (x+1, y-1), (x+1, y), (x+1, y+1)] if 0 <= i < l and 0 <= j < w and board[i][j] in ('M', 'E')] m = 0 for i, j in coordinate: if board[i][j] == 'M': m += 1 if m == 0: board[x][y] = 'B' points.extend(coordinate) else: board[x][y] = str(m) return board if __name__ == "__main__": solution = Solution() print(*solution.updateBoard([["E","E","E","E","E"],["E","E","M","E","E"],["E","E","E","E","E"],["E","E","E","E","E"]], [3,0]), sep='\n')
b1f6801705c66bb334c2ebb1ef3749301164d12b
VladislavJanibekyan/py_home
/git_class.py
1,385
4.25
4
class Car: #class Car(): class Car(object): brand = "BMW" year = 2019 color = "red" def presentation(self): return self.brand, self.year, self.color bmw = Car() bmw.brand = "bmw" mercedes = Car() mercedes.brand = "mercedes" print(bmw.presentation()) print(mercedes.presentation()) print(Car.presentation(bmw)) print(type(bmw)) print(type(bmw.brand)) print(type(bmw.year)) print(bmw.year) #bmw.year = 2018 print(bmw.year) print(Car.year) Car.year = 15 print(bmw.year) class Car: def __init__(self,brand="bmw",year= 2010,color = "black"): self.brand_name = brand self.year = year self.color = color def presentation(self): return self.brand, self.year, self.color a = Car("Bmw",201,12) b = Car() print(a.color) print(b.__dict__) class Fruit(): def __init__(self,taste,shape,price,color): self.taste = taste self.shape = shape self.price = price self.color = color def presentation(self): return f"this is a fruit which is {self.taste}, the shape is {self.shape}, the price is {self.price} and the color is {self.color}" apple = Fruit("sweet","round",20,"red") mandarin = Fruit("sweet","round",32,"orange") print(mandarin.presentation()) print(mandarin.__dict__) print(apple.presentation()) print(apple.__dict__)
40e8409c8f0d6b675c49bb7fc0024443237ca354
Robertzzz123/Python-labs
/Lab 5/Lab 5.py
1,971
3.75
4
import math class Fraction: """Находим сумму сложения двух дробей""" def __init__(self, n, d): self.num = int(n / self.gcd(abs(n), abs(d))) self.denom = int(d / self.gcd(abs(n), abs(d))) if self.denom < 0: self.denom = abs(self.denom) self.num = -1 * self.num elif self.denom == 0: raise ZeroDivisionError def gcd(self, n, d): while n != d: if n > d: n = n - d else: d = d - n return n def __Add__(self, other): return self.num * other.denom + self.denom * other.num, self.denom * other.denom def __str__(self): if type(self) is tuple: if self[1] < 0: return '%s/%s' % (self[0], -1 * self[1]) else: return '%s/%s' % (self[0], self[1]) def __le__(self, other): return math.sqrt(self.num ** 2 + other.denom ** 2 + self.denom ** 2 + other.num ** 2) <= math.sqrt(self.denom ** 2 + other.num ** 2 + self.num ** 2 + other.denom ** 2) def __li__(self, other): return math.sqrt(self.num ** 2 + other.denom ** 2 + self.denom ** 2 + other.num ** 2) < math.sqrt(self.denom ** 2 + other.num ** 2 + self.num ** 2 + other.denom ** 2) def __la__(self, other): return math.sqrt(self.num ** 2 + other.denom ** 2 + self.denom ** 2 + other.num ** 2) >= math.sqrt(self.denom ** 2 + other.num ** 2 + self.num ** 2 + other.denom ** 2) def __lo__(self, other): return math.sqrt(self.num ** 2 + other.denom ** 2 + self.denom ** 2 + other.num ** 2) > math.sqrt(self.denom ** 2 + other.num ** 2 + self.num ** 2 + other.denom ** 2) f1 = Fraction(3,-3) f2 = Fraction(3,-3) f3 = Fraction.__Add__(f1,f2) print(Fraction.__str__(f3)) print(Fraction.__Add__(f1,f2)) print(Fraction.__le__(f1,f2)) print(Fraction.__li__(f1,f2)) print(Fraction.__la__(f1,f2)) print(Fraction.__lo__(f1,f2))
eaea60dee33f86ac9274031ad8c0f09412724f64
portugol/decode
/Algoritmos Traduzidos/Python/Algoritmos traduzidos[Filipe]/ex2.py
114
3.53125
4
lado = input('Medida do lado do quadrado: ') area=int(lado)*int(lado) print('A area do quadrado é:',area)
6e7468ba558528ca36e8f38dac2d8c1b42447331
plume-n/plume
/python/Day04_20180821_najw.py
1,134
3.703125
4
#task 1 排序 a = [1,2,3,4,5,6,7,8,9] a.reverse() print('task1 逆序操作:') print(a) #学生管理系统 print('\ntask2 学生管理系统:') person_list = [] num = 1 str_in = input('学生管理系统:\ \n 1.新增学生\ \n 2.查找所有学生\ \n 3.根据学号查找学生\ \n 4.根据学号删除学生\ \n 5.退出\ \n 请输入序号操作:') while str_in != '5': if str_in == '1': person = {'number':'','name':'','age':'','class':''} person['name'] = input('姓名:') person['age'] = input('年龄:') person['class'] = input('班级:') person['number'] = num num += 1 person_list.append(person) elif str_in == '2': for index in person_list: print(index) elif str_in == '3': sear_num = input('请输入学号:') for index in person_list: result = index.get('number') if int(result) == int(sear_num): print(index) elif str_in == '4': del_num = input('请输入要删除的学号:') for x in person_list: y = x.get('number') if int(y) == int(del_num): person_list.remove(x) print('已删除学员:',x) str_in = input('请选择操作:')
bef52cebe93d0c16f662501fee9a5f1182cf8e4c
ethanwllms/QC-Project
/QC-Pi/createDirectory.py
743
3.546875
4
import os import datetime def findCurrentYear(): now = datetime.datetime.now() return str(now.year) def createDIR(directory): if not os.path.exists(directory): os.makedirs(directory) elif os.path.exists(directory): print("Directory (" + directory + ") already exists") pass else: print ('Error: Creating directory. ' + directory) def nameDIR(): jobIDNumber = input("Please scan or enter job ID (or Press Q to quit): ") if (jobIDNumber == 'q') or (jobIDNumber == 'Q'): jobIDNumber = 'FALSE' return jobIDNumber year = findCurrentYear() dirPathPART = "/mnt/usbstorage/" + year + "/" + jobIDNumber testDIRPathPART = "Test/" + jobIDNumber createDIR(jobIDNumber) print (dirPathPART) #Test PRINT return jobIDNumber
40db7eafe46899cd31c47c81983117345ff600ba
616049195/random_junks
/random_games/magic/Magic.py
865
3.84375
4
""" # credit goes to: HK # created on 2014.08.17 # status: semi-done """ from random import randint class Magic(object): """ does the magic""" number = 0 ran_num = 0 def intro(self): print "\nChoose a number between 1 and 10." wait = True while (wait): if raw_input("Once you are done, enter \"YES\": ").lower() == 'yes': wait = False def doing_magic(self): """ asks the user to add a randomized number """ self.ran_num = randint(1,10) self.number += self.ran_num print "\nAdd %s to your number." % (self.ran_num) def show_magic(self): _sum = int(raw_input("What is your sum?: ")) self.number = _sum - self.number print "\nYour number was %s" % (self.number) def start(self): self.intro() for x in range(0, randint(3,7)): self.doing_magic() raw_input("Once you are done, type ENTER.") self.show_magic()
ce9e901fdc32770c1ba7cea4a074f2ecd8abcd06
m-lair/Projects
/lair-project-6.py
4,846
3.890625
4
from tkinter import * import math class TipCalculator: def __init__(self): window = Tk() window.title("Tippity Split") Label(window, text = "Tippity Split - Tip Calculator", fg = "Red").grid(row = 1, column = 1, columnspan = 2, ) # Labels on left side of GUI and left of Entry boxes Label(window, text = "Check Amount $").grid(row = 2, column = 1, sticky = "W") Label(window, text = "Tip %").grid(row = 3, column = 1, sticky = "W") Label(window, text = "Split (x Ways):").grid(row = 4, column = 1, sticky = "W") # Entry Boxes self.checkAmount = StringVar() Entry(window, textvariable = self.checkAmount).grid(row = 2, column = 2) self.checkAmount.set("0.00") self.tipPercent = StringVar() Entry(window, textvariable = self.tipPercent).grid(row = 3, column = 2) self.tipPercent.set("15") self.split = StringVar() Entry(window, textvariable = self.split).grid(row = 4, column = 2) self.split.set("1") # Radio Buttons for rounding up self.roundRadioButtons = IntVar() roundButton = Radiobutton(window, text = "Round Up", variable = self.roundRadioButtons, value = 0).grid(row = 5, column = 1) dontRound = Radiobutton(window, text = "Don't Round", variable = self.roundRadioButtons, value = 1).grid(row = 5, column = 2) # Buttons to perform calculation and clear data calcButton = Button(window, text = "Calculate", command = self.calculate).grid(row = 6, column = 1) clearButton = Button(window, text = "Clear", command = self.clear).grid(row = 6, column = 2) # Results Labels at bottom of GUI self.tipLabel = StringVar() tipLabel = Label(window, textvariable = self.tipLabel).grid(row = 7, columnspan = 2, sticky = "W") self.tipLabel.set("The tip is $0.00") self.totalLabel = StringVar() totalLabel = Label(window, textvariable = self.totalLabel).grid(row = 8, columnspan = 2, sticky = "W") self.totalLabel.set("The total after tip is $0.00") self.splitLabel = StringVar() self.splitLabel.set("Each gues should pay $0.00") splitLabel = Label(window, textvariable = self.splitLabel).grid(row = 9, columnspan = 2, sticky = "W") window.mainloop() def calculate(self): ''' Calculates tip, total check and split input: none returns: values to result labels ''' rad = self.roundRadioButtons.get() if rad == 0: tip = math.ceil(float(self.checkAmount.get()) * float(self.tipPercent.get()) / 100) total = math.ceil(tip + float(self.checkAmount.get())) splitPay = math.ceil(total / int(self.split.get())) else: tip = float(self.checkAmount.get()) * float(self.tipPercent.get()) / 100 total = tip + float(self.checkAmount.get()) splitPay = total / int(self.split.get()) self.tipLabel.set(str("The tip is $" + str(tip))) self.totalLabel.set(str("The total after tip is $" + str(total))) self.splitLabel.set(str("Each guest should pay $" + str(splitPay))) def clear(self): ''' clears all data from labels and entry boxes input: none returns: default amounts ''' self.tipLabel.set("The tip is $") self.totalLabel.set("The total after tip is $0.00") self.splitLabel.set("Each guest should pay $0.00") self.checkAmount.set("0.00") self.tipPercent.set("15") self.tipLabel.set("The total after tip is $0.00") self.splitLabel.set("Each gues should pay $0.00") TipCalculator()
2bc2912ce3a782156edff88c3f159fb376587883
kmark1625/Project-Euler
/p9.py
499
4.09375
4
import itertools def pythagorean_generator(): #Generates a pythagorean triplet sets = itertools.combinations(range(500),3) while True: a, b, c = next(sets) if (a**2 + b**2 == c**2): yield (a,b,c) def find_1000(): a,b,c=0,0,0 sets = pythagorean_generator() while (a+b+c) < 2000: a,b,c = next(sets) print a,b,c if (a+b+c) == 1000: yield (a,b,c) if __name__ == '__main__': a,b,c = next(find_1000()) print "The answer is: %i, %i, %i" % (a,b,c) print "a*b*c = %i" % (a*b*c)
f9244a1d2f2aa6a2b60b16845558444ac9f025fb
Artificial-Ridiculous/Codes
/Python/leetconde-cn/二叉树遍历.py
1,206
3.78125
4
class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None n5 = TreeNode(5) n3 = TreeNode(3) n6 = TreeNode(6) n2 = TreeNode(2) n4 = TreeNode(4) n1 = TreeNode(1) n5.left = n3 n5.right = n6 n3.left = n2 n3.right = n4 n2.left = n1 def bfs(root:TreeNode): p = root queue = [] if p: queue.append(p) while(queue): p = queue.pop(0) print (p.val) if p.left: queue.append(p.left) if p.right:queue.append(p.right) def dfs(root:TreeNode): p = root stack = [] while(stack or p): while(p): print(p.val) stack.append(p) p=p.left p = stack.pop() p = p.right def bfsdic(root:TreeNode): p = root queue = [] if p: dic = {p:None} queue.append(p) while(queue): p = queue.pop(0) if p.left: dic[p.left]=p queue.append(p.left) if p.right: dic[p.right]=p queue.append(p.right) print(dic) return dic if __name__ == '__main__': bfsdic(n5) # print('---') # dfs(n5)
47353d7ef1d34872e0a0404005e010f42d95febb
dilaraism/-solutions
/codewars/python/simple_pig.py
255
3.828125
4
def simple_pig(s): from string import punctuation sp = lambda x: x[1:]+x[0]+"ay" if x not in punctuation else x return " ".join([sp(i) for i in s.split(" ")]) print simple_pig("Quis custodiet o ipsos custodes ?") print simple_pig("Pig latin is cool")
8afc2cbfaf63b6b6c34ecc49bf16b027b164f245
saurabh-pandey/AlgoAndDS
/leetcode/queue_stack/stack/clone_graph.py
2,795
3.625
4
#URL: https://leetcode.com/explore/learn/card/queue-stack/232/practical-application-stack/1392/ #Description """ Given a reference of a node in a connected undirected graph. Return a deep copy (clone) of the graph. Each node in the graph contains a value (int) and a list (List[Node]) of its neighbors. class Node { public int val; public List<Node> neighbors; } Test case format: For simplicity, each node's value is the same as the node's index (1-indexed). For example, the first node with val == 1, the second node with val == 2, and so on. The graph is represented in the test case using an adjacency list. An adjacency list is a collection of unordered lists used to represent a finite graph. Each list describes the set of neighbors of a node in the graph. The given node will always be the first node with val = 1. You must return the copy of the given node as a reference to the cloned graph. Example 1: Input: adjList = [[2,4],[1,3],[2,4],[1,3]] Output: [[2,4],[1,3],[2,4],[1,3]] Explanation: There are 4 nodes in the graph. 1st node (val = 1)'s neighbors are 2nd node (val = 2) and 4th node (val = 4). 2nd node (val = 2)'s neighbors are 1st node (val = 1) and 3rd node (val = 3). 3rd node (val = 3)'s neighbors are 2nd node (val = 2) and 4th node (val = 4). 4th node (val = 4)'s neighbors are 1st node (val = 1) and 3rd node (val = 3). Example 2: Input: adjList = [[]] Output: [[]] Explanation: Note that the input contains one empty list. The graph consists of only one node with val = 1 and it does not have any neighbors. Example 3: Input: adjList = [] Output: [] Explanation: This an empty graph, it does not have any nodes. Example 4: Input: adjList = [[2],[1]] Output: [[2],[1]] Constraints: The number of nodes in the graph is in the range [0, 100]. 1 <= Node.val <= 100 Node.val is unique for each node. There are no repeated edges and no self-loops in the graph. The Graph is connected and all nodes can be visited starting from the given node. """ class Node: def __init__(self, val = 0, neighbors = None): self.val = val self.neighbors = neighbors if neighbors is not None else [] def getClonedNode(clonedNodes, id): if id in clonedNodes: return clonedNodes[id] else: clonedNode = Node(id) clonedNodes[id] = clonedNode return clonedNode def cloneGraph(node): if node is None: return None clonedNodes = {} nodes = [node] while len(nodes) > 0: node = nodes.pop(0) clonedNode = getClonedNode(clonedNodes, node.val) if len(clonedNode.neighbors) > 0: continue for neighbour in node.neighbors: clonedNeighbourNode = getClonedNode(clonedNodes, neighbour.val) clonedNode.neighbors.append(clonedNeighbourNode) nodes.append(neighbour) return clonedNodes[1]
a3775466d520e001307f4a23a1c1d63d7286be97
Software05/Github
/Modulo-for/app3.py
487
3.875
4
palabraSinVocal = "" # Indicar al usuario que ingrese una palabra userWord = input('Ingrese la palabra: ') # y asignarlo a la variable userWord userWord = userWord.upper() for letra in userWord: if letra == 'A': continue if letra == 'E': continue if letra == 'I': continue if letra == 'O': continue if letra == 'U': continue print(letra, end='') # Imprimir la palabra asignada a palabraSinVocal. print(palabraSinVocal)
f8f65452d503b6a3238e0875512e5c236cf07cb3
agw2105/TravelingSalesman
/TravelingSalesmanProblem.py
5,332
4.1875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Nov 14 11:21:55 2020 @author: alysonweidmann """ import math import random from collections import deque """ """ def dist(xy1, xy2): """ Calculate the Euclidean distance between two points. """ # TODO: Implement this function! x1 = xy1[0] x2 = xy2[0] y1 = xy1[1] y2 = xy2[1] return math.sqrt((x1-x2)**2 + (y1-y2)**2) class TravelingSalesmanProblem: """ Representation of a traveling salesman optimization problem. An instance of this class represents a complete circuit of the cities in the `path` attribute. Parameters ---------- cities : iterable An iterable sequence of cities; each element of the sequence must be a tuple (name, (x, y)) containing the name and coordinates of a city on a rectangular grid. e.g., ("Atlanta", (585.6, 376.8)) shuffle : bool If True, then the order of the input cities (and therefore the starting city) is randomized. Attributes ---------- names : sequence An iterable sequence (list by default) containing only the names from the cities in the order they appear in the current TSP path coords : sequence An iterable sequence (list by default) containing only the coordinates from the cities in the order they appear in the current TSP path path : tuple A path between cities as specified by the order of the city tuples in the list. """ def __init__(self, cities, shuffle=False): if shuffle: cities = list(cities) random.shuffle(cities) self.path = tuple(cities) self.__utility = None def copy(self, shuffle=False): cities = list(self.path) if shuffle: random.shuffle(cities) return TravelingSalesmanProblem(cities) @property def names(self): """Strip and return only the city name from each element of the path list. For example, [("Atlanta", (585.6, 376.8)), ...] -> ["Atlanta", ...] """ names, _ = zip(*self.path) return names @property def coords(self): """ Strip the city name from each element of the path list and return a list of tuples containing only pairs of xy coordinates for the cities. For example, [("Atlanta", (585.6, 376.8)), ...] -> [(585.6, 376.8), ...] """ _, coords = zip(*self.path) return coords @property def utility(self): """ Calculate and cache the total distance of the path in the current state. """ if self.__utility is None: self.__utility = self.__get_value() return self.__utility def successors(self): """ Return a list of states in the neighborhood of the current state. Returns ------- iterable<Problem> A list of TravelingSalesmanProblem instances initialized with their list of cities set to one of the neighboring permutations of cities in the present state """ # TODO: Implement this function! initial_state = list(self.names) n = len(initial_state) n_states = math.factorial(n-1) end_point = initial_state[-1] neighbors = deque(maxlen=n_states) while True: k = random.sample(initial_state[:n-1], n-1) if k not in neighbors: neighbors.append(k) if len(neighbors) == neighbors.maxlen: break for i in neighbors: i.append(end_point) path_dict = dict(self.path) successors = list(TravelingSalesmanProblem(list((i, path_dict[i]) for i in x)) for x in neighbors) return successors def get_successor(self): """ Return a random state from the neighborhood of the current state. Returns ------- list<Problem> A list of TravelingSalesmanProblem instances initialized with their list of cities set to one of the neighboring permutations of cities in the present state """ # TODO: Implement this function! neighbors = self.successors() return random.choice(neighbors) def __get_value(self): """ Calculate the total length of the closed-circuit path of the current state by summing the distance between every pair of cities in the path sequence. Returns ------- float A floating point value with the total cost of the path given by visiting the cities in the order according to the self.cities list """ # TODO: Implement this function! current_path = list(self.names) current_path.append(current_path[0]) path_dict = dict(self.path) path_lengths = [] for current, next in zip(current_path, current_path[1:]): distance = dist(path_dict[current], path_dict[next]) path_lengths.append(distance) return sum(path_lengths)
7f6afb0ce1f96358fff33def93b1e184bf8e9705
Cryptoriser7/Curso-emVideo-Python
/calculadora_941.py
1,364
3.765625
4
from time import sleep print() sleep(0.5) print('Calculadora Automatica de Produção\nReferencia 941') print() print() sleep(0.5) print('Insira valores de produção:') sleep(0.5) p = int(input('Paletes Completas: ')) b = int(input('Palete Incompleta: ')) df = int(input('Sucata Fundição: ')) dm = int(input('Sucata Maquinação: ')) s = int(input('Suspenso: ')) print('-' * 20) print('\033[33mA calcular...\033[30m') print('-' * 20) sleep(2) pc = p * 165 tpb = pc + b tpp = tpb + df + dm + s ts = df + dm y = tpp % 8 x = tpp // 8 a = 8 - y b = y c = x d = x + 1 percentagem = (tpp * 100) / 632 print('\033[34mProdução Total: {}\n\033[32mProdução Aproveitada: {}\n\033[31mTotal sucata : {}\033[30m'.format(tpp, tpb, ts)) print() print('{} horas x {} peças\n{} horas x {} peças'.format(a, c, b, d)) print() if percentagem <= 70: print('\033[31m{:.2f}\033[30m % Produção'.format(percentagem)) if percentagem >= 70 and percentagem <= 85: print('\033[33m{:.2f}\033[30m % Produção'.format(percentagem)) if percentagem >= 85: print('\033[32m{:.2f}\033[30m % Produção'.format(percentagem)) print('-' * 20) print('-' * 20) print('Versão 0.01 alfa') print('Costumer ID: 3640270') print('Reference No: R1610950') print('Licença PyCharm Professional ID: UEGWPB5YUC') print('-' * 20) bool(input('Prime qualquer tecla para sair')) exit()
f382b1aa3321904463b3332ef202e256ff66174c
Viccari073/exercises_for_range_while
/exer_estruturas_de_repeticao_28.py
404
3.84375
4
""" Faça um programa que leia um valor N inteiro e positivo, calcule e mostre o valor E, conforme a fórmula a seguir: E = 1 + 1/1! + 1/2! + 1/3! + 1/4!...+1/N! """ from math import factorial num_final = int(input("Digite o termo final da sequência fatorial: ")) soma = 1 for n in range(1, num_final + 1): soma += 1 / factorial(n) print(f"O resultado de E é igual a: {soma:.2f} ")
086dd5d4943aff5a4fb82453c43f9ea5bd23b73a
vanigupta20024/Programming-Challenges
/SpiralOrderMatrix1.py
1,137
3.765625
4
''' Given a matrix of m * n elements (m rows, n columns), return all elements of the matrix in spiral order. ''' class Solution: # @param A : tuple of list of integers # @return a list of integers def spiralOrder(self, A): top = 0 bottom = len(A) left = 0 right = len(A[0]) dir = 'r' answer = [] while top < bottom and left < right: if dir == 'r': for i in range(left, right): answer.append(A[top][i]) top += 1 dir = 'd' elif dir == 'd': for i in range(top, bottom): answer.append(A[i][right - 1]) right -= 1 dir = 'l' elif dir == 'l': for i in range(right - 1, left - 1, -1): answer.append(A[bottom - 1][i]) bottom -= 1 dir = 'u' elif dir == 'u': for i in range(bottom - 1, top - 1, -1): answer.append(A[i][left]) left += 1 dir = 'r' return answer
9ea00a56132a55089ca8ce9b639083de94c62522
cbiswajeet89/Face-Detection-App
/face_detection.py
1,000
3.5625
4
import cv2 #Pre-trained faces trained_face_data=cv2.CascadeClassifier('haarcascade_frontalface_default.xml') #reading image #img=cv2.imread('mypic.png') #To capture video from webcam webcam=cv2.VideoCapture(0, cv2.CAP_DSHOW) # 0 value takes the default cam in the system #Iteration over frames while True: successful_frame_read, frame=webcam.read() #Converting the coloured img to grayscaled image grayscaled_img=cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY) #Detect faces face_coordinates=trained_face_data.detectMultiScale(grayscaled_img) #Draw rectangle around the faces for (x,y,w,h) in face_coordinates: cv2.rectangle(frame,(x,y),(x+w,y+h),(0,255,0),2) #Draw rectangle around the eyes cv2.imshow('Face Detector',frame) key=cv2.waitKey(1) #holding the image on screen for 1 milisecond #Stop if Q is pressed if key==81 or key==113: break webcam.release() #print(face_coordinates) #showing the image #cv2.imshow('Face Detector',img) #cv2.waitKey() #holding the image on screen
da2f006a1a30c07f42bf0eb8ed54bf1a0796f06a
ErenBtrk/Python-Fundamentals
/Numpy/numpy-exercises18.py
246
4.25
4
# 18- Calculate squares of the elements of the matrix in exercise 9 import numpy as np np_matrix = np.random.randint(10,50,15) np_matrix = np_matrix.reshape(3,5) print(np_matrix) np_matrix_square = np.power(np_matrix,2) print(np_matrix_square)
a74f115ed3498b82488b2b6d8e46c311ad2b510e
SayarGitHub/Intermediate-Python
/9.py
3,891
4.96875
5
# The general syntax of a lambda function is quite simple: # lambda argument_list: expression # The argument list consists of a comma separated list of arguments and the # expression is an arithmetic expression using these arguments. You can assign # the function to a variable to give it a name. # The following example of a lambda function returns the sum of its two # arguments: sum = lambda x, y: x + y print(sum(3, 4)) # -----------------------------------------------------------------------------# # The advantage of the lambda operator can be seen when it is used in # combination with the map() function. map() is a function which takes two # arguments: # r = map(func, seq) # The first argument func is the name of a function and the second a sequence # (e.g. a list) seq. map() applies the function func to all the elements of the # sequence seq. Before Python3, map() used to return a list, where each element # of the result list was the result of the function func applied on the # corresponding element of the list or tuple "seq". With Python 3, map() returns # an iterator. The following example illustrates the way of working of map(): def fahrenheit(T): return (float(9) / 5) * T + 32 def celsius(T): return (float(5) / 9) * (T - 32) # The iterator returned by map function can only be used/iterated once once temperatures = (36.5, 37, 37.5, 38, 39) F = list(map(fahrenheit, temperatures)) C = list(map(celsius, F)) print(F) print(C) # In the example above we haven't used lambda. By using lambda, we wouldn't have # had to define and name the functions fahrenheit() and celsius(). C = [39.2, 36.5, 37.3, 38, 37.8] F = list(map(lambda x: (float(9) / 5) * x + 32, C)) C = list(map(lambda x: (float(5) / 9) * (x - 32), F)) print(F) print(C) # map() can be applied to more than one list. The lists don't have to have the # same length. map() will apply its lambda function to the elements of the # argument lists, i.e. it first applies to the elements with the 0th index, then # to the elements with the 1st index until the n-th index is reached: a = [1, 2, 3, 4] b = [17, 12, 11, 10] c = [-1, -4, 5, 9] print(list(map(lambda x, y, z: x + y + z, a, b, c))) # If one list has fewer elements than the others, map will stop when the shortest # list has been consumed: a = [1, 2, 3] b = [17, 12, 11, 10] c = [-1, -4, 5, 9] print(list(map(lambda x, y, z: 2.5 * x + 2 * y - z, a, b, c))) # -----------------------------------------------------------------------------# # The function filter(f,l) needs a function f as its first argument. f has to # return a Boolean value, i.e. either True or False. This function will be # applied to every element of the list l. Only if f returns True will the element # be produced by the iterator, which is the return value of filter(function, # sequence). fibonacci = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55] odd_numbers = list(filter(lambda x: x % 2, fibonacci)) print(odd_numbers) even_numbers = list(filter(lambda x: x % 2 == 0, fibonacci)) print(even_numbers) # -----------------------------------------------------------------------------# # The function # reduce(func, seq) # continually applies the function func() to the sequence seq. It returns a # single value. # If seq = [ s1, s2, s3, ... , sn ], calling reduce(func, seq) works like this: # At first the first two elements of seq will be applied to func, i.e. # func(s1,s2) The list on which reduce() works looks now like this: [ func(s1, # s2), s3, ... , sn ] In the next step func will be applied on the previous # result and the third element of the list, i.e. func(func(s1, s2),s3) The list # looks like this now: [ func(func(s1, s2),s3), ... , sn ] Continues like this # until just one element is left and returns this element as the result of # reduce() import functools print(functools.reduce(lambda x, y: x + y, [47, 11, 42, 13]))
cc091c228f488ec198a09bcfbae7bcd9e1f648ca
kyoungje/bank_atm_controller
/test.py
3,266
3.5
4
# test program for the ATM controller import atmctrl def showAccounts(): print("\n===================================\n") print("\n[ List of Accounts ]\n") account_list = atmctrl.getAccounts() for acc in account_list: print("ID: ", acc[0], ", Balance: $", acc[1], ",\t Name: ", acc[2]) print("\n===================================") if __name__ == '__main__': acc_id = 0 # ATM Controller menu loop while True: # Wake up from idle status input("\nInsert card and press any key...") # Reading PIN from user id = int(input("\nEnter account pin: ")) # Validate the PIN if atmctrl.ATMCTRL_RET_SUCCESS != atmctrl.validatePIN(id): print("\nYou're not allowed to proceed. start again.") continue # Get status of the ATM controller if atmctrl.ATMCTRL_STATUS_AUTHENTICATED != atmctrl.getStatus(): print("\nYou're not allowed to proceed. start again.") continue showAccounts() # Iterating over account session while True: # Printing menu print("\n [1] Show and Select Account\n [2] Show Balance \n [3] Withdraw \n [4] Deposit \n [5] Exit ") # Reading selection of menu selection = int(input("\nEnter your selection: ")) # Select accounts if selection == 1: showAccounts() # Select account acc_id = int(input("\nEnter account id: ")) print("\nCurrent account id: ", acc_id) continue # Show Balance if selection == 2: # Printing balance print("\nCurrent account id", acc_id, ", balance is $", atmctrl.getBalance(acc_id)) # Withdraw elif selection == 3: # Reading amount amt = int(input("\nEnter the amount to withdraw: ")) if amt < atmctrl.getBalance(acc_id): # Calling withdraw method if atmctrl.ATMCTRL_RET_SUCCESS == atmctrl.withdraw(acc_id, amt): # Printing updated balance print("\nOK.. Current balance is $" + str(atmctrl.getBalance(acc_id))) else: print("\Withdraw job failed..") else: print("\nYour balance is not enough: current balance is $" + str(atmctrl.getBalance(acc_id))) # Deposit elif selection == 4: # Reading amount amt = int(input("\nEnter amount to deposit: ")) # Calling deposit method if atmctrl.ATMCTRL_RET_SUCCESS == atmctrl.deposit(acc_id, amt): # Printing updated balance print("\nOK.. Current balance is $" + str(atmctrl.getBalance(acc_id)) ) else: print("\nDeposit job failed..") elif selection == 5: print("\nBye!") break # Any other choice else: print("\nInvalid choice. try again!")
aa798de6f6fa87815eb337cbd8877a63f004810f
dxc19951001/Everyday_LeetCode
/130.被围绕的区域.py
3,535
3.515625
4
from typing import List class Solution: def solve(self, board: List[List[str]]) -> None: """ Do not return anything, modify board in-place instead. """ # 核心思想--dfs # 由题:任何边界上的 'O' 都不会被填充为 'X'。 # 任何不在边界上,或不与边界上的 'O' 相连的 'O' 最终都会被填充为 'X'。 # 可以理解为:边界上的O不会被填充为X,与边界上的O相连的O也不会填充为X # 找出边界:第一行与最后一行,第一列与最后一列上的O # 并使用dfs搜索,找出边界上的O相连的O,将其标记为 A # 全部找完后,最后循环列表,将标记为A的的O设置为O, # 没有标记的O全部设为X,得到结果 if not board: # 如果没有board直接返回 return n, m = len(board), len(board[0]) # n是行,m是列 def dfs(x, y): # 使用dfs搜索,找出所有与边界O相连的O if not 0 <= x < n or not 0 <= y < m or board[x][y] != 'O': # 递归出口:dfs搜索范围不超过n*m # 且搜索的点如果不是O(以标记的A 或 X就不用再去标记) return board[x][y] = "A" # 将于边界相连的O进行标记 # 每个点的上下左右四个方向 dfs(x + 1, y) dfs(x - 1, y) dfs(x, y + 1) dfs(x, y - 1) for i in range(n): # 第一行和最后一行 dfs(i, 0) dfs(i, m - 1) for i in range(m - 1): # 第一列和最后一列 dfs(0, i) dfs(n - 1, i) # 标记完成后,对所有已标记为A的点设置为0,其他未标记的O设置为X for i in range(n): for j in range(m): if board[i][j] == "A": board[i][j] = "O" elif board[i][j] == "O": board[i][j] = "X" def solve2(self, board: List[List[str]]) -> None: """ Do not return anything, modify board in-place instead. """ # 核心思想--类似的解法,dfs不同实现,可以快10ms左右 if not board: return row = len(board) col = len(board[0]) def dfs(i, j): board[i][j] = "B" for x, y in [(-1, 0), (1, 0), (0, -1), (0, 1),(0,0)]: tmp_i = i + x tmp_j = j + y if 1 <= tmp_i < row and 1 <= tmp_j < col and board[tmp_i][tmp_j] == "O": dfs(tmp_i, tmp_j) for j in range(col): # 第一行 if board[0][j] == "O": dfs(0, j) # 最后一行 if board[row - 1][j] == "O": dfs(row - 1, j) for i in range(row): # 第一列 if board[i][0] == "O": dfs(i, 0) # 最后一列 if board[i][col-1] == "O": dfs(i, col - 1) for i in range(row): for j in range(col): # O 变成 X if board[i][j] == "O": board[i][j] = "X" # B 变成 O if board[i][j] == "B": board[i][j] = "O"
9f1d7ebe2f906827721d5007ed4c6ab110d0999b
Fastiz/artificial-intelligence-systems
/autoencoder/encoded_graph.py
576
3.625
4
import matplotlib.pyplot as plt def read_from_file(path): file = open(path, "r") lines = file.read().splitlines() return [(float(x), float(y), letter) for x, y, letter in [line.split(" ") for line in lines]] def plot(): values = read_from_file("../data") x = [x for x, y, letter in values] y = [y for x, y, letter in values] letters = [letter for x, y, letter in values] fig, ax = plt.subplots() ax.scatter(x, y) for i in range(len(values)): ax.annotate(" {0}".format(letters[i]), (x[i], y[i])) plt.show() plot()
1f5b21f2b798ec44bb1dbf0a2af2d3c37d8a5b90
rakeshsukla53/interview-preparation
/Rakesh/graph-theory-algorithms/graph_valid_tree_cycle_find.py
994
3.8125
4
from collections import OrderedDict class Solution(object): def topological_sorting(self, graph, root): state = set() def dfs(node): if node in state: raise ValueError('Cycle') else: state.add(node) for k in graph.get(node, []): dfs(k) dfs(root) return state def validTree(self, n, edges): """ :type n: int :type edges: List[List[int]] :rtype: bool """ graph = OrderedDict() for key, value in edges: if key in graph: graph[key].append(value) else: graph[key] = [value] root = graph.keys()[0] try: if len(self.topological_sorting(graph, root)) == n: return True else: return False except: return False print Solution().validTree(5, [[0, 1], [1, 2], [3, 4]])
90c9614732fe48917627cef15a0f099a03e2ff46
JenniferDominique/Arthur_Merlin_Games
/Main.py
3,790
3.828125
4
from Merlin import * from random import randint print() print('_____________________ ARTHUR MERLIN GAMES _____________________') print() #___________________ Problema das Damas _____________________# print('....... Problema das Damas .......') print() arquivos = ['casamento.txt', 'casamento no.txt', 'casamento noo.txt'] n = randint(0,2) f = open(arquivos[n]) # Abre um arquivo sorteado da lista de arquivos damas = [] # Lista queridos = {} # Dicionário for pessoa in f: pessoa = pessoa.strip().split() # Strip -> tira os espaços do início e do fim do texto # Split -> separa os elementos do texto a partir de um parâmetro queridos[pessoa[0]] = pessoa[1:] # O primeiro elemento da lista nome é a key (chave) # Os outros são os amigos do nome key damas.append(pessoa[0]) # Guardar o nome das damas # Elas também são as chaves para o dicionário dos queridos #print(queridos) x = 0 y = False while x < (len(damas)-1): if len(queridos[damas[x]]) == 0: print(f'A {damas[x]} não tem preferências, ela prefere cuidar de 7 gatos ᓚᘏᗢ') print('Isso pode ser um problema para o reino ಠ_ಠ') print() y = True break x = x + 1 if y == False: for s in enumerações(damas): # Enumeração -> Fazer todas as combinações possíveis # desde a menor quantidade até a maior quantidade possível # Função descrita no arquivo Merlin.py pessoa = [] for d in s: pessoa.extend(queridos[d]) if len(s) > len(set(pessoa)): # Se a quantidade de damas for maior do que # a quantidade de cavaleiros únicos na lista print('Não é possível casar todas as damas, pois a') s = ' e '.join(s) # Nome das damas pessoa = ' '.join(set(pessoa)) # Querido disputado print(f'{s} gostam de {pessoa} ¯\_(ツ)_/¯') print() break else: print('É possível casar todas as damas!! (❤ ω ❤)') print() #___________________ Problema dos Cavaleiros ___________________# print('....... Problema dos Cavaleiros .......') print() arquivos = ['cavaleiros.txt', 'cavaleiros no.txt', 'cavaleiros noo.txt'] n = randint(0,2) m = open(arquivos[n]) # Abre um arquivo sorteado da lista de arquivos cavaleiros = [] # Lista amigos = {} #Dicionário for pessoa in m: pessoa = pessoa. strip().split() amigos[pessoa[0]] = pessoa[1:] # O primeiro elemento da lista nome é a key (chave) # Os outros são os amigos do nome key cavaleiros.append(pessoa[0]) # Guardar o nome dos cavaleiros # Eles também são as chaves para o dicionário dos amigos #print(amigos) x = 0 y = False while x < (len(cavaleiros)-1): if len(amigos[cavaleiros[x]]) < 2: print(f'O {cavaleiros[x]} não tem amigos suficientes para se sentar a mesa') print(f'que seriam no mínimo 2, por isso o {cavaleiros[x]} pode ser um problema (⊙_⊙;)') print() y = True break x = x + 1 if y == False: for p in permutações(cavaleiros): # Permutação -> Trocar as posições dos valores # todas as posições preenchidas possíveis # Função descrita no arquivo Merlin.py for k in range(len(p)): if p[k] not in amigos[p[(k+1)%len(p)]]: break else: print('Conseguimos uma mesa para todos os cavaleiros \o/') print('Sentados na seguinte sequência:') print(' '.join(p)) break else: print('Não é possível arrumar uma mesa para os cavaleiros! (>﹏<)')
360cd4c249e7685721cfeb212cdd75933f24508b
jrschmiedl/Sudoku
/SudokuSolver.py
2,227
3.828125
4
# Sudoku Solver 1.0 # @author Jacob Schmiedl puzzle = [ [7,8,0,4,0,0,1,2,0], [6,0,0,0,7,5,0,0,9], [0,0,0,6,0,1,0,7,8], [0,0,7,0,4,0,2,6,0], [0,0,1,0,5,0,9,3,0], [9,0,4,0,6,0,0,0,5], [0,7,0,3,0,0,0,1,2], [1,2,0,0,0,7,4,0,0], [0,4,9,2,0,6,0,0,7] ] # solves the puzzle def solve(board): # base case for recursion find = find_empty_spots(board) if not find: return True else: row, col = find # loops through every single num to see if it valid for i in range(1, 10): if valid(board, i, (row, col)): board[row][col] = i # sees if it works if solve(board): return True # resets if it is not valid board[row][col] = 0 return False # checks if the spot is valid def valid(board, num, pos): # checks the row for i in range(len(board[0])): if board[pos[0]][i] == num and pos[1] != i: return False # checks the column for i in range(len(board)): if board[i][pos[1]] == num and pos[0] != i: return False # checks the 3 by 3 square x_board = pos[1] // 3 y_board = pos[0] // 3 for i in range(y_board * 3, y_board * 3 + 3): for j in range(x_board * 3, x_board * 3 + 3): if board[i][j] == num and (i,j) != pos: return False return True # finds empty spots on the board def find_empty_spots(board): for i in range(len(board)): for j in range(len(board[0])): if board[i][j] == 0: return (i, j) return None # prints out the Sudoku Board def print_board(board): for i in range(len(board)): if (i % 3 == 0) and i != 0: print("- - - - - - - - - - - - -") for j in range(len(board[0])): if (j % 3 == 0) and j != 0: print(" | ", end="") if j == 8: print(board[i][j]) else: print(str(board[i][j]) + " ", end="") print("Sudoku Puzzle Given") print_board(puzzle) solve(puzzle) print("Solution to the Puzzle") print_board(puzzle)
7ebc2621de57aba29a68be3d6dacaa16ebf4c4dc
yywecanwin/PythonLearning
/day03/13.猜拳游戏.py
657
4.125
4
# -*- coding: utf-8 -*- # author:yaoyao time:2019/9/28 import random # 写一个死循环 while True: # 1.从键盘录入一个1-3之间的数字表示自己出的拳 self = int(input("请出拳")) # 2.定义一个变量赋值为1,表示电脑出的拳 computer = random.randint(1,3) print(computer) if((self == 1 and computer == 2) or (self == 2 and computer == 3) or (self == 3 and computer == 1)): print("我又赢了,我妈喊我 回家吃饭了") break elif self == computer: print("平局,我们在杀一盘") else: print("不行了,我要和你杀到天亮") break
ffcef51cc07f551c87aa41906b41ece138dcd9e9
daniel-reich/ubiquitous-fiesta
/biJPWHr486Y4cPLnD_13.py
244
3.578125
4
def chunkify(lst, size): output=[] i=0 new_list=[] n=0 while i < len(lst): output.append([]) #print(output) for k in range(0,size): if i < len(lst): output[n].append(lst[i]) i+=1 else: break n+=1 return output
c765b63a9a589e540afec1e34b96e383f5ebc1a3
aman9924/Python-Projects
/HealthManage.py
4,050
3.84375
4
def getdate(): import datetime return datetime.datetime.now() # time= getdate() # print(time) def lock(k): if (k == 1): p = int(input("Enter 1-Exercise 2-Food:- ")) if (p == 1): value = input("Enter The Exercise:- ") with open("Aman-Exercise.txt", "a") as op: time = getdate() op.write(str(time) + " - " + value+"\n") print("Your Response Has Been Entered") elif (p == 2): value = input("Enter The Food:- ") with open("Aman-Food.txt", "a") as op: time = getdate() op.write(str(time) + " - " + value+"\n") print("Your Response Has Been Entered") else: print("Enter Correct Option") elif (k == 2): p = int(input("Enter 1-Exercise 2-Food:- ")) if (p == 1): value = input("Enter The Exercise:- ") with open("Amar-Exercise.txt", "a") as op: time = getdate() op.write(str(time) + " - " + value) print("Your Response Has Been Entered") elif (p == 2): value = input("Enter The Food:- ") with open("Amar-Food.txt", "a") as op: time = getdate() op.write(str(time) + " - " + value) print("Your Response Has Been Entered") else: print("Enter Correct Option") elif (k == 3): p = int(input("Enter 1-Exercise 2-Food:- ")) if (p == 1): value = input("Enter The Exercise:- ") with open("Golu-Exercise.txt", "a") as op: time = getdate() op.write(str(time) + " - " + value) print("Your Response Has Been Entered") elif (p == 2): value = input("Enter The Food:- ") with open("Golu-Food.txt", "a") as op: time=getdate() op.write(str(time) + " - " + value) print("Your Response Has Been Entered") else: print("Enter Correct Option") def retrieve(k): if (k == 1): p = int(input("Enter 1-Exercise 2-Food:- ")) if (p == 1): # value = input("Enter The Exercise:- ") with open("Aman-Exercise.txt") as op: for text in op: print(text) elif (p == 2): with open("Aman-Food.txt") as op: for text in op: print(text) else: print("Enter Correct Option") elif (k == 2): p = int(input("Enter 1-Exercise 2-Food:- ")) if (p == 1): # value = input("Enter The Exercise:- ") with open("Amar-Exercise.txt") as op: for text in op: print(text) elif (p == 2): with open("Amar-Food.txt") as op: for text in op: print(text) else: print("Enter Correct Option") elif (k == 3): p = int(input("Enter 1-Exercise 2-Food:- ")) if (p == 1): # value = input("Enter The Exercise:- ") with open("Golu-Exercise.txt") as op: for text in op: print(text) elif (p == 2): with open("Golu-Food.txt") as op: for text in op: print(text) else: print("Enter Correct Option") def again(): a=int(input("Enter 1 for Retirive or 2 to lock:- ")) if(a==1): b=int(input("Enter 1-Aman 2-Amar 3-Golu:- ")) retrieve(b) else: b=int(input("Enter 1-Aman 2-Amar 3-Golu:- ")) lock(b) while(True): ans = input("Do you Want to Continue: Type y-Yes or n-No:- ") if(ans=='y'): again() elif(ans=='n'): break else: print("Enter Correct Response")
6d891f3138392da3eb552cd5228069fd0adf63fb
RaviSankarRao/PythonBasics
/11_Reading_Files.py
632
3.5625
4
# using OPEN cmd to open files # first param - File name with relative path # second param - mode # r - read, w - write, a - append, r+ - read and write employee_file = open("Employees", "r") # check if file is readable print(employee_file.readable()) # read - read the entire file # print(employee_file.read()) # readline - read line by line # print(employee_file.readline()) # print(employee_file.readline()) # readlines - convert each line to array # print(employee_file.readlines()) for employee in employee_file.readlines(): print(employee) # always close thf ile at the end of your execution employee_file.close()
0d1ff287d135793de6708134ae3a804afb2d2339
naveensantu/Open_cv-Tutorial
/drawing_assesment.py
2,038
3.8125
4
# # Image Basics Assessment import numpy as np import cv2 import matplotlib.pyplot as plt #%matplotlib inline # #### TASK: Open the *dog_backpack.jpg* image from the DATA folder and display it in the notebook. Make sure to correct for the RGB order. image=cv2.imread(r"D:\Computer Vision with OpenCV and Deep Learning\Computer-Vision-with-Python\DATA\dog_backpack.jpg") image_cvt=cv2.cvtColor(image, cv2.COLOR_BGR2RGB) plt.imshow(image_cvt) image_cvt2=image_cvt.copy() # #### TASK: Flip the image upside down and display it in the notebook. image_flipped=cv2.flip(image_cvt, 0) plt.imshow(image_flipped) # #### TASK: Draw an empty RED rectangle around the dogs face and display the image in the notebook. rectangle=cv2.rectangle(image_cvt,(200,750),(625,350),(255,0,0), thickness=7) plt.imshow(image_cvt) # #### TASK: Draw a BLUE TRIANGLE in the middle of the image. The size and angle is up to you, but it should be a triangle (three sides) in any orientation. verticies=np.array([[250,700],[400,400],[650,700]],np.int32) pts=verticies.reshape(-1,1,2) triangle=cv2.polylines(image_cvt, [pts], isClosed=True, color=(0,0,255), thickness=10) plt.imshow(image_cvt) # ### BONUS TASK. Can you figure our how to fill in this triangle? It requires a different function that we didn't show in the lecture! See if you can use google search to find it. cv2.fillPoly(image_cvt2, [pts], (0,0,255)) plt.imshow(image_cvt2) # #### TASK:Create a script that opens the picture and allows you to draw empty red circles whever you click the RIGHT MOUSE BUTTON DOWN. def create_circle(event,x,y,flag,params): if event == cv2.EVENT_RBUTTONDOWN: cv2.circle(img, (x,y), 100, (0,0,255), thickness=10) img = cv2.imread(r"D:\Computer Vision with OpenCV and Deep Learning\Computer-Vision-with-Python\DATA\dog_backpack.jpg") cv2.namedWindow(winname="circle_on_dog") cv2.setMouseCallback("circle_on_dog",create_circle) while True: cv2.imshow("circle_on_dog",img) if cv2.waitKey(20) & 0xFF == 27: break cv2.destroyAllWindows()
20c009fa3f977cbc29a33827699e78c6da08eb9f
smv5047/Sprint-Challenge--Data-Structures-Python
/ring_buffer/ring_buffer.py
1,067
3.546875
4
class RingBuffer: def __init__(self, capacity): self.capacity = capacity self.storage = [] self.buffer_pointer = 0 def append(self, item): # Is buffer at capacity? if len(self.storage) < self.capacity: self.storage.insert(len(self.storage), item) return else: self.storage[self.buffer_pointer] = item if self.buffer_pointer < self.capacity-1: self.buffer_pointer += 1 else: self.buffer_pointer = 0 return def get(self): return self.storage new_buffer = RingBuffer(5) new_buffer.append(1) new_buffer.append(2) new_buffer.append(3) new_buffer.append(4) new_buffer.append(5) new_buffer.append(6) new_buffer.append(7) new_buffer.append(8) new_buffer.append(9) print(new_buffer.buffer_pointer) new_buffer.append(45) print(new_buffer.buffer_pointer) # new_buffer.append(46) # new_buffer.append(47) # new_buffer.append(48) # new_buffer.append(49) # new_buffer.append('b') print(new_buffer.get())
d1709b74fd6754a389dc09c9429413f7479c2efc
Brienyll/python-automate
/Map.py
196
3.71875
4
def add_five(x): return x + 5 nums = [11, 22, 33, 44, 55] result = list(map(add_five, nums)) print(result) nums = [11, 22, 33, 44, 55] result = list(map(lambda x: x+5, nums)) print(result)
6d950efdfc2fd19da03b627f8a8b388929e1a011
warsang/CCTCI
/chapter2/2.3-false/deleteMiddleNode.py
804
3.734375
4
class node(object): def __init__(self,name,child): self.name = name self.child = child def main(): llist = [] f = node("f",None) e = node("e",f) d = node("d",e) c = node("c",d) b = node("b",c) a = node("a",b) llist = [a,b,c,d,e,f] deleteNode(c,llist) Node = a while True: if Node.child is None: print(Node.name) break else: print( Node.name + "->") Node = Node.child def deleteNode(node,llist): head = llist[0] while True: if head.child is None: break if head.child == node: head.child = head.child.child break else: head = head.child if __name__ == "__main__": main()
75562289656f729df56a9f59fd7e0a1dbccd89d8
WaterH2P/Algorithm
/LeetCode/751-1000/836 isRectangleOverlap.py
950
3.9375
4
# 【简单】836. 矩形重叠 # 矩形以列表 [x1, y1, x2, y2] 的形式表示,其中 (x1, y1) 为左下角的坐标,(x2, y2) 是右上角的坐标。 # 如果相交的面积为正,则称两矩形重叠。需要明确的是,只在角或边接触的两个矩形不构成重叠。 # 给出两个矩形,判断它们是否重叠并返回结果。 class Solution: def isRectangleOverlap(self, rec1, rec2) -> bool: # 判断不重叠 if rec1[3] <= rec2[1] or rec2[3] <= rec1[1] or rec1[2] <= rec2[0] or rec2[2] <= rec1[0]: return False return True if __name__ == '__main__': s = Solution() result = True rec1 = [0,0,2,2] rec2 = [1,1,3,3] print(s.isRectangleOverlap(rec1, rec2)) result = False rec1 = [0,0,1,1] rec2 = [1,0,2,1] print(s.isRectangleOverlap(rec1, rec2)) result = True rec1 = [4,4,14,7] rec2 = [4,3,8,8] print(s.isRectangleOverlap(rec1, rec2))
9a5e91177601e8939a7695be41786b7666a9e08f
weardo98/Github
/1.5.3/1.5.3.PY radius_changer.py
1,458
4.21875
4
##### # radius_changer.py # # Creates a Scale and a Canvas. Updates a circle based on the Scale. # (c) 2013 PLTW # version 11/1/2013 #### import Tkinter #often people import Tkinter as * ##### # Create root window #### root = Tkinter.Tk() ##### # Create Model ###### radius_intvar = Tkinter.IntVar() radius_intvar.set(100) #initialize radius # center of circle x = 640 y = 512 ###### # Create Controller ####### # Event handler for slider def radius_changed(new_intval): # Get data from model # Could do this: r = int(new_intval) r = radius_intvar.get() # Controller updating the view canvas.coords(circle_item, x-x, y-r, x+x, y+r) # Instantiate and place slider radius_slider = Tkinter.Scale(root, from_=1, to=360, variable=radius_intvar, label='Radius', command=radius_changed) radius_slider.grid(row=1, column=0, sticky=Tkinter.W) # Create and place directions for the user text = Tkinter.Label(root, text='Drag slider \nto adjust\ncircle.') text.grid(row=0, column=0) ###### # Create View ####### # Create and place a canvas canvas = Tkinter.Canvas(root, width=1280, height=1024, background='#FFFFFF') canvas.grid(row=0, rowspan=2, column=1) # Create a circle on the canvas to match the initial model r = radius_intvar.get() circle_item = canvas.create_oval(x-r, y-y, x+r, y+y, outline='#000000', fill='#00FFFF') ####### # Event Loop ####### root.mainloop()
f4e90092c38faf6e1636c97d5da54294e6874f36
PaulKitonyi/Python-Practise-Programs
/testing_classes/Employee/employee.py
534
3.84375
4
class Employee(): """class to simulate Employees""" def __init__(self, first, last, annual_salary): self.first = first self.last = last self.annual_salary = annual_salary def give_raise(self, amount=''): self.annual_salary += 5000 amount = amount if amount: self.annual_salary += amount return self.annual_salary # emp_1 = Employee('pau', 'kitonyi', 1000) # emp_1.give_raise(1000) # print(emp_1.annual_salary)
d684a7e8750fa8ee27cc9f9f04cc7e7bee972688
georgePopaEv/python-exercise
/DAY5P.py
1,401
3.9375
4
# ord sa transformam din char in int # chr sa transformam din int in char # caractere speciale # start 33 ----------------Finish 129 # 33 la 47 inclusiv char special 58 la 64, 91 la 96, 123 la 128 # 48 la 57 inclusiv cifre # 65 la 90 si de la 97 la 122 litere mari si mici import random print("Bine ai venit la Generatorul de parole BY POPA GEORGE-ALEXANDRU <3") cifre = [] litere = [] caractere = [] for i in range(33, 127): if (i >= 48) & (i <= 57): cifre.append(chr(i)) elif ((i >= 65) & (i <= 90)) | ((i >= 97) & (i <= 122)): litere.append(chr(i)) else: caractere.append(chr(i)) password = '' print("Pentru a parola sigura aceasta trebuie sa contina : \n ") print("-- 8 elemente") print("-- cel puitin o litera mica") print("-- cel putin litera mare") print("-- cel putin 1 caracter special") print("-- cel putin o cifra") nr_litere = int(input("Cate litere vrei sa contina parola? :")) nr_cifre = int(input("Cate cifre vrei sa contina parola? :")) nr_char = int(input("Cate caractere vrei sa contina? :")) for i in range(nr_cifre): password += random.choice(cifre) for i in range(nr_litere): password += random.choice(litere) for i in range(nr_char): password += random.choice(caractere) # amestecarea caracterelor print(f"Parola generata de catre noi este == \"{''.join(random.sample(password, len(password)))}\"")
6a6d8db5763d38ccac76aadfadf5d6c1c5d83c58
stolksdorf/BGSAWorkshop
/Python/ex2.py
410
3.515625
4
import sys import csv print sys.argv #Make sure you inputed a filename if len(sys.argv) < 2: print "Must provide an input file name" sys.exit() inputFilename = sys.argv[1] dataset = csv.reader(open(inputFilename, 'rb')) for rowNumber, row in enumerate(dataset): # Don't process the first row, all the column names if rowNumber != 0: concetration = float(row[5]) if concetration > 300: print row
f999d2da67e27fae68bdeaedd3d53b9381a68cf8
NARMATHA-R/PYTHON-PRACTICE
/replace() .py
84
3.75
4
txt = "I like bananas" x = txt.replace("bananas", "mango") print(x) #I like mango
aa35a95f312fbd81d579618fd9cbcf0314762899
a1347539/algorithms-and-data-structure
/dataStructure/heap.py
1,886
3.5625
4
class maxHeap: def __init__(self): self.heap = [] self.size = 0 def parent(self, i): i+=1 if i == 1: return None return (i-1) // 2 def leftChild(self, i): if i * 2 > self.size: return None return i * 2 def rightChild(self, i): if i * 2 + 1 > self.size: return None return i* 2 + 1 def swap(self, i, j): self.heap[i], self.heap[j] = self.heap[j], self.heap[i] def heapify(self, i, up): if up: while self.parent(i) != None and self.heap[i] > self.heap[self.parent(i)]: self.swap(i, self.parent(i)) i = self.parent(i) if not up: while True: if (self.leftChild(i) != None or self.rightChild(i) != None): if (self.heap[i] < self.heap[self.leftChild(i)] or self.heap[i] < self.heap[self.rightChild(i)]): if (self.heap[self.leftChild(i)] < self.heap[self.rightChild(i)]): self.swap(i, self.rightChild(i)) i = self.rightChild(i) else: self.swap(i, selfleftChild(i)) i = self.leftChild(i) else: break def insert(self, i, obj): self.size += 1; self.heap.insert(i, obj) self.heapify(i, True) def append(self, obj): self.size += 1; self.heap.append(obj) self.heapify(len(self.heap)-1, True) def delete(self, i): self.size -= 1; self.swap(i, -1) self.heap.pop() self.heapify(i, False) h = maxHeap() h.append(5) h.append(21) h.append(43) h.append(534) h.append(2)
b6c14b24676d59cc28dde57a96cdca5f6f498e14
skipkolch/Linear_regression
/Task_5/Task 5/featureNormalize.py
2,335
3.5625
4
import numpy as np from numpy.matlib import repmat def featureNormalize(X): """ Функция позволяет вычислить нормализованную версию матрицы объекты-признаки X со средним значением для каждого признака равным 0 и среднеквадратическим отклонением равным 1 """ X_norm = X mu = np.zeros(X.shape[1]) sigma = np.zeros(X.shape[1]) # ====================== Ваш код здесь ====================== # Инструкция: во-первых, необходимо вычислить среднее значение # каждого признака и вычесть его из значений соответствующих # признаков в матрице X. Сохранить вектор средних в переменную mu. # Во-вторых, необходимо вычислить среднеквадратическое отклонение # для каждого признака и разделить на него соответствующий признак # с учетом нормализации на среднее значение. Сохранить вектор # среднеквадратических отклонений в переменную sigma. Необходимо # отметить, что X является матрицей, в которой каждый столбец # является свойством, а каждая строка - объектом. Нормализацию # требуется выполнить раздельно для каждого свойства # ============================================================ for i in range(mu.shape[0]): mu[i] = np.mean(X[:,i]) sigma[i] = np.std(X_norm[:,i], ddof = 1) X[:,i] = np.divide((X[:,i] - mu[i]), sigma[i]) # for i in range(mu.shape[0]): # mu[i] = np.mean(X[:,i]) # X_norm[:,i] = np.subtract(X_norm[:,i],mu[i]) # sigma[i] = np.std(X_norm[:,i], ddof = 1) # X_norm[:,i] = np.divide(X_norm[:,i], sigma[i]) return X_norm, mu, sigma
d72785f1a4bf7443e2563e18f31b0cfdda8cbf37
jawnbriggz/Trigrams
/trigrammer.py
2,587
3.703125
4
import re import sys import string import operator def book_parser(x): full_text = [] for line in x: # strip of punctuation and lowercase it line = line.lower() line = line.translate(str.maketrans('','',string.punctuation)) temp = line.split() full_text += temp OVERALL_LENGTH = len(full_text) return(full_text, OVERALL_LENGTH) def gramGenerator(full_text, OVERALL_LENGTH): unigrams = {} bigrams = {} trigrams = {} first = 0 second = 1 third = 2 for t in full_text: # construct grams bigram = [] trigram = [] if(first <= OVERALL_LENGTH - 3): trigram.append(full_text[first]) trigram.append(full_text[second]) trigram.append(full_text[third]) if(first <= OVERALL_LENGTH - 2): bigram.append(full_text[first]) bigram.append(full_text[second]) first += 1 second += 1 third += 1 s = gram_to_string(trigram) strang = gram_to_string(bigram) # create the dictionaries if(s in trigrams): trigrams[s] += 1 else: trigrams[s] = 1 if(strang in bigrams): bigrams[strang] += 1 else: bigrams[strang] = 1 if(t in unigrams): unigrams[t] += 1 else: unigrams[t] = 1 return(unigrams, bigrams, trigrams) def gram_to_string(gram): s = "" idx = 0 y = len(gram) for w in gram: if(idx == y): s += w else: s += w s += " " idx += 1 return s def print_to_file(bigrams, trigrams): # save trigrams and # of occurrences to a file file = open("trigrams_output.txt", "w") for t in trigrams: count = str(trigrams[t]) file.write(t) file.write(" ") file.write(count) file.write("\n") file.close() # save bigrams and # of occurrences to a file file = open("bigrams_output.txt", "w") for t in bigrams: count = str(bigrams[t]) file.write(t) file.write(" ") file.write(count) file.write("\n") file.close() def main(): book = sys.argv[1] # open the file, do what you gotta do and then close it. x = open(book) parsed_text = book_parser(x) text = parsed_text[0] OVERALL_LENGTH = parsed_text[1] x.close() # GET THE GRAMS grams = gramGenerator(text, OVERALL_LENGTH) unigrams = grams[0] bigrams = grams[1] trigrams = grams[2] most_occurring_word = max(unigrams.items(), key=operator.itemgetter(1))[0] most_occurring_bigram = max(bigrams.items(), key=operator.itemgetter(1))[0] most_occurring_trigram = max(trigrams.items(), key=operator.itemgetter(1))[0] print("THE MOST OCCURRING WORD: ", most_occurring_word) print("THE MOST OCCURRING BIGRAM: ", most_occurring_bigram) print("THE MOST OCCURRING TRIGRAM: ", most_occurring_trigram) main()
1e238c16531818644f8b43c98cbed109ca77ac22
LittleAndroidBunny/Python_Cheatsheet_Nohar_Batit
/Beer-sheva Ref/Excercises/e_Linked_list.py
3,936
4.15625
4
from b_ll_node import Node class LinkedList: # Why doesn't the class inherit the node class? def __init__(self, seq=None): """ Linked list init function :param seq: Use seq != none to generate a linked list from any python sequence type """ self.next = None self.length = 0 if seq is not None: for x in seq[::-1]: self.add_at_start(x) # Use add_at_start in reverse order due to O(1) complexity for each insertion def __repr__(self): out = "" p = self.next while p is not None: out += str(p) + " -> " # str invokes __repr__ of class Node p = p.next return out def __len__(self): """ called when using Python's length() """ return self.length def add_at_start(self, val): """ add node with value val at the list head """ p = self tmp = p.next p.next = Node(val) p.next.next = tmp self.length += 1 def add_at_end(self, val): """ add node with value val at the list tail """ p = self while p.next is not None: p = p.next p.next = Node(val) self.length += 1 def insert(self, loc, val): """ add node with value val after location 0<=loc<length of the list """ assert 0 <= loc < len(self) p = self for i in range(0, loc): p = p.next tmp = p.next p.next = Node(val) p.next.next = tmp self.length += 1 def __getitem__(self, loc): """ called when using L[i] for reading return node at location 0<=loc<length """ assert 0 <= loc < len(self) p = self.next for i in range(0, loc): p = p.next return p def __setitem__(self, loc, val): """ called when using L[loc]=val for writing assigns val to node at location 0<=loc<length """ assert 0 <= loc < len(self) p = self.next for i in range(0, loc): p = p.next p.value = val return None def find(self, val): """ find (first) node with value val in list """ p = self.next loc = 0 # in case we want to return the location while p is not None: if p.value == val: return loc, p else: p = p.next loc = loc + 1 # in case we want to return the location return None def delete(self, loc): """ delete element at location 0<=loc<length """ assert 0 <= loc < len(self) p = self for i in range(0, loc): p = p.next # p is the element BEFORE loc p.next = p.next.next self.length -= 1 def insert_ordered(self, val): """ assume self is an ordered list, insert Node with val in order """ p = self q = self.next while q is not None and q.value < val: p = q q = q.next new_node = Node(val) p.next = new_node new_node.next = q self.length += 1 def find_ordered(self, val): """ assume self is an ordered list, find Node with value val """ p = self.next while p is not None and p.value < val: p = p.next if p is not None and p.value == val: return p else: return None def reverse(self): prev = None curr = self.next while curr is not None: tmp = curr.next curr.next = prev prev = curr curr = tmp self.next = prev return self def to_standard_list(self): result = [None] * len(self) p = self.next for i in range(len(self)): result[i] = p.value p = p.next return result
f163b69671fbd87d129be56c16749773fe145bad
shuvo14051/python-data-algo
/Problem-solving/HackerRank/p18-Mutations.py
322
3.515625
4
def mutate_string(s, position, character): li = [] result = '' for i in s: li.append(i) li[position] = character for j in li: result += j return result if __name__ == '__main__': s = input() i, c = input().split() s_new = mutate_string(s, int(i), c) print(s_new)
66ca15e4f5a7cef6f39046deb431194e358cbbfa
rdghenrique94/Estudos_Python
/Curso_Python/Modulo2/ex042.py
632
3.875
4
def main(): print("="*30) print("Analisando Triangulos") print("="*30) r1 = float(input("Primeiro Segmento: ")) r2 = float(input("Segundo Segmento: ")) r3 = float(input("Terceiro Segmento: ")) if r1 == r2 != r3 or r1 == r3 != r2 or r2 == r1 != r3 or r2 == r3 != r1 or r3 == r1 != r2 or r3 == r2 != r1: print("O triangulo é Isorceles") elif r1 == r2 == r3: print("O triangulo é Equilatero") elif r1 != (r2 != r3) or r1 != (r3 != r2) or r2 != (r1 != r3) or r2 != (r3 != r2) or r3 != (r1!=r2) or r3 !=(r2!=r1): print("O triangulo é Escaleno") return main() main()
2ea32c0747ce15b2a5e2069ef54a8b7212f6c939
prajwalccc13/Hacktoberfest2020
/vigenere.py
386
4.125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ @author: darshasawa """ phrase = input("Please enter the phrase: ") key = input("Enter the key: ") phrase = phrase.upper() key=key.upper() key_length = len(key) encrypt_phrase = "" for i in range(len(phrase)): value =(ord(phrase[i])+ord(key[(i%key_length)]))%26 encrypt_phrase+=chr(value+65) print("\n"+encrypt_phrase)
f92d4b48b24066bd4887966b5238f54428a4daf3
vitorflc/flasktutorial
/tutorial4.py
903
3.671875
4
## Tutorial 4: HTTP Methods (GET/POST) & Retrieving Form Data # get - insecure way to get info - you don't care if people see it (link etc) # post - secure way (form data, not going to be saved) from flask import Flask, redirect, url_for, render_template, request app = Flask(__name__) @app.route("/") #define como acessar esta página específica (poderia ser /home) def home(): return render_template("index.html") @app.route("/login", methods=["POST","GET"]) def login(): if request.method == "POST": user = request.form["nm"] #vai me dar o dado que foi inputado dentro de "nm" em login.html request.form vem como dicionário, portanto deve ser único return redirect(url_for("user", usr=user)) else: return render_template("login.html") @app.route("/<usr>") def user(usr): return f"<h1>{usr}</h1>" if __name__ == '__main__': app.run(debug=True)
edda1e2e6d9fd0cbbe25b3a9a956de087c84fc1f
rozen03/codeforces-solutions
/757A.py
223
3.703125
4
#!/usr/bin/env python3 text = input() bolba="Bulbasaur" chars = {} for i in bolba: chars[i] = 0 for i in text: if i in bolba: chars[i]+=1 chars['u'] = chars['u']//2 chars['a'] = chars['a']//2 print(min(chars.values()))
2bd4ef9b6c8264110837172b7e33f3080ace69e6
ironboxer/leetcode
/python/337.py
6,113
4
4
""" https://leetcode.com/problems/house-robber-iii/ The thief has found himself a new place for his thievery again. There is only one entrance to this area, called the "root." Besides the root, each house has one and only one parent house. After a tour, the smart thief realized that "all houses in this place forms a binary tree". It will automatically contact the police if two directly-linked houses were broken into on the same night. Determine the maximum amount of money the thief can rob tonight without alerting the police. Example 1: Input: [3,2,3,null,3,null,1] 3 / \ 2 3 \ \ 3 1 Output: 7 Explanation: Maximum amount of money the thief can rob = 3 + 3 + 1 = 7. Example 2: Input: [3,4,5,1,3,null,1] 3 / \ 4 5 / \ \ 1 3 1 Output: 9 Explanation: Maximum amount of money the thief can rob = 4 + 5 = 9. """ # Definition for a binary tree node. class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution0: """ according to defination """ def rob(self, root: TreeNode) -> int: def f(root): if not root: return 0 val = 0 if root.left: val += f(root.left.left) + f(root.left.right) if root.right: val += f(root.right.left) + f(root.right.right) return max(val + root.val, f(root.left) + f(root.right)) return f(root) class Solution1: def rob(self, root: TreeNode) -> int: memo = {} def f(root): if not root: return 0 if root in memo: return memo[root] val = 0 if root.left: val += f(root.left.left) + f(root.left.right) if root.right: val += f(root.right.left) + f(root.right.right) max_val = max(val + root.val, f(root.left) + f(root.right)) memo[root] = max_val return max_val return f(root) class Solution: def rob(self, root: TreeNode) -> int: def f(root): if not root: return [0, 0] a, b = f(root.left), f(root.right) # 这个递归的结构有点难以理解 return [max(a) + max(b), root.val + a[0] + b[0]] return max(f(root)) class Solution: """ 太过高级的算法实际上已经超出的你的理解能力了 需要循序渐进 """ def rob(self, root: TreeNode) -> int: """ 这个算法虽然慢但是有效 是完全按照题意来的 所以是正确的 """ def f(root): if not root: return 0 l, r = f(root.left), f(root.right) val = root.val if root.left: val += f(root.left.left) + f(root.left.right) if root.right: val += f(root.right.left) + f(root.right.right) return max(val, l + r) return f(root) class Solution: def rob(self, root: TreeNode) -> int: """ 这个算法其实更加抽象 或者去类别 House Robber 这道题的不用数组的dp方式 """ def f(root): if not root: return 0, 0 l, r = f(root.left), f(root.right) # 包含roor节点的最大值 不包含root节点的最大值 return root.val + l[1] + r[1], max(l) + max(r) return max(f(root)) # Another Slow But Work # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None from functools import lru_cache class Solution: def rob(self, root: TreeNode) -> int: @lru_cache def f(root): if root is None: return 0 val = root.val if root.left: val += f(root.left.left) + f(root.left.right) if root.right: val += f(root.right.left) + f(root.right.right) return max(val, f(root.left) + f(root.right)) return f(root) # Solution 1 Slow but Work and Easy from functools import lru_cache class Solution: def rob(self, root: TreeNode) -> int: @lru_cache def f(root): if root is None: return 0 retval = root.val if root.left: retval += f(root.left.left) + f(root.left.right) if root.right: retval += f(root.right.left) + f(root.right.right) return max(retval, f(root.left) + f(root.right)) return f(root) # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def rob(self, root: TreeNode) -> int: # f return two values # first is max value with root.val # last is max value without root.val def f(root): if root is None: return 0, 0 l, r = f(root.left), f(root.right) # 这里的两个返回值分别表示 root.val + sub sub tree max val # max subtree val # 所以第二个应该是 max(l) + max(r) # 表示需要将子树的值考虑进去 而 第一个因为有root.val参与 所以子树的值不能考虑进去 return root.val + l[1] + r[1], max(l) + max(r) return max(f(root)) if __name__ == '__main__': root = TreeNode(3) root.left = TreeNode(2) root.right = TreeNode(3) root.left.right = TreeNode(3) root.right.right = TreeNode(1) print(Solution().rob(root)) root = TreeNode(3) root.left = TreeNode(4) root.right = TreeNode(5) root.left.left = TreeNode(1) root.left.right = TreeNode(3) root.right.right = TreeNode(1) print(Solution().rob(root))
92c22b5a180955961487ae6f2cc7771a549650d6
oguzbalkaya/ProgramlamaLaboratuvari
/fibonacci.py
252
3.75
4
#n. fibonacci sayısını bulur. known={0:0,1:1} def fibo_rec(n): if n in known: return known[n] else: result = fibo_rec(n-1)+fibo_rec(n-2) known[n]=result #print(known) return result print(fibo_rec(10))
4459e52dbc267e4b68605a2d5611d8173123af80
kurrenda/aplikacja
/Zajecia_2/Cw3.py
121
3.875
4
def delete(letter, text): print(text.replace(letter, "")) txt = "Ha Ala Ha ma Ha kota Ha" a = "Ha" delete(a, txt)
62dbac5648858507b73c587f96dfb867506d0190
SpringSnowB/All-file
/m1/d3/esercise14.py
708
3.71875
4
""" 比较四个数大小 """ wight1 = float(input("请输入第一个人的体重:")) wight2 = float(input("请输入第二个人的体重:")) wight3 = float(input("请输入第三个人的体重:")) wight4 = float(input("请输入第四个人的体重:")) # if wight1>=wight2 and wight1>=wight3 and wight1>=wight4: # print("最重的是:"+str(wight1)) # elif wight2>=wight3 and wight2>=wight4: # print("最重的是:"+str(wight2)) # elif wight3>=wight4: # print("最重的是:" + str(wight3)) # else: # print("最重的是:" + str(wight4)) i = wight1 if i < wight2: i = wight2 if i < wight3: i = wight3 if i < wight4: i = wight4 print("最重的是:"+str(i))
3f466095480bd6735b808ec2a3ba24df585bab3e
seangz/PythonCrash
/UserInput/pizzatoppings.py
214
3.8125
4
prompt = "\nWhat pizza toppings do you want? " prompt += "\nSay 'done' when you're done with your toppings. " message = "" while message != 'done': message = input(prompt) if message != 'done': print(message)
4da294427a1ea95b3caa76fb1afa82acb1a73f0d
manelbonilla/hackerrank
/006.Arrays Left Rotation.py
332
3.8125
4
#!/bin/python3 import math import os import random import re import sys # Complete the rotLeft function below. def rotLeft(a, d): for x in range(0, d): a.append(a.pop(0)) return a #Input #2 # 1, 2, 3, 4 #Expected Output #3, 4, 1, 2 list = [1, 2, 3, 4] print(str(rotLeft(list, 2)))
141ad8951be67835912e00db310bf236e329b125
joao-lopesr/Exercice-Lists
/List 4 Ex 3.py
92
3.71875
4
List = [1, 3, 5, 7, 9, 10] addition = [2, 4, 6, 8] List[-1] = addition print (List)
d749a4a1eefff77ef85b5d39cca779a27c0fe76e
MathewtheCoder/Leetcode-Solutions
/addtwonumbers.py
3,400
4
4
from typing import List, Union class ListNode: # Function to initialise the node object def __init__(self, data): self.val = data # Assign data self.next = None # Initialize next as null # Linked List class contains a Node object class LinkedList: # Function to initialize head def __init__(self): self.head = None # This function prints contents of linked list # starting from head def printList(self): temp = self.head while (temp): print(temp.val) temp = temp.next class Solution: def calcSumAndCarryover(self, l1: ListNode, l2: ListNode, carryOver:int) -> List[int]: if(l1 != None and l2 != None): total = l1.val + l2.val + carryOver elif(l1 != None and l2 == None): total = l1.val + carryOver elif(l1 == None and l2 != None): total = l2.val + carryOver if(total > 9): total = total - 10 carryOver = 1 else: carryOver = 0 return [total, carryOver] def addToSumLL(self, answer: Union[None, ListNode], sumTemp: Union[None, ListNode], sum1: int) -> List[ListNode]: if(isinstance(answer, ListNode)): sumTemp.next = ListNode(sum1) sumTemp = sumTemp.next else: answer = ListNode(sum1) sumTemp = answer return [answer, sumTemp] def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: temp1 = l1 temp2 = l2 answer = None sumTemp = None carryOver = 0 while(temp1 != None and temp2 != None): [sum1, carryOver] = self.calcSumAndCarryover(temp1, temp2, carryOver) [answer, sumTemp] = self.addToSumLL(answer, sumTemp, sum1) temp1 = temp1.next temp2 = temp2.next # If first ll is more than second while(temp1 != None): [sum1, carryOver] = self.calcSumAndCarryover(temp1, temp2, carryOver) [answer, sumTemp] = self.addToSumLL(answer, sumTemp, sum1) temp1 = temp1.next # If first ll is more than second while(temp2 != None): [sum1, carryOver] = self.calcSumAndCarryover(temp1, temp2, carryOver) [answer, sumTemp] = self.addToSumLL(answer, sumTemp, sum1) temp2 = temp2.next # In case of any extra carryOver if(carryOver == 1): [answer, sumTemp] = self.addToSumLL(answer, sumTemp, carryOver) return answer # Code execution starts here if __name__=='__main__': # Start with the empty list # [2,4,3] # [5,6,4] llist1 = LinkedList() llist1.head = ListNode(1) second = ListNode(8) third = ListNode(3) llist1.head.next = second; # Link first node with second second.next = third; # Link second node with the third node llist2 = LinkedList() llist2.head = ListNode(0) second2 = ListNode(6) third2 = ListNode(4) llist2.head.next = second2 # Link first node with second second2.next = third2 # Link second node with the third node print('List 1') llist1.printList() print('List 2') llist2.printList() solution = Solution() sumRes = solution.addTwoNumbers(llist1.head, llist2.head) sumllist = LinkedList() sumllist.head = sumRes print('Sum List') sumllist.printList()
c5a3a36a4ca5d1bce2451548ca3abf590aaa0e3c
Noel62608/PythonVendingMAchine
/car.py
1,197
4.15625
4
class Car: #Constructor Method - Waiter that takes the order for your Car. def __init__(self,whatColor,wheelSizeInput,model,isElectric,engineHp): self.color = whatColor self.wheelSize = wheelSizeInput self.type = model self.electric = isElectric self.horsepower = engineHp def drive(self): print("We're driving down the road!") def turn(self): print("Turning now!") def stop(self): print("Screeeech!!!") AdamsCar = Car("Lime Green",5,"Tesla",True,100000) #Concatenation AdamsCar.drive() AdamsCar.turn() #Object Oriented Programming #Classes - Blueprints for building Objects / Instances #Parameters - How you customize... #Functions / Methods - What your thing can do. #What do you need to build a car? #Metal #Engine #Tires #People that know how to build it #Brakes #steering wheel #leather #Engine Parts #Wheels #Gasoline / Fuel #Door Handles #How can you customize a car? #Paint color.... #GPS #Better Engines. #Interior A/C #Custom Wheels #Steering #Type / Model #What can a car do? #Travel long distances at high speed. #Take you wheere you need to go. #Drive #Turn - Left/Right #forward/backwards #Speed up #slow down #Play Music
7ec5b07f596b5a43ba37b5003b2468794fbe9641
MrQ722/leetcode-notes
/Python3/#234 回文链表.py
2,797
3.796875
4
# 双指针 # 执行用时:92ms,击败36.40% # 内存消耗:23.2MB,击败61.05% # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def isPalindrome(self, head: ListNode) -> bool: if not head: return True val = [] while head: val.append(head.val) head = head.next i,j=0,-1 for n in range(len(val)//2): if val[i] == val[j]: i+=1 j-=1 else: return False return True # 简化写法,指针可以用list反向 class Solution: def isPalindrome(self, head: ListNode) -> bool: vals = [] current_node = head while current_node is not None: vals.append(current_node.val) current_node = current_node.next return vals == vals[::-1] # 递归 class Solution: def isPalindrome(self, head: ListNode) -> bool: self.front_pointer = head def recursively_check(current_node=head): if current_node is not None: if not recursively_check(current_node.next): return False if self.front_pointer.val != current_node.val: return False self.front_pointer = self.front_pointer.next return True return recursively_check() # 快慢指针 class Solution: def isPalindrome(self, head: ListNode) -> bool: if head is None: return True # 找到前半部分链表的尾节点并反转后半部分链表 first_half_end = self.end_of_first_half(head) second_half_start = self.reverse_list(first_half_end.next) # 判断是否回文 result = True first_position = head second_position = second_half_start while result and second_position is not None: if first_position.val != second_position.val: result = False first_position = first_position.next second_position = second_position.next # 还原链表并返回结果 first_half_end.next = self.reverse_list(second_half_start) return result def end_of_first_half(self, head): fast = head slow = head while fast.next is not None and fast.next.next is not None: fast = fast.next.next slow = slow.next return slow def reverse_list(self, head): previous = None current = head while current is not None: next_node = current.next current.next = previous previous = current current = next_node return previous
351e79d71059e89664cddd394ac4db110beab3d3
hsyun89/PYTHON_ALGORITHM
/FAST_CAMPUS/링크드리스트.py
746
4.125
4
#파이썬 객체지향 프로그래밍으로 링크드리스트 구현하기 from random import randrange class Node: def __init__(self,data,next=None): self.data = data self.next = next class NodeMgmt: def __init__(self, data): self.head = Node(data) def add(self, data): if self.head =='': self.head = Node(data) else: node = self.head while node.next: node = node.next node.next = Node(data) def desc(self): node = self.head while node: print(node.data) node = node.next #출력 linkedlist1 = NodeMgmt(0) for data in range (1,10): linkedlist1.add(data) linkedlist1.desc()
b73af1a4f920d70c5d5f66f4059d2431d51585b1
Griffinw15/Intro-Python-I
/inclass/rps.py
2,421
4.53125
5
# Planning # Write a program to play Rock Paper Scissors with a user # Let's flesh out the rules and think about how this is going to work ​ # Rules: Rock -> Scissors # Scissors -> Paper # Paper -> Rock ​ import random ​ # Flow: # Start up program ​ # Keep track of number of wins, losses, and ties for the user # How do we do this? # Have separate variables for each wins = 0 losses = 0 ties = 0 ​ # keep all of this going in an infinite loop until the user decies to quit while True: # User will specify their choice, or can type "quit" in order to exit the program ​ users_choice = input("Choose rock, paper, or scissors: ") # How does the program read the user's choice? # Use Python's `input` function if users_choice == "quit": print("See you next time!") break ​ # Program also needs to specify its choice possible_choices = ["rock", "paper", "scissors"] programs_choice = random.choice(possible_choices) print(f"Program picked {programs_choice}") # How does the program determine its choice? # Just have it randomly pick a choice # Use Python's `random.choice` function ​ # Once both choices are made, compare them via the rules to # see who won # How do we do the comparison? # use if statements if users_choice == "rock": if programs_choice == "rock": print("A tie!") ties += 1 elif programs_choice == "paper": print("Program won!") losses += 1 else: print("You won!") wins += 1 elif users_choice == "paper": if programs_choice == "rock": print("You won!") wins += 1 elif programs_choice == "paper": print("A tie!") ties += 1 else: print("Program won!") losses += 1 elif users_choice == "scissors": if programs_choice == "rock": print("Program won!") losses += 1 elif programs_choice == "paper": print("You won!") wins += 1 else: print("A tie!") ties += 1 else: print("I don't understand that") # go on to the next iteration of the game loop continue ​ print(f"Wins: {wins}, ties: {ties}, losses: {losses}")
04e60c5dd84e54606d81bb253eb94f800adc67cc
bgoonz/UsefulResourceRepo2.0
/MY_REPOS/INTERVIEW-PREP-COMPLETE/notes-n-resources/Data-Structures-N-Algo/_DS-n-Algos/_PyAlgo-Tree/Cryptography/Diffie_Hellmann/diffie_hellman.py
2,160
4.1875
4
""" - Diffie-Hellman algorithm is used only key exchange not encryption and decryption - A public-key distribution scheme cannot be used to exchange an arbitrary message, rather it can establish a common key known only to the two participants value of key depends on the participants and their private and public key information """ p = int( input("Enter prime value chosen by A & B: ") ) # number chosen by both the parties g = int(input("Enter the primitive root: ")) a = int(input("Enter private key of A: ")) # secret key of party1 A = (g ** a) % p print("A sends to B:", A) b = int(input("Enter private key of B: ")) # secret key of party2 B = (g ** b) % p print("B sends to A:", B) print("\nCalculating shared secret....") sec1 = (B ** a) % p print("\nShared secret key of A is: ", sec1) sec2 = (A ** b) % p print("Shared secret key of B is: ", sec2) print("Therefore, both the parties obtain the same value of secret key") """ TEST CASES: Q) In a Diffie-Hellman Key Exchange, Alice and Bob have chosen prime value q = 17 and primitive root = 5. If Alice’s secret key is 4 and Bob’s secret key is 6, what is the secret key they exchanged? Given:- q = 17, a = 5, Private key of Alice XA = 4, Private key of Bob XB = 6 Step-1: Both Alice and Bob calculate the value of their public key and exchange with each other. Public key of Alice Public key of Bob = 5^(private key of Alice) mod 17 = 5^(private key of Bob) mod 17 = 5^(4) mod 17 = 5^(6) mod 17 = 13 = 2 Step-2: Both the parties calculate the value of secret key at their respective side. Secret key obtained by Alice Secret key obtained by Bob = 2^(private key of Alice )mod 7 = 13^(private key of Bob) mod 7 = 2^(4) mod 17 = 13^(6) mod 17 = 16 = 16 Finally, both the parties obtain the same value of secret key. """
acece788b3940d58e2451b45ffac7ab807f359b5
rupesh1149/python-goto-repo
/closure.py
577
3.875
4
# A Closure is a function object that remembers values in enclosing scopes even if they are not present in memory def transmit_to_space(message): "This is the enclosing function" def data_transmitter(): "The nested function" print(message) data_transmitter() print(transmit_to_space("Test message")) # Even though the execution of the "transmit_to_space()" was completed, the message was rather preserved. This technique by which the # data is attached to some code even after end of those other original functions is called as closures in python
70f1b4151e85b266a237192667835b5a9f49689e
SamuelJadzak/SamuelJadzak.github.io
/calculator.py
1,664
3.984375
4
def add(num1, num2): """Returns num1 plus num2.""" return num1 + num2 def sub(num1, num2): """returns num1 - num2.""" return num1 - num2 def mul(num1, num2): """returns num1 * num2.""" return num1 * num2 def div(num1, num2): """returns num1 / num2.""" try: return num1 / num2 except ZeroDivisionError: print("Handled div by zero. Return zero") return 0 def runOperation(operation, num1, num2): if (operation == 1): print(add(num1, num2)) elif (operation == 2): print(sub(num1, num2)) elif (operation == 3): print(mul(num1, num2)) elif (operation == 4): print(div(num1, num2)) else: print("I don't understand") def anotherCalculation(morecalc): if (morecalc == "y"): main() else: print("Bye") return def main(): validInput = False while not validInput: try: num1 = int(raw_input("What is number 1?")) num2 = int(raw_input("What is number 2?")) operation = int(raw_input("What do you want to do? 1)add, 2)subtract, 3)multiply, 4)divide")) validInput = True runOperation(operation, num1, num2) except ValueError: print("Invalid input. Try again") except: print("Unknown error") reRun = False while not reRun: try: morecalc = (raw_input("Another calculation?('y' for yes)")) anotherCalculation(morecalc) reRun = True except: return main()
1d28b13d64c414f95a03a4de9f0b3ef42dcb6297
oshirohugo/unicamp-2014-1
/mc302/lab07/ativ07.py
2,320
3.515625
4
#This module is used read fuel usage and distance #data and calc consume statistics from it #Hugo K. Oshiro data = {} #dictionary to store data input - 'date' : (volume, kms) consumes = {} #dictionary to store consumes calc by date - consume : (consume, 'date') consumesList = [] #list to store consume kmsList = [] #list to store distance consumeWasCalc = False #flag to calc statistics volumeList = [] #list to stores volumes #function used to store data input in data dictionary def anota(date, volume, kms): global data data[date] = (volume, kms) #function used to calc statistics from data def calcConsume(): global consumes #needed to alter global value global consumesList #needed to alter global value #calc consume for all dates for date in data: volume = data[date][0] #get volume from a date kms = data[date][1] #get kms from date consume = kms / volume #calc consume consumes[consume] = (consume, date) #put consume in consume dict consumesList.append(consume) #put consume in consume list kmsList.append(kms) #stores values in kmsList be used in kmMed volumeList.append(volume) def consMin(): global consumeWasCalc #needed to alter global value #if statistics wasn't calc yet if not consumeWasCalc: calcConsume() #calc statistics consumeWasCalc = True #inform it return consumes[min(consumesList)] #return minor element def consMax(): global consumeWasCalc #needed to alter global value #if statistics wasn't calc yet if not consumeWasCalc: calcConsume() #calc statistics consumeWasCalc = True #inform it return consumes[max(consumesList)] #return greater element def consMed(): global consumeWasCalc #needed to alter global value #if statistics wasn't calc yet if not consumeWasCalc: calcConsume() #calc statistics consumeWasCalc = True #inform it return sum(consumesList) / len(consumesList) #return consumes list average def kmMed(): global consumeWasCalc #needed to alter global value #if statistics wasn't calc yet if not consumeWasCalc: calcConsume() #calc statistics consumeWasCalc = True #inform it return sum(kmsList) / len(kmsList) #return kms list average
d6b207df2a17bedff2634f4b302bf7845a1fa5de
AminHoss/Wave_2
/Roulette_Payout.py
698
3.75
4
import random numbers = [0, 00, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30,31, 32, 33, 34, 35, 36] red = [1,3,5,7,9,12,14,16,18,19,21,23,25,27,30,32, 34, 36] black= [2,4,6,8,10,11,13,15,17,20,22,24,26,28,29,31, 33, 35] number = random.choice(numbers) print(number) if number == 0: print("Pay 0") elif number == 00: print("Pay 00") else: if number in red: print("Pay Red") elif number in black: print("pay Black") if number % 2 == 0: print("Pay Even") else: print("Pay Odd") if number in range(1, 19): print("Pay 1 to 18") else: print("Pay 19 to 36")
8998c4a05f6317c43a237fd740f045b5b04cbc5c
xiaozhi521/PythonLearn
/venv/Scripts/com/def/DefTest.py
431
3.515625
4
#!/usr/bin/python # -*- coding: UTF-8 -*- #import __init__; #__init__.printme("111") Money = 2000 def AddMoney(): # 想改正代码就取消以下注释: global Money Money = Money + 1 print Money AddMoney() print Money import math content = dir(math) print content; print locals() # 返回的是所有能在该函数里访问的命名 print globals() # 返回的是所有在该函数里能访问的全局名字
ad55a21c492832cd968e7b3fe8c9034c8dd3dfd2
GitKurmax/coursera-python
/week01/task21.py
658
3.671875
4
# Улитка ползет по вертикальному шесту высотой H метров, поднимаясь за день на A метров, а за ночь спускаясь на B метров. На какой день улитка доползет до вершины шеста? # Формат ввода # Программа получает на вход целые H, A, B. Гарантируется, что A > B ≥ 0. # Формат вывода # Программа должна вывести одно натуральное число. H, A, B = int(input()), int(input()), int(input()) print((H - A - 1)//(A - B) + 2)
a11376608160513fab58d7b1abfeab93a7da9efb
youngerous/algorithm
/etc/Sortings/InsertionSort.py
1,062
4.15625
4
class InsertionSort: """ Complexity: O(N^2) - O(N) for moving key(step) - O(N) for pairwise swap Assumption: Operations of Comparison and Swap are equal in cost. - But usually comparison is more expensive than swap. - When using Binary Search, we can make comparison cost O(NlogN). - However, inserting(swap) cost is still O(N^2). This algorithm does in-place sort. It needs O(1) auxiliary space (swapping variable). """ def sort(self, arr): length = len(arr) for key in range(1, length): # Assumption: index zero is already sorted. current_value = arr[key] index = key while index > 0 and current_value < arr[index - 1]: arr[index] = arr[index - 1] # swap index -= 1 arr[index] = current_value return arr if __name__ == "__main__": testArr = [8, 31, 48, 73, 3, 65, 20, 29, 11, 15] insertion = InsertionSort() print("RESULT = " + str(insertion.sort(testArr))) # RESULT = [3, 8, 11, 15, 20, 29, 31, 48, 65, 73]
200a6bbcb231745e630985f9267b181c1ad6eaa6
perglervitek/Python-B6B36ZAL
/permutations.py
907
3.6875
4
def permutations(array): perms = [] if len(array) == 0 or len(array) == 1: return [array] else: for key, firstItem in enumerate(array): remainingItems = array[key+1:] + array[:key] for permut in permutations(remainingItems): perms.append([firstItem] + permut) return perms # print(permutations(['a', 'b', 'c', 'd'])) # print(permutations([1])) # print(permutations([])) # [['b', 'a', 'c', 'd'], ['b', 'c', 'a', 'd'], ['b', 'c', 'd', 'a'], ['c', 'a', 'b', 'd'], ['c', 'b', 'a', 'd'], ['c', 'b', 'd', 'a'], ['a', 'c', 'd', 'b'], ['c', 'a', 'd', 'b'], ['c', 'd', 'a', 'b'], ['c', 'd', 'b', 'a'], ['b', 'a','d', 'c'], ['b', 'd', 'a', 'c'], ['b', 'd', 'c', 'a'], ['a', 'd', 'b', 'c'], ['d', 'a', 'b', 'c'], ['d', 'b', 'a', 'c'], ['d', 'b', 'c', 'a'], ['a', 'd', 'c', 'b'], ['d', 'a', 'c', 'b'], ['d', 'c', 'a', 'b'], ['d', 'c', 'b', 'a']]
b4ae80e5a5d1c09ae91a269d4b4cc82b31962e95
Artekaren/Trainee-Python
/V30_lista_a_dicc_viceversa.py
662
4.15625
4
#Ejercicio30: #Caso1: Convertir un diccionario en una lista con la función items() list({"k1": 5, "k2": 7}.items()) #Caso2: Convertir una lista en diccionario con la función dict() dict([('k1', 5), ('k2', 7)]) #Caso3: Cruzando información de dos listas. 2 formas. nombres = ['Alumno1', 'Alumno2', 'Alumno3'] notas = [10, 3, 8] #1 Forma1: Iterar las listas simultáneamente, con un índice. notas_por_alumno = {} for i in range(len(nombres)): alumno = nombres[i] nota = notas[i] notas_por_alumno[alumno] = nota print(notas_por_alumno) #2 Forma2: Utilizando el método zip notas_por_alumno = dict(zip(nombres, notas)) print(notas_por_alumno)