blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
1afb2e4b5772a71ace603b6908b47876eb109cb5
Matthew-P-Lee/Python
/verticalc.py
1,139
4.28125
4
import math #speed, distance, time calculations class Verticalc(object): grade = 0.0 distance = 0.0 speed = 0.0 time = 0.0 def __init__(self, grade,distance,speed,time): self.grade = grade self.distance = distance self.speed = speed self.time = time def getVerticalFeet(self): vert = ((float(grade)/100) * float(distance)) vertFeet = float(vert) * 5280 return vertFeet def getDistance(self): return float(speed/60.0) * float(time) # def __str__(self): # return #calculate vertical gain from an angle and average speed - treadmill calculator grade = input("Enter the average angle of the climb (in degrees): ") distance = input("Enter the distance of the climb (in miles): ") speed = input ("Enter your average pace (in mph): ") time = input ("Enter your total time at " + str(grade) + "% grade (in minutes): ") vc = Verticalc(grade,distance,speed,time) #vertical feet gained print "%s vertical feet at %s%% grade" % (str(vc.getVerticalFeet()), vc.grade) #distance given time / speed print "%s miles travelled at %s mph for %s minutes" % (str(vc.getDistance()),str(vc.speed),str(vc.time))
a19a25dc98ba53d6f72fedd6141191e48dd56706
exploring-curiosity/DesignAndAnalysisOfAlgorithms
/Assignment2/q1_1power_Rec.py
206
4.21875
4
def power(a,n): if n==1: return a else: return a*power(a,n-1) a=int(input("Enter the value of x : ")) n=int(input("Enter the value of power : ")) print("The result is ",power(a,n))
d3017f73eed8174a200c80027fe20babbf55aa62
Mjcanson/TCP-UDP-Centralized-Client-Server-Network
/client/client.py
4,121
3.75
4
######################################################################################################################## # Class: Computer Networks # Date: 02/03/2020 # Lab3: TCP Client Socket # Goal: Learning Networking in Python with TCP sockets # Student Name: Michael Canson # Student ID:920601003 # Student Github Username: Mjcanson # Instructions: Read each problem carefully, and implement them correctly. ######################################################################################################################## # don't modify this imports. import socket import pickle from client_helper import ClientHelper ######################################## Client Socket ###############################################################3 """ Client class that provides functionality to create a client socket is provided. Implement all the methods but bind(..) """ class Client(object): def __init__(self): """ Class constructor """ #client socket self.client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.id = 0 def connect(self, server_ip_address, server_port): """ TODO: Create a connection from client to server Note that this method must handle any exceptions :server_ip_address: the know ip address of the server :server_port: the port of the server """ print('connecting to ' + str(server_ip_address) + ' port ' + str(server_port)) #uses socket connect() method client_socket = self.client # self.client.connect((server_ip_address,server_port)) try: self.client.connect((server_ip_address,server_port)) except OSError as msg: print(msg) self.client.close() client_socket = None if client_socket == None: print('could not open socket') def bind(self, client_ip='', client_port=12000): """ DO NOT IMPLEMENT, ALREADY IMPLEMENTED This method is optional and only needed when the order or range of the ports bind is important if not called, the system will automatically bind this client to a random port. :client_ip: the client ip to bind, if left to '' then the client will bind to the local ip address of the machine :client_port: the client port to bind. """ self.client.bind((client_ip, client_port)) def send(self, data): """ TODO: Serializes and then sends data to server :param data: the raw data to serialize (note that data can be in any format.... string, int, object....) :return: VOID """ # #test # print('send() data sending: ' + str(data)) self.client.send(pickle.dumps(data)) def receive(self, max_alloc_buffer=4090): """ TODO: Deserializes the data received by the server :param max_alloc_buffer: Max allowed allocated memory for this data :return: the deserialized data. """ # self.id = pickle.loads(self.client.recv(max_alloc_buffer)) data = pickle.loads(self.client.recv(max_alloc_buffer)) if data['headers']['ack'] == 1: print( str(data['headers']['clientid']) + " has succesfully connected to " + str(server_ip) + "/" + str(server_port)) return data def client_helper(self): """ TODO: create an object of the client helper and start it. """ ch = ClientHelper(self) ch.start() def close(self): """ TODO: close this client :return: VOID """ # print('closing socket') self.client.close() # main code to run client if __name__ == '__main__': # server_ip = '10.0.0.204' # server_port = 12000 server_ip = input('Enter the server IP Address: ') server_port = int(input('Enter the server port: ')) client = Client() client.connect(server_ip, server_port) # creates a connection with the server client.client_helper() client.close()
e6db1f936b5e8d5619e72298476718505fcba09b
gtalarico/ironpython-stubs
/release/stubs.min/Rhino/Geometry/__init___parts/Arc.py
9,956
3.625
4
class Arc(object,IEquatable[Arc],IEpsilonComparable[Arc]): """ Represents the value of a plane,two angles and a radius in a subcurve of a three-dimensional circle. The curve is parameterized by an angle expressed in radians. For an IsValid arc the total subtended angle AngleRadians()=Domain()(1) - Domain()(0) must satisfy 0 < AngleRadians() < 2*PiThe parameterization of the Arc is inherited from the Circle it is derived from. In particulart -> center + cos(t)*radius*xaxis + sin(t)*radius*yaxiswhere xaxis and yaxis,(part of Circle.Plane) form an othonormal frame of the plane containing the circle. Arc(circle: Circle,angleRadians: float) Arc(circle: Circle,angleIntervalRadians: Interval) Arc(plane: Plane,radius: float,angleRadians: float) Arc(center: Point3d,radius: float,angleRadians: float) Arc(plane: Plane,center: Point3d,radius: float,angleRadians: float) Arc(startPoint: Point3d,pointOnInterior: Point3d,endPoint: Point3d) Arc(pointA: Point3d,tangentA: Vector3d,pointB: Point3d) """ def BoundingBox(self): """ BoundingBox(self: Arc) -> BoundingBox Computes the 3D axis aligned bounding box for this arc. Returns: Bounding box of arc. """ pass def ClosestParameter(self,testPoint): """ ClosestParameter(self: Arc,testPoint: Point3d) -> float Gets parameter on the arc closest to a test point. testPoint: Point to get close to. Returns: Parameter (in radians) of the point on the arc that is closest to the test point. If testPoint is the center of the arc,then the starting point of the arc is (arc.Domain()[0]) returned. If no parameter could be found, RhinoMath.UnsetValue is returned. """ pass def ClosestPoint(self,testPoint): """ ClosestPoint(self: Arc,testPoint: Point3d) -> Point3d Computes the point on an arc that is closest to a test point. testPoint: Point to get close to. Returns: The point on the arc that is closest to testPoint. If testPoint is the center of the arc,then the starting point of the arc is returned. UnsetPoint on failure. """ pass def EpsilonEquals(self,other,epsilon): """ EpsilonEquals(self: Arc,other: Arc,epsilon: float) -> bool Check that all values in other are within epsilon of the values in this """ pass def Equals(self,*__args): """ Equals(self: Arc,other: Arc) -> bool Determines whether another arc has the same value as this arc. other: An arc. Returns: true if obj is equal to this arc; otherwise false. Equals(self: Arc,obj: object) -> bool Determines whether another object is an arc and has the same value as this arc. obj: An object. Returns: true if obj is an arc and is exactly equal to this arc; otherwise false. """ pass def GetHashCode(self): """ GetHashCode(self: Arc) -> int Computes a hash code for the present arc. Returns: A non-unique integer that represents this arc. """ pass def PointAt(self,t): """ PointAt(self: Arc,t: float) -> Point3d Gets the point at the given arc parameter. t: Arc parameter to evaluate. Returns: The point at the given parameter. """ pass def Reverse(self): """ Reverse(self: Arc) Reverses the orientation of the arc. Changes the domain from [a,b] to [-b,-a]. """ pass def TangentAt(self,t): """ TangentAt(self: Arc,t: float) -> Vector3d Gets the tangent at the given parameter. t: Parameter of tangent to evaluate. Returns: The tangent at the arc at the given parameter. """ pass def ToNurbsCurve(self): """ ToNurbsCurve(self: Arc) -> NurbsCurve Initializes a nurbs curve representation of this arc. This amounts to the same as calling NurbsCurve.CreateFromArc(). Returns: A nurbs curve representation of this arc or null if no such representation could be made. """ pass def Transform(self,xform): """ Transform(self: Arc,xform: Transform) -> bool Transforms the arc using a Transformation matrix. xform: Transformations to apply. Note that arcs cannot handle non-euclidian transformations. Returns: true on success,false on failure. """ pass def Trim(self,domain): """ Trim(self: Arc,domain: Interval) -> bool Sets arc's angle domain (in radians) as a subdomain of the circle. domain: 0 < domain[1] - domain[0] <= 2.0 * RhinoMath.Pi. Returns: true on success,false on failure. """ pass def __eq__(self,*args): """ x.__eq__(y) <==> x==y """ pass def __init__(self,*args): """ x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """ pass @staticmethod def __new__(self,*__args): """ __new__[Arc]() -> Arc __new__(cls: type,circle: Circle,angleRadians: float) __new__(cls: type,circle: Circle,angleIntervalRadians: Interval) __new__(cls: type,plane: Plane,radius: float,angleRadians: float) __new__(cls: type,center: Point3d,radius: float,angleRadians: float) __new__(cls: type,plane: Plane,center: Point3d,radius: float,angleRadians: float) __new__(cls: type,startPoint: Point3d,pointOnInterior: Point3d,endPoint: Point3d) __new__(cls: type,pointA: Point3d,tangentA: Vector3d,pointB: Point3d) """ pass def __ne__(self,*args): pass def __reduce_ex__(self,*args): pass def __repr__(self,*args): """ __repr__(self: object) -> str """ pass def __str__(self,*args): pass Angle=property(lambda self: object(),lambda self,v: None,lambda self: None) """Gets or sets the sweep -or subtended- angle (in Radians) for this arc segment. Get: Angle(self: Arc) -> float Set: Angle(self: Arc)=value """ AngleDegrees=property(lambda self: object(),lambda self,v: None,lambda self: None) """Gets or sets the sweep -or subtended- angle (in Radians) for this arc segment. Get: AngleDegrees(self: Arc) -> float Set: AngleDegrees(self: Arc)=value """ AngleDomain=property(lambda self: object(),lambda self,v: None,lambda self: None) """Gets or sets the angle domain (in Radians) of this arc. Get: AngleDomain(self: Arc) -> Interval Set: AngleDomain(self: Arc)=value """ Center=property(lambda self: object(),lambda self,v: None,lambda self: None) """Gets or sets the center point for this arc. Get: Center(self: Arc) -> Point3d Set: Center(self: Arc)=value """ Circumference=property(lambda self: object(),lambda self,v: None,lambda self: None) """Gets the circumference of the circle that is coincident with this arc. Get: Circumference(self: Arc) -> float """ Diameter=property(lambda self: object(),lambda self,v: None,lambda self: None) """Gets or sets the Diameter of this arc. Get: Diameter(self: Arc) -> float Set: Diameter(self: Arc)=value """ EndAngle=property(lambda self: object(),lambda self,v: None,lambda self: None) """Gets or sets the end angle (in Radians) for this arc segment. Get: EndAngle(self: Arc) -> float Set: EndAngle(self: Arc)=value """ EndAngleDegrees=property(lambda self: object(),lambda self,v: None,lambda self: None) """Gets or sets the end angle (in Radians) for this arc segment. Get: EndAngleDegrees(self: Arc) -> float Set: EndAngleDegrees(self: Arc)=value """ EndPoint=property(lambda self: object(),lambda self,v: None,lambda self: None) """Gets the end point of the arc. Get: EndPoint(self: Arc) -> Point3d """ IsCircle=property(lambda self: object(),lambda self,v: None,lambda self: None) """Gets a value indicating whether or not this arc is a complete circle. Get: IsCircle(self: Arc) -> bool """ IsValid=property(lambda self: object(),lambda self,v: None,lambda self: None) """Gets a value indicating whether or not this arc is valid. Detail: Radius>0 and 0<AngleRadians()<=2*Math.Pi. Get: IsValid(self: Arc) -> bool """ Length=property(lambda self: object(),lambda self,v: None,lambda self: None) """Gets the length of the arc. (Length=Radius * (subtended angle in radians)). Get: Length(self: Arc) -> float """ MidPoint=property(lambda self: object(),lambda self,v: None,lambda self: None) """Gets the mid-point of the arc. Get: MidPoint(self: Arc) -> Point3d """ Plane=property(lambda self: object(),lambda self,v: None,lambda self: None) """Gets or sets the plane in which this arc lies. Get: Plane(self: Arc) -> Plane Set: Plane(self: Arc)=value """ Radius=property(lambda self: object(),lambda self,v: None,lambda self: None) """Gets or sets the radius of this arc. Get: Radius(self: Arc) -> float Set: Radius(self: Arc)=value """ StartAngle=property(lambda self: object(),lambda self,v: None,lambda self: None) """Gets or sets the start angle (in Radians) for this arc segment. Get: StartAngle(self: Arc) -> float Set: StartAngle(self: Arc)=value """ StartAngleDegrees=property(lambda self: object(),lambda self,v: None,lambda self: None) """Gets or sets the start angle (in Radians) for this arc segment. Get: StartAngleDegrees(self: Arc) -> float Set: StartAngleDegrees(self: Arc)=value """ StartPoint=property(lambda self: object(),lambda self,v: None,lambda self: None) """Gets the start point of the arc. Get: StartPoint(self: Arc) -> Point3d """
e96ee14920798627d606a7389129a65ba31ce7d1
advaith-unnikrishnan/Getting-started-with-Python
/Basic Programs/palindrome.py
346
4.125
4
""" Program: To find whether a number is palindrome or not. Eg: 121 is a plaindrome number Author: Advaith n-stores the number r-stores the reverse of the number """ n=int(input("Enter the number ")) i,r=n,0 while(i>0): r=r*10+i%10 i=i//10 if n==r: print(n," is a palindrome number") else: print(n," is not a palindrome number")
0a1f9f7a18d4c22d47830b5a85ba70f7cfcbe722
WinterMute1000/Algorithm_Practice
/target_index.py
710
3.6875
4
class TargetIndex: def inputData(self): self.num_list=list(map(int,input("Input:").split())) self.target=int(input("Target:")) def searchIndex(self): result=False for i in range(len(self.num_list)): temp=self.target-self.num_list[i] if temp in self.num_list: result=True result_index=[i,self.num_list.index(temp)] break if result: print("Output"+str(result_index)) else: print("No search.") def main(): targetIndex=TargetIndex() targetIndex.inputData() targetIndex.searchIndex() if __name__=="__main__": main()
a3c4ab4e4028eaf087d3aa94cec53b88e1503000
mass234/broPython12hoursTutorials
/Ball.py
688
3.625
4
class Ball: def __init__(self,canvas,x,y,diameter,xVelocity,yVelocity,color): self.canvas = canvas self.image = canvas.create_oval(x,y,diameter,diameter,fill=color) self.xVelocity = xVelocity self.yVelocity = yVelocity def move(self): coordinates = self.canvas.coords(self.image) print(coordinates) if(coordinates[2]>=(self.canvas.winfo_width()) or coordinates[0]<0): self.xVelocity = -self.xVelocity if (coordinates[3] >= (self.canvas.winfo_height()) or coordinates[1] < 0): self.yVelocity = -self.yVelocity self.canvas.move(self.image,self.xVelocity,self.yVelocity)
536bf3674c4f4b44a3ad264b93963d7d3ae19a37
GUTINGLIAO/sonne
/file/rename_file.py
1,025
3.765625
4
from pathlib import Path def rename(root: str, base_name: str, skip_dir: bool = True): """重命名目录下的所有文件 根据base_name重命名文件,按照次序修改名字,保留文件后缀,所有文件均放置在同一级目录下 :param skip_dir: 重命名是否跳过目录 :param root: 根目录 :param base_name: 基础名称 """ root_file = Path(root) for i, file in enumerate(root_file.rglob('*'), 0): if skip_dir and file.is_dir(): continue parent = file.parent if '.' in str(file.name): suffix = str(file.name).split('.')[-1] file.rename(str(parent.absolute()) + '/' + base_name + str(i) + '.' + suffix) print('rename % successfully' % str(file.name)) else: file.rename(str(parent.absolute()) + '/' + base_name + str(i)) print('rename % successfully' % str(file.name)) if __name__ == '__main__': rename('/Users/apple/Downloads/图片/锈蚀', '锈蚀')
d9bc03fc5a2157268cecbae2f25dd694431c604a
Gabrielatb/Interview-Prep
/elements_of_programming/Array/delete_dup_sorted_array.py
424
3.625
4
#deleting repeated elements from a sorted array #input [2,3,5,5,7,11,11,13] #output [2,3,5,7,11,13] #Time: O(n) #Space: O(1) def delete_dup(lst): if lst == []: return 0 write_indx = 1 for i in range(1, len(lst)): if lst[write_indx-1] != lst[i]: lst[write_indx] = lst[i] write_indx += 1 print lst return write_indx print delete_dup([2,3,5,5,7,11,11,13])
c2c41dbf8728fe5c3e4fd44f46620938ef8b9398
amandameganchan/advent-of-code-2020
/day23/day23code.py
1,791
3.609375
4
#!/bin/env python3 import sys import re from collections import defaultdict def solution(filename): data = [] with open(filename) as f: for x in f: data.extend(list(x.strip())) data = list(map(int, data)) return collectLabels(playGame(data)) def collectLabels(final_cups): # start at 1 and collect cups clockwise # do not include 1 and remember to wrap final_string = final_cups[final_cups.index(1)+1:] final_string.extend(final_cups[:final_cups.index(1)]) return ''.join(list(map(str,final_string))) def playGame(cups): current_cup = cups[0] for _ in range(100): current_cup, cups = makeMove(current_cup,cups) return cups def makeMove(current_cup, cups): # pop next 3 cups starting from after index of current cup pop_cups = [cups.pop((cups.index(current_cup)+1)%len(cups)), cups.pop((cups.index(current_cup)+1)%len(cups)), cups.pop((cups.index(current_cup)+1)%len(cups))] # select destination cup: current_cup's label - 1 dest_cup = current_cup - 1 if current_cup > 1 else 9 # if this cup is one of the removed, subtract 1 again and repeat # note if number goes below 1, wrap aroud to 9 while dest_cup not in cups: dest_cup = dest_cup - 1 if dest_cup > 1 else 9 # place the removed cups next to the destination cup # in the same order and immediately next to dest cup cups[cups.index(dest_cup)+1:cups.index(dest_cup)+1] = pop_cups # select new current_cup: cup immediately clockwise next to current cup new_index = cups.index(current_cup)+1 if cups.index(current_cup) < 8 else 0 new_current = cups[new_index] return new_current, cups if __name__ == '__main__': if len(sys.argv) < 2: print("Usage: python3 day23code.py <data-file>") sys.exit(1) labels = solution(sys.argv[1]) print("Labels on the cups after cup 1: {}".format(labels))
68d22f4f4bf0b43997a8afb78d3039249c0a9b97
lportinari/DarkSoulsInShell
/DSS.py
19,183
3.53125
4
from time import sleep import random import math class Class: def __init__(self, name='', phyAttack=0,max_phy_attack=0, magAttack=0, max_mag_attack=0, phyDef=0, magDef=0, criticalChance=0, hp=0, mp=0, souls=0, level=0, weapom='', shield='', estus_flask=2, class_name=''): self.phyAttack = phyAttack self.magAttack = magAttack self.phyDef = phyDef self.magDef = magDef self.hp = hp self.mp = mp self.souls = souls self.level = level self.criticalChance = criticalChance self.estus_flask = estus_flask self.class_name = class_name self.max_phy_attack = max_phy_attack self.max_mag_attack = max_mag_attack def createCharacter(self): print('-' * 60) print('CRIAÇÃO DE PERSONAGEM'.center(60)) print() self.name = str(input('Digite o nome do personagem: ')) def choseClass(sef): print('') print('-=' * 30) print('SELEÇÃO DA CLASSE'.center(60)) print(""" 1 - WARRIOR 2 - KNIGHT 3 - THIEF 4 - BANDIT 5 - HUNTER 6 - SORCERER 7 - PYROMANCER 8 - DEPRIVED """) while True: select = int(input('Digite o número da classe escolhida: ')) if select > 8 or select < 1: print('ERRO! Escolha uma opção válida:') else: break #Classe Warrior if select == 1: hero.class_name = 'Warrior' hero.phyAttack = 13 hero.max_phy_attack = 23 hero.magAttack = 7 hero.max_mag_attack = 17 hero.phyDef = 12 hero.magDef = 8 hero.criticalChance = 5 hero.hp = 110 hero.mp = 50 hero.souls = 0 #Classe Knight elif select == 2: hero.class_name = 'Knight' hero.phyAttack = 11 hero.max_phy_attack = 21 hero.magAttack = 8 hero.max_mag_attack = 18 hero.phyDef = 10 hero.magDef = 10 hero.criticalChance = 5 hero.hp = 140 hero.mp = 50 hero.souls = 0 #Classe Thief elif select == 3: hero.class_name = 'Thief' hero.phyAttack = 9 hero.max_phy_attack = 19 hero.magAttack = 8 hero.max_mag_attack = 18 hero.phyDef = 9 hero.magDef = 11 hero.criticalChance = 10 hero.hp = 90 hero.mp = 11 hero.souls = 0 #Classe Bandit elif select == 4: hero.class_name = 'Bandit' hero.phyAttack = 14 hero.max_phy_attack = 24 hero.magAttack = 10 hero.max_mag_attack = 20 hero.phyDef = 10 hero.magDef = 8 hero.criticalChance = 8 hero.hp = 120 hero.mp = 50 hero.souls = 0 #Classe Hunter elif select == 5: hero.class_name = 'Hunter' hero.phyAttack = 12 hero.max_phy_attack = 22 hero.magAttack = 9 hero.max_mag_attack = 19 hero.phyDef = 11 hero.magDef = 9 hero.criticalChance = 9 hero.hp = 11 hero.mp = 50 hero.souls = 0 #Classe Sorcerer elif select == 6: hero.class_name = 'Sorcerer' hero.phyAttack = 9 hero.max_phy_attack = 19 hero.magAttack = 15 hero.max_mag_attack = 25 hero.phyDef = 8 hero.magDef = 15 hero.criticalChance = 5 hero.hp = 80 hero.mp = 100 hero.souls = 0 #Classe Pyromancer elif select == 7: hero.class_name = 'Pyromancer' hero.phyAttack = 10 hero.max_phy_attack = 20 hero.magAttack = 12 hero.max_mag_attack = 22 hero.phyDef = 11 hero.magDef = 10 hero.criticalChance = 5 hero.hp = 100 hero.mp = 80 hero.souls = 0 #Classe Deprived elif select == 8: hero.class_name = 'Deprived' hero.phyAttack = 10 hero.max_phy_attack = 20 hero.magAttack = 10 hero.max_mag_attack = 20 hero.phyDef = 10 hero.magDef = 10 hero.criticalChance = 5 hero.hp = 110 hero.mp = 50 hero.souls = 0 print('-' * 50) print(''' Atributos da Classe: Classe: {} Ataque Físico: {}/{} Ataque Mágico: {}/{} Defesa Física: {} Defesa Mágica: {} Chance Crítica: {}% HP: {} MP: {} '''.format(hero.class_name, hero.phyAttack, hero.max_phy_attack, hero.magAttack, hero.max_mag_attack, hero.phyDef, hero.magDef, hero.criticalChance, hero.hp, hero.mp)) print(''' [ 1 ] CONFIRMAR A ESCOLHA [ 2 ] VOLTAR ''') choose = int(input('Escolha uma opção: ')) if choose == 1: pass elif choose == 2: hero.choseClass() def equipWeapon(self, other): self.phyAttack += other.phyAttack self.max_phy_attack += other.max_phy_attack self.magAttack += other.magAttack self.max_mag_attack += other.max_mag_attack self.criticalChance += other.critical_chance self.weapom = other.name print('Você equipou {}!'.format(other.name)) class Equips: def __init__(self, ID, name='', phyAttack=0, max_phy_attack=0, magAttack=0, max_mag_attack=0, critical_chance=0, price=0): self.ID = ID self.name = name self.phyAttack = phyAttack self.max_phy_attack = max_phy_attack self.magAttack = magAttack self.max_mag_attack = max_mag_attack self.critical_chance = critical_chance self.price = price class Monster: def __init__(self, name='', phyAttack=50, max_phy_attack=60, magAttack=65, max_mag_attack=75, phyDef=40, magDef=35, hp=500, mp=100, souls=50): self.name = name self.phyAttack = phyAttack self.max_phy_attack = max_phy_attack self.magAttack = magAttack self.max_mag_attack = max_mag_attack self.phyDef = phyDef self.magDef = magDef self.hp = hp self.mp = mp self.souls = souls def attack(self, other): dano = random.randint(self.phyAttack, self.max_phy_attack) - other.phyDef other.hp -= dano sleep(1) if other.hp <= 0: print('{}:'.format(self.name)) print('Você recebeu {} de dano!'.format(dano)) else: print('{}:'.format(self.name)) print('Você recebeu {} de dano!'.format(dano)) #dano = 0 def magic(self, other): pass class Hero(Class): def __init__(self, name='', phyAttack=1, magAttack=1, phyDef=1, magDef=1, criticalChance=1, hp=1, mp=1, souls=0, level=0, weapom='', shield='', estus_flask=2, class_name=''): super(Hero, self).__init__(name, phyAttack, magAttack, phyDef, magDef, criticalChance, hp, mp, souls, level, weapom, shield, estus_flask, class_name) def createCharacter(self): super(Hero, self).createCharacter() def choseClass(self): super(Hero, self).choseClass() def attack(self, other): dano = random.randint(self.phyAttack, self.max_phy_attack) - other.phyDef hero.critChance() if crit: dano *= 2 other.hp -= dano sleep(1) print('STATUS DA BATALHA:') print('------------------\n') if other.hp <= 0: print('{}:'.format(self.name)) other.hp = 0 hero.souls += other.souls if crit: print('ATAQUE CRÍTICO!') print('Você causou {} de dano no inimigo\n'.format(dano)) print('Parabéns, você derrotou {}!'.format(other.name)) print('Você adquiriu {} souls'.format(other.souls)) else: print('{}:'.format(self.name)) if crit: print('ATAQUE CRÍTICO!') print('Você causou {} de dano no inimigo'.format(dano)) print('HP {}: {}\n'.format(other.name, other.hp)) def estusFlask(self): if self.estus_flask > 0: self.estus_flask -= 1 self.hp += 100 sleep(0.5) if self.hp > max_hp: self.hp = max_hp print('Você recuperou 100 pontos de vida!\n'.format(self.estus_flask)) else: print('Você não possui Estus Flask!') def magic(self, other): pass def critChance(self): global crit crit = False critical = random.randint(0, 100) if critical <= self.criticalChance: crit = True return crit class Store: def __init__(self, one_handed_swords, two_handed_greatsword): self.one_handed_swords = one_handed_swords self.two_handed_greatsword = two_handed_greatsword def weaponStore(self): print(''' ( ) ( _ _._ |_|-'_~_`-._ _.-'-_~_-~_-~-_`-._ _.-'_~-_~-_-~-_~_~-_~-_`-._ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ | [] [] [] [] [] | | __ ___ | ._| [] [] | .| [___] |_._._._._._._._._._._._._._._._._. |=|________()|__|()_______|=|=|=|=|=|=|=|=|=|=|=|=|=|=|=|=|=| ^^^^^^^^^^^^^^^ === ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ _______ === <_Loja_> === ^|^ === | === -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- * [ 1 ] ESPADAS DE UMA MÃO * * [ 2 ] ESPADAS DE DUAS MÃOS * * [ 3 ] ESCUDOS * -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- O que deseja comprar? ''') option = int(input('Escolha uma opção: ')) if option == 1: print('-=' * 49) print('ESPADAS DE UMA MÃO'.center(98)) print('Para guerreiros que além de focar em ataque físico, pretendem focar na defesa. PRÓS: Pode ser equipado em conjunto com escudo / CONTRAS: Ataque mediano') print('-=' * 49) for i in self.one_handed_swords: print(''' -------------------------------------------------------------------------------------------------- !Nome: {} | Ataque físico: {}/{} | Ataque mágico: {}/{} | Chance Crítica: {}% !Preço: {} Souls | Código de compra: {} --------------------------------------------------------------------------------------------------'''.format(i.name, i.phyAttack, i.max_phy_attack, i.magAttack, i.max_mag_attack, i.critical_chance, i.price, i.ID)) print() buy = int(input('Digite o código de compra ou 0 para voltar: ')) if buy == 0: pass else: check = int(input(''' |[1 - CONFIRMAR]| |[2 - CANCELAR]| Escolha uma opção: ''')) if check == 1: if buy == 1: hero.equipWeapon(broken_straight_sword) elif buy == 2: hero.equipWeapon(straight_sword) elif buy == 3: hero.equipWeapon(bastard_sword) elif buy == 4: hero.equipWeapon(straight_sword_hilt) else: store.weaponStore() elif option == 2: print('-=' * 49) print('ESPADAS DE DUAS MÃOS'.center(98)) print('Perfeita para guerreiros que querem focar em ataque físico. PRÓS: Ataque físico anto / CONTRAS: Não pode usar em conjunto de escudos.') print('-=' * 49) for i in self.two_handed_greatsword: print(''' -------------------------------------------------------------------------------------------------- !Nome: {} | Ataque físico: {}/{} | Ataque mágico: {}/{} | Chance Crítica: {}% !Preço: {} Souls | Código de compra: {} --------------------------------------------------------------------------------------------------'''.format(i.name, i.phyAttack, i.max_phy_attack, i.magAttack, i.max_mag_attack, i.critical_chance, i.price, i.ID)) print() buy = int(input('Digite o código de compra ou 0 para voltar: ')) if buy == 0: pass else: check = int(input(''' |[1 - CONFIRMAR]| |[2 - CANCELAR]| Escolha uma opção: ''')) if check == 1: if buy == 5: hero.equipWeapon(flamberge) elif buy == 6: hero.equipWeapon(claymore) elif buy == 7: hero.equipWeapon(stone_greatsword) elif buy == 8: hero.equipWeapon(greatlord_greatsword) else: store.weaponStore() # Menu de batalha def battle_interface(enemy): global max_hp, battle_result battle_result = None #Numero de rodadas por batalha turn = 0 while True: turn += 1 if turn == 1: max_hp = hero.hp sleep(1) print('-' * 50) choice = int(input(""" ------------------------------------------ | Vida: {} | Mana: {} | Qtd Estus: {} | ------------------------------------------ -======================- *[ 1 ] ATACAR * *[ 2 ] ESTUS FLASK * *[ 3 ] FUGIR * -======================- Escolha uma opção: """.format(hero.hp, hero.mp, hero.estus_flask))) print('-' * 50) if choice == 1: hero.attack(enemy) if enemy.hp <= 0: battle_result = True return battle_result elif choice == 2: hero.estusFlask() if hero.estus_flask == 0: continue elif choice == 3: print('Você fugiu!') break enemy.attack(hero) if hero.hp <= 0: print('Você foi derrotado!') battle_result = False return battle_result #------------------------------------------------------------------------------------------- #Objects: WEAPONS | #_________________| #Swords: #ID, name='', phyAttack=0, max_phy_attack=0, magAttack=0, max_mag_attack=0, critical_chance=0, price=0) broken_straight_sword = Equips(1, 'Broken Straight Sword', 10, 15, 0, 0, 0, 200) straight_sword = Equips(2, 'Straight Sword', 20, 25, 0, 0, 5, 500) bastard_sword = Equips(3, 'Bastard Sword', 30, 37, 0, 0, 5, 1500) straight_sword_hilt = Equips(4, 'Straight Sword Hilt', 40, 50, 0, 0, 10, 2000) #Lista dos objetos swords que suprirá a loja one_handed_swords = [broken_straight_sword, straight_sword, bastard_sword, straight_sword_hilt] #Greatswords: flamberge = Equips(5, 'Flamberge', 18, 23, 0, 0, 0, 500) claymore = Equips(6, 'Claymore', 27, 33, 0, 0, 5, 1000) stone_greatsword = Equips(7, 'Stone Greatsword', 35, 45, 0, 0, 0, 1750) greatlord_greatsword = Equips(8, 'Great Lord Greatsword', 50, 60, 0, 0, 5, 3000) #Lista dos objetos greatswords que suprirá a loja two_handed_greatsword = [flamberge, claymore, stone_greatsword, greatlord_greatsword] #------------------------------------------------------------------------------------------- #Objects: BOSSES | #_________________| #name='', phyAttack=50, max_phy_attack=60, magAttack=65, max_mag_attack=75, phyDef=40, #magDef=35, hp=500, mp=100, souls=50 asylum_demon = Monster('Asylum Demon', 25, 35, 0, 0, 15, 30, 300, 100, 500) bell_gargoyle = Monster('Bell Gargoyle', 30, 40, 25, 35, 35, 40, 500, 100, 750) #------------------------------------------------------------------------------------------- #Início do programa #introdução ''' print('-=' * 50) print('Na Era dos Antigos,') sleep(3) print('O mundo era disforme, envolto por névoa.') sleep(3) print('Uma terra de penhascos cinzentos, arquiárvores e dragões eternos.') sleep(3) print('Mas então, fez-se o fogo.') sleep(3) print('Mas com o fogo, veio a disparidade.') sleep(3) print('Calor e frio,') sleep(3) print('vida e morte,') sleep(3) print('e é claro... Luz e Escuridão.') sleep(3) print('E então, da Escuridão eles vieram,') sleep(3) print('e encontraram as almas dos lordes na chama.') sleep(3) print('Nito, o Primeiro dos Mortos,') sleep(3) print('a Bruxa de Izalith com suas filhas do Caos,') sleep(3) print('Gwyn, o Lorde da Luz Solar, com seus leais cavaleiros,') sleep(3) print('e o furtivo pigmeu, tão facilmente esquecido.') sleep(3) print('Com a força dos lordes, eles desafiaram os dragões.') sleep(3) print('Os poderosos raios de Gwyn perfuraram suas escamas de pedras.') sleep(3) print('As bruxas conjuraram violentas tempestades de fogo') sleep(3) print('Nito lançou um miasma de morte e pestilência.') sleep(3) print('E Seath, o Descamado, traiu sua espécie.') sleep(3) print('Com isso, os dragões sucumbiram.') sleep(3) print('E assim teve início a Era do Fogo.') sleep(3) print('Sem demora, contudo, as chamas se apagarão e restará somente a Escuridão.') sleep(3) print('Mesmo agora, há apenas brasas,') sleep(3) print('e no lugar da luz, a humanidade vê apenas noites sem fim.') sleep(3) print('Além disso, entre os vivos se vê portadores da amaldiçoada Marca Negra.') print('-=' * 50) #Introdução 2 sleep(3) print('Sim, de fato.') sleep(3) print('A Marca Negra assinala os Mortos-vivos.') sleep(3) print('E nesta terra,') sleep(3) print('os Mortos-vivos são agrupados e levados ao norte,') sleep(3) print('onde são então trancados e deixados à espera do fim do mundo.') sleep(3) print('...Esse é o seu destino.') print() sleep(3) ''' print(""" _____ _ _____ _ | __ \ | | / ____| | | | | | | __ _ _ __| | __ | (___ ___ _ _| |___ | | | |/ _` | '__| |/ / \___ \ / _ \| | | | / __| | |__| | (_| | | | < ____) | (_) | |_| | \__ \ """) hero = Hero() store = Store(one_handed_swords, two_handed_greatsword) #Escolher o nome do personagem hero.createCharacter() #Escolher a classe do personagem hero.choseClass() #Equipando a arma #hero.equipWeapom(straight_sword_hilt) store.weaponStore() battle_interface(asylum_demon) print('-=' * 20) if battle_result: print('Parabéns, você acaba de derrotar o Asylum Demon!')
2e728336dc03b6a5650a39424869caad3e2a4d31
kamekame/alpha
/module/lxml_.py
2,414
3.984375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Often used function for extracting data from a XML-file. This file is not ready yet. """ # from lxml import etree import xml.etree.ElementTree as ET def parse_xml(topic): xmlpath = '' if topic == 'contacts': xmlpath = "/home/kame/Dropbox/data/contacts.xml" if topic == 'music': xmlpath = "/home/kame/Dropbox/data/music.xml" else: print("Error: topic not found") xml_ = ET.parse(xmlpath) return xml_ def print_whole_xml(xml_): print(ET.tostring(xml_)) def count_items(xpath): n_items = len(xml.xpath(xpath)) print(str(n_items) + " items") return n_items def item_attributes(xml_): # show attributes between the item tag import re # print(etree.tostring(xml)) lst = re.findall(r'<\/?(.*?)\/?>', ET.tostring(xml_)) # print(lst) # count all tags print("number of tags: " + str(len(lst))) from collections import Counter c = Counter(lst) taglist = [] # print("most used attributes: " + str(c.most_common(4)[0][0]) + ", " + # str(c.most_common(4)[1][0]) + ", " + str(c.most_common(4)[2][0])) for letter, count in c.most_common(15): # print('%s: %7d' % (letter, count)) taglist.append(letter) # print all existing tags taglist = list(set(taglist)) # first word is outer tag print("most outer tag: " + lst[0]) taglist.remove(lst[0]) # print(taglist) # second word depicts every item print("item tag (e.g. item): " + lst[1]) taglist.remove(lst[1]) # show attributes print("attributes: " + str(taglist)) xml = parse_xml('contacts') # print_whole_xml(xml) # count_items(xml) item_attributes(xml) # get_y_if_x_equal_xx(xml) # todo # print all artists # print(xml.xpath("//artist/text()")) # print first artist # print(xml.xpath("//item[1]/artist/text()")) # print all song titles # print(xml.xpath("//song/text()")) # n_songs # print(str(len(xml.xpath("//song/text()"))) + " songs") # artist = 'Arovane' # for i in range(1, n_items+1): # temp = str(xml.xpath("//item[" + str(i) + "]/artist/text()")) # if temp[2:-2] == artist: # print("Artist '" + str(artist) + "' found at position " + str(i)) # print("Song of this artist: " + str(xml.xpath("//item[" + str(i) + "]/song/text()"))[2:-2]) if __name__ == '__main__': pass # print_whole_xml(sys.argv[1])
177cce3a76c3a46b87ec9beb33f4b52728212de7
rockdonald2/leetcode
/iteratorBST/index.py
1,071
3.8125
4
from typing import List class TreeNode: def __init__(self, val: int=0, left=None, right=None): self.val = val self.left = left self.right = right class BSTIterator: def __init__(self, root: TreeNode): self._st = [] self._index = 0 self._traverse(root) def _traverse(self, root: TreeNode): if not root: return self._traverse(root.left) self._st.append(root) self._traverse(root.right) def next(self) -> int: """ @return the next smallest number """ if self.hasNext(): old = self._index self._index += 1 return self._st[old] def hasNext(self) -> bool: """ @return whether we have a next smallest number """ if self._index < len(self._st): return True else: return False root = TreeNode(5) root.left = TreeNode(1) root.right = TreeNode(7) root.right.right = TreeNode(8) root.right.left = TreeNode(6) it = BSTIterator(root)
21833eed52139390e9de371bf7e41ae2bd326efb
laraflynn/tipcalculator
/main.py
1,935
3.90625
4
# Author: Lara Flynn # Created: June 19 2020 # Last Updated: June 22 2020 import tkinter from tkinter import Entry, Frame, Button, Label, StringVar, END # get the numbers from input def retrieveEntry(): bill = 0 percent = 0 try: bill = float(my_entry1.get()) except ValueError: resultLabel.config(text = "Please enter a number for both inputs.") try: percent = float(my_entry2.get()) except ValueError: resultLabel.config(text = "Please enter a number for both inputs.") # valid input, go on if type(bill) == float and type(percent) == float: tip = bill * (percent / 100) total = bill + tip returnEntry(tip, total) # show the resulting tip and total def returnEntry(tip, total): str1 = "Your tip is " + str('{:.2f}'.format(tip)) + "." str2 = "Your total is " + str('{:.2f}'.format(total)) + "." resultLabel.config(text = str1 + "\n" + str2) # delete inputs when done calculating my_entry1.delete(0, END) my_entry2.delete(0, END) # the main GUI root = tkinter.Tk() root.geometry("300x200") root.title("Tip Calculator") # use to format everything nicely frame = Frame(root) frame.pack() # create a fresh label to show output resultLabel = Label(root, text = "") resultLabel.pack() # inform and get first input text1 = StringVar() text1.set("How much was the bill?") text1Dir = Label(frame, textvariable = text1, height = 1) text1Dir.pack() my_entry1 = Entry(frame, width = 20) my_entry1.pack(padx = 5, pady = 5) # inform and get second input text2 = StringVar() text2.set("How much, in percent, do you plan to tip?") text2Dir = Label(frame, textvariable = text2, height = 1) text2Dir.pack() my_entry2 = Entry(frame, width = 10) my_entry2.pack(padx = 5, pady = 5) # button to submit Button = Button(frame, text = "Calculate", command = retrieveEntry) Button.pack(padx = 5, pady = 5) root.mainloop()
fe32b21f23ea1cda37ee656592f42970b083604c
ParulProgrammingHub/assignment-1-devang2011
/9.py
396
3.71875
4
s1=float(input( " Enter Marks of subject 1 ")) s2=float(input( " Enter Marks of subject 2 ")) s3=float(input( " Enter Marks of subject 3 ")) s4=float(input( " Enter Marks of subject 4 ")) s5=float(input( " Enter Marks of subject 5 ")) tot=(s1+s2+s3+s4+s5) mean=(tot)/5 print ( " mean ",mean) per=(tot*100)/500 print ( " Per ",per) if per <= 35 : print( " Fail ") else : print( " Pass ")
f6c898d25cab7bd1ccba0f048829b68c56d14532
musale/advent-of-code-2018
/day_2/part_2.py
855
3.828125
4
"""Get the common letters between two correct IDs.""" def main(): """Check for the common letters and remove them.""" with open("day_2/input.txt") as file: file_input = file.readlines() for i, word in enumerate(iter(file_input)): for next_word in iter(file_input[i+1:]): common_word, ok = compare(word, next_word) if ok: print(common_word) def compare(word, next_word): """Compares 2 words and returns the word with 1 different character.""" idx = -1 if len(word) != len(next_word): return "", False for i, _ in enumerate(word): if word[i] == next_word[i]: continue if idx >= 0: return "", False idx = i return word[:idx] + word[idx+1:], True if __name__ == "__main__": main()
916eaebe04a76c2646bf42dde6d2eea444c18901
smcnearney/python2
/dictionaries3.py
358
4.34375
4
meal = { "drink": "beer", "appetizer": "chips", "entree": "tacos", "dessert": "churros" } print(meal) #Change drink to green tea and get rid of dessert #When you pass a dictionary a NEW key, it creates the key #When you pass a dictionary a key it already has, it REPLACES the key meal["drink"] = "green tea" del meal["dessert"] print(meal)
36419e717c2f90ffd40bd02b551d1470c740e55a
codeGoogler/MyPythonPrintF
/test3.py
381
3.625
4
# 读取生成的input.txt内容 if __name__ == '__main__': f1 = open('input.txt') # 读取的数据类型为str number1 = int(f1.read()) # 执行你要执行的程序(例子为计算平方) number2 = number1 * number1 # 把运行的结果写入result.txt中 f2 = open('result.txt', 'w') f2.write((str(number2))) f1.close() f2.close()
06c441e79832a80519c9101113fac1e0decad80a
fainaszar/pythonPrograms
/maxim.py
377
3.5
4
input_params = raw_input().split() lists=[] for i in range(int(input_params[0])): list = raw_input().split() list = map(int ,list) lists.append(list) sum = 0 from itertools import product product(*lists) print product print "Sum is %r" % sum for list in lists: maxItem = max(list) square = maxItem **2 sum += square print sum % int(input_params[1])
a4ba0daddb3d42c24d3034a41ad3740f0527220e
zake7749/TensorFlow-Study-Notes
/1. MNIST/MNIST_CNN.py
3,815
3.671875
4
'''' Use a CNN to solve MNIST. ''' import numpy as np import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data # Hpyer parameter TRAINING_EPOCH = 5 BATCH_SIZE = 128 LEARNING_RATE = 1e-2 CLASS = 10 KEEPRATIO = .75 class CNN(object): def __init__(self, session): self.features = tf.placeholder(dtype='float32', shape=[None,784]) self.labels = tf.placeholder(dtype='float32', shape=[None,10]) self.sess = session self.build() def build(self): cnn_x = tf.reshape(self.features, shape=(-1,28,28,1)) # (batch, height, width, channel) # Convolution layer 1 # conv2d takes a filter with shpae [filter_height, filter_width, in_channels, out_channels] W1 = tf.Variable(tf.random_normal([3, 3, 1, 32], stddev=0.01)) CL1 = tf.nn.conv2d(cnn_x, W1, strides=[1, 1, 1, 1], padding='SAME') # ksize is for the window size for each dimension, which is (batch, height, width, channel) # we usally set ksize for [1, pool_window_height, pool_window_width, 1], because doing maxpooling on the # batch or channel does not make sense. CL1 = tf.nn.max_pool(CL1, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME') CL1 = tf.nn.dropout(CL1, keep_prob=KEEPRATIO) # Convolution layer 2 W2 = tf.Variable(tf.random_normal([3, 3, 32, 64], stddev=0.01)) CL2 = tf.nn.conv2d(CL1, W2, [1,1,1,1], padding='SAME') CL2 = tf.nn.max_pool(CL2, ksize=[1, 2, 2, 1], strides=[1, 2, 2 ,1], padding='SAME') CL2 = tf.nn.dropout(CL2, keep_prob=KEEPRATIO) # Fully connected NN flattened_x = tf.reshape(CL2, shape=[-1, 7 * 7 * 64]) # get a image with size= (28/2/2) = 7, and we have 64 filters. W3 = tf.Variable(tf.random_normal([7 * 7 * 64, 10])) B3 = tf.Variable(tf.random_normal([10])) logits = tf.matmul(flattened_x , W3) + B3 self.logits = tf.nn.softmax(logits) self.cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits( logits=logits, labels=self.labels)) self.optimizer = tf.train.AdamOptimizer( learning_rate=LEARNING_RATE).minimize(self.cost) correct_prediction = tf.equal(tf.argmax(logits, 1), tf.argmax(self.labels, 1)) self.accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) def predict(self, x_test): return self.sess.run(self.logits, feed_dict={self.features: x_test}) def predict_class(self, x_test): hypothesis = self.predict(x_test) return np.argmax(hypothesis) def get_accuracy(self, x_test, y_test): return self.sess.run(self.accuracy, feed_dict={self.features: x_test, self.labels: y_test}) def train(self, x_data, y_data, keep_prop=0.7): return self.sess.run( [self.cost, self.optimizer], feed_dict={ self.features: x_data, self.labels: y_data } ) def main(): sess = tf.Session() cnn = CNN(sess) sess.run(tf.global_variables_initializer()) # Load the MNIST Data mnist = input_data.read_data_sets("MNIST_data/", one_hot=True) # Training for epoch in range(TRAINING_EPOCH): cost = 0. total_batch = int(mnist.train.num_examples / BATCH_SIZE) for i in range(total_batch): batch_xs, batch_ys = mnist.train.next_batch(BATCH_SIZE) c, _ = cnn.train(batch_xs, batch_ys) cost += c avg_cost = c / total_batch print('Epoch #%2d' % (epoch+1)) print('- Average cost: %4f' % (avg_cost)) # Testing print('Accuracy:', cnn.get_accuracy(mnist.test.images, mnist.test.labels)) if __name__ == "__main__": main()
8e3378c32800b0e88358bc1ebb1036ce44c39643
DiyanKalaydzhiev23/OOP---Python
/Encapsulation - Exercise/Pizza/pizza.py
1,533
4
4
class Pizza: def __init__(self, name, dough, toppings_capacity): self.name = name self.dough = dough self.toppings_capacity = toppings_capacity self.toppings = {} @property def name(self): return self.__name @name.setter def name(self, value): if not value: raise ValueError("The name cannot be an empty string") self.__name = value @property def dough(self): return self.__dough @dough.setter def dough(self, value): if not value: raise ValueError("You should add dough to the pizza") self.__dough = value @property def toppings_capacity(self): return self.__toppings_capacity @toppings_capacity.setter def toppings_capacity(self, value): if value <= 0: raise ValueError("The topping's capacity cannot be less or equal to zero") self.__toppings_capacity = value def add_topping(self, topping): if len(self.toppings) < self.toppings_capacity: if topping.topping_type in self.toppings: self.toppings[topping.topping_type] += topping.weight else: self.toppings[topping.topping_type] = topping.weight return raise ValueError("Not enough space for another topping") def calculate_total_weight(self): total_weight = 0 for w in self.toppings.values(): total_weight += w return total_weight + self.dough.weight
400b8f09bc0bc97e9e779641126672723d9265a2
Ashok-Mishra/python-samples
/python exercises/dek_program083.py
405
3.96875
4
#!/usr/bin/python # -*- coding: utf-8 -*- #- Author : (DEK) Devendra Kavthekar # program083: # Please write a program to print the running time of execution of "1+1" # for 100 times. # Hints: # Use timeit() function to measure the running time. from timeit import Timer def main(): time = Timer("for iter in range(100):1+1") print time.timeit() if __name__ == '__main__': main()
e9100ef719d45a22962437858e414764073b8127
sivaprasadkonduru/Python-Programs
/Dreamwin5/nestedfor.py
200
3.6875
4
a = [3, 4, 5] b = [7, 8, 9] #c = [(3, 7), (4, 8), 5, 9] c = [] for i in enumerate(a): #(0, 3) for j in enumerate(b): #(0, 7) if i[0] == j[0]: c.append((i[1], j[1])) print(c)
83e014847357a65a186184432bdccdaa74f150ff
PushkarIshware/pythoncodes
/bridgelabz_pythonproj/functional/stockqueue.py
1,083
3.765625
4
''' /********************************************************************************** * Purpose: stock management queue * * @author : Janhavi Mhatre * @python version 3.7 * @platform : PyCharm * @since 8-1-2019 * ***********************************************************************************/ ''' from utilities import stockutilqueue def stock(): print("1. login / 2. create account") # ask user whether he/she want to login or create account i = int(input()) if i == 1: name = input("enter name ") stockutilqueue.ss.account_details(name) else: stockutilqueue.ss.create_account() print("enter choice 1.sell 2.buy 3.add ") # after login ask for sell/buy/add share ch = int(input()) try: if ch == 1: stockutilqueue.ss.sell() elif ch == 2: stockutilqueue.ss.buy() elif ch == 3: stockutilqueue.ss.add() else: print("wrong choice") raise ValueError except ValueError: print("only int") if __name__ == "__main__": stock()
37b1c34af974874f5732707966129b731ed0eb29
hanjasn/ctci
/recursion_and_dynamic_programming/towers_of_hanoi/stack.py
823
3.625
4
from typing import TypeVar T = TypeVar('T') class Stack: def __init__(self) -> None: self.top = None self.size = 0 def push(self, data: T) -> None: node = StackNode(data) node.next = self.top self.top = node self.size += 1 def pop(self) -> T: if self.empty() == True: return None data = self.top.data self.top = self.top.next self.size -= 1 return data def peek(self) -> T: if self.empty() == True: return None return self.top.data def get_size(self) -> int: return self.size def empty(self) -> bool: return self.size == 0 class StackNode: def __init__(self, data: T) -> None: self.data = data self.next = None
632d47d846347fa3c78bbcee501ffd30008f683b
iman1000000/pygcurses60
/demo_maze.py
6,824
3.828125
4
# Pygcurse Maze # By Al Sweigart al@inventwithpython.com # Maze Generation code by Joe Wingbermuehle # This program is a demo for the Pygcurse module. # Simplified BSD License, Copyright 2011 Al Sweigart import pygcurse, pygame, sys, random, time from pygame.locals import * BLUE = (0, 0, 128) YELLOW = (255, 255, 0) GREEN = (0, 255, 0) BLACK = (0,0,0) RED = (255,0,0) MAZE_WIDTH = 41 MAZE_HEIGHT = 41 FPS = 40 win = pygcurse.PygcurseWindow(MAZE_WIDTH, MAZE_HEIGHT, fullscreen=False) pygame.display.set_caption('Pygcurse Maze') win.autowindowupdate = False win.autoupdate = False class JoeWingMaze(): # Maze generator in Python # Joe Wingbermuehle # 2010-10-06 # http://joewing.net/programs/games/python/maze.py def __init__(self, width=21, height=21): if width % 2 == 0: width += 1 if height % 2 == 0: height += 1 # The size of the maze (must be odd). self.width = width self.height = height # The maze. self.maze = dict() # Generate and display a random maze. self.init_maze() self.generate_maze() #self.display_maze() # prints out the maze to stdout # Display the maze. def display_maze(self): for y in range(0, self.height): for x in range(0, self.width): if self.maze[x][y] == 0: sys.stdout.write(" ") else: sys.stdout.write("#") sys.stdout.write("\n") # Initialize the maze. def init_maze(self): for x in range(0, self.width): self.maze[x] = dict() for y in range(0, self.height): self.maze[x][y] = 1 # Carve the maze starting at x, y. def carve_maze(self, x, y): dir = random.randint(0, 3) count = 0 while count < 4: dx = 0 dy = 0 if dir == 0: dx = 1 elif dir == 1: dy = 1 elif dir == 2: dx = -1 else: dy = -1 x1 = x + dx y1 = y + dy x2 = x1 + dx y2 = y1 + dy if x2 > 0 and x2 < self.width and y2 > 0 and y2 < self.height: if self.maze[x1][y1] == 1 and self.maze[x2][y2] == 1: self.maze[x1][y1] = 0 self.maze[x2][y2] = 0 self.carve_maze(x2, y2) count = count + 1 dir = (dir + 1) % 4 # Generate the maze. def generate_maze(self): random.seed() #self.maze[1][1] = 0 self.carve_maze(1, 1) #self.maze[1][0] = 0 #self.maze[self.width - 2][self.height - 1] = 0 # maze generator modified to have randomly placed entrance/exit. startx = starty = endx = endy = 0 while self.maze[startx][starty]: startx = random.randint(1, self.width-2) starty = random.randint(1, self.height-2) while self.maze[endx][endy] or endx == 0 or abs(startx - endx) < int(self.width / 3) or abs(starty - endy) < int(self.height / 3): endx = random.randint(1, self.width-2) endy = random.randint(1, self.height-2) self.maze[startx][starty] = 0 self.maze[endx][endy] = 0 self.startx = startx self.starty = starty self.endx = endx self.endy = endy def main(): newGame = True solved = False moveLeft = moveRight = moveUp = moveDown = False lastmovetime = sys.maxsize mainClock = pygame.time.Clock() while True: if newGame: newGame = False # if you want to see something cool, change the False to True jwmaze = JoeWingMaze(MAZE_WIDTH, MAZE_HEIGHT) maze = jwmaze.maze solved = False playerx, playery = jwmaze.startx, jwmaze.starty endx, endy = jwmaze.endx, jwmaze.endy breadcrumbs = {} if (playerx, playery) not in breadcrumbs: breadcrumbs[(playerx, playery)] = True # handle input for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() elif event.type == KEYDOWN: if solved or event.key == K_BACKSPACE: newGame = True elif event.key == K_ESCAPE: pygame.quit() sys.exit() elif event.key == K_UP: moveUp = True moveDown = False elif event.key == K_DOWN: moveDown = True moveUp = False elif event.key == K_LEFT: moveLeft = True moveRight = False elif event.key == K_RIGHT: moveRight = True moveLeft = False lastmovetime = time.time() - 1 elif event.type == KEYUP: if event.key == K_UP: moveUp = False elif event.key == K_DOWN: moveDown = False elif event.key == K_LEFT: moveLeft = False elif event.key == K_RIGHT: moveRight = False # move the player (if allowed) if time.time() - 0.05 > lastmovetime: if moveUp and isOnBoard(playerx, playery-1) and maze[playerx][playery-1] == 0: playery -= 1 elif moveDown and isOnBoard(playerx, playery+1) and maze[playerx][playery+1] == 0: playery += 1 elif moveLeft and isOnBoard(playerx-1, playery) and maze[playerx-1][playery] == 0: playerx -= 1 elif moveRight and isOnBoard(playerx+1, playery) and maze[playerx+1][playery] == 0: playerx += 1 lastmovetime = time.time() if playerx == endx and playery == endy: solved = True # display maze drawMaze(win, maze, breadcrumbs) if solved: win.cursor = (win.centerx - 4, win.centery) win.write('Solved!', fgcolor=YELLOW, bgcolor=RED) moveLeft = moveRight = moveUp = moveDown = False win.putchar('@', playerx, playery, RED, BLACK) win.putchar('O', jwmaze.endx, jwmaze.endy, GREEN, BLACK) win.update() pygame.display.update() mainClock.tick(FPS) def isOnBoard(x, y): return x >= 0 and y >= 0 and x < MAZE_WIDTH and y < MAZE_HEIGHT def drawMaze(win, maze, breadcrumbs): for x in range(MAZE_WIDTH): for y in range(MAZE_HEIGHT): if maze[x][y] != 0: win.paint(x, y, BLUE) else: win.paint(x, y, BLACK) if (x, y) in breadcrumbs: win.putchar('.', x, y, RED, BLACK) if __name__ == '__main__': main()
30f8d17fab25c7622e3581b53eb86c1689f78cf9
MokahalA/ITI1120
/Lab 11 Work/Lab11Ex2.py
346
3.96875
4
def count_digits(n): """(int) -> int Return the number of digits in the integer n. Precondition: n >= 0 """ if n // 10 == 0: return 1 return 1 + count_digits(n//10) #test print(count_digits(0)) #1 print(count_digits(7)) #1 print(count_digits(73)) #2 print(count_digits(13079797)) #8
aa73390273cea301ec3b5049bfc59b073cea61d3
Gurpreet-Moudgill/Python-Lab
/strings.py
170
4.03125
4
v = "My name is" w = " Gurpreet Moudgill" print(v) print(w) # concatenation vw = v+w print(vw) # string slicing print(v[3:9]) print(v[2:7]) # extended slicing print(v[2: 9: 2])
9f4b2149b3df9008be66423ee1a5506c9ec8b030
claw0ed/Python3Lab
/List.py
8,167
3.671875
4
# 파이썬 자료구조 # 리스트 : sequence 자료구조를 사용 # sequence : 순서가 있는 데이터 구조를 의미 # 리스트, 튜불, 레인지, 문장열등이 sequence 구조 사용 # 리스트 [] 을 이용해서 각 요소에 접근할 수 있다 msg = 'Hello, World!!' # 파이썬에서는 자료구조를 의미하는 접미사를 # 변수명에 사용하기도 한다 list1_list = [] # 빈 리스트 list2_list= [1,2,3,4,5] # 숫자 list3_list = ['a','b','c'] # 문자 list4_list = ['a','b','c',1,2,3,True] # 혼합 print(list1_list) # 간단한 연산 # 요소 존재 여부 파악 : in/out in 연산자 print(1 in list1_list) # False print('a' in list1_list) # False print(3 in list2_list) # True # 길이 연산 : len() print( len(list1_list) ) # 0 print( len(list2_list) ) # 5 # 연결 연산 : + print( list2_list + list3_list) # [1, 2, 3, 4, 5, 'a', 'b', 'c'] # 반복 연산 : * print( list2_list * 2) # [1, 2, 3, 4, 5, 1, 2, 3, 4, 5] # 요소의 특정값 참조 : index 사용 print( msg[4], msg[9] ) # o r print(list2_list[2]) # 3 print(list3_list[2]) # c print(list4_list[5]) # 3 # 요소값 변경 : index, = 사용 list2_list[2] = -3 # c print(list2_list) # [1, 2, -3, 4, 5] # 주민코드에서 성별 여부 판별 jumin = [1,2,3,4,5,6,1,2,3,4,5,6,7] if jumin[6] == 1: print('남성 입니다') else: print('여성 입니다') # 주민코드에서 for i in range(0,6): print(jumin[i], end = '') # 줄바꿈없이 출력시 종결문자를 지정 # 특정범위내 요소들을 추출할때는 슬라이스를 사용 [i:j:step] print('\n',jumin[0:6]) # 생년월일 print(jumin[:6]) print(jumin[6:]) # 생년월일 제외 나머지 부분 print(jumin[:]) # 모두 print(jumin[0:6:2]) # 0부터 5까지 홀수자리만 추출 print(jumin[::-1]) # 역순 출력 # print(jumin[100]) # 인덱스 초과 - 오류? (실행안됨) # print(jumin[0:100:2]) # 인덱스 초과 - 오류? (실행안됨) # 리스트관련 통계함수 print( sum(list2_list) ) # 9 print( min(list2_list) ) # -3 print( max(list2_list) ) # 5 # 리스트가 주어지면 이것의 가운데에 있는 요소값을 출력 # [1,2,6,8,4] => 6 # [1,2,6,8,4,10] => 6,8 list = [1,2,6,8,4] list2 = [1,2,6,8,4,10] size = len(list) mid = int(size / 2) print('가운데 값 :', list[mid]) # 요소 수가 홀수 size = len(list2) mid = int(size / 2) # print('가운데 값 :', list[mid-1], list[mid+1]) # 요소 수가 짝수 print('가운데 값 :', list2[mid-1:mid+1]) # 요소 수가 짝수 def listcenter(list): size = len(list) mid = int(size / 2) if size %2 == 0: # 짝수인 경우 print(list[mid-1:mid+1]) else: print(list[mid]) listcenter([1,2,3]) listcenter([1,2,3,4]) # 리스트 조작 함수 # 요소 추가 : append list = [1,2,3,4,5] list.append(9) list.append(8) print(list) # 요소 추가 : insert(위치, 값) list.insert(6, 7) print(list) # 요소 제거 : remove(값), 왼쪽부터 검색 후 삭제 list.remove(9) print(list) # 요소 제거 : pop(), pop(위치) list.pop(5) print(list) list.pop() # 마지막 요소 제거 print(list) # 모두 제거 : clear() list.clear() print(list) ### 튜플 tuple # 리스트 자료구조와 유사하지만 # 한번 입력한 자료구조는 변경불가 # 즉, 요소 추가는 가능/수정,삭제는 불가 # 튜플은 () 을 이용해서 # 튜플생성시 단일 요소 뒤에 , 를 추가 t = [1,2,3] # 리스트 t = (1,2,3) t = (1, 'a', True) t = (1) # 숫자 t = (1,) # 단일요소로 구성된 튜플 days = ('일','월','화','수','목','금','토') print(days) # 요일을 튜풀로 정의하고 출력 print(days(3)) # '수'요일 출력 print(len(days)) print(days[3:]) # 슬라이스 # days[3] = '水' #튜플요소에 깂 변경 - 불가! ### 집합set # 저장된 데이터를 순서에 따라 관리하지 않고 # 중복을 허용하지 않는 (unique) 자료구조 # 집합은 {} 을 이용 # 집합의 개념에 따라 합/교/차집합이 지언 t = [1,1,1,1] print(t) t = (1,1,1,1) print(t) t = {1,1,1,1} print(t) t = [1,2,3,4,5,6,7,8,9] print(t) t = set( t ) # 리스트 집합으로 변환 print(t) # 집합 정의 # 1월 중 교육받는 날을 집합으로 정의 edu = {2,3,4,5,6,7,8,9,10,11,12 } # 집합의 기본적인 연산 동물 = {'사자','늑대','호랑이','얼룩말'} 육상동물 = {'기린','여우','사슴'} 해상동물 = {'고래','상어','고등어'} 조류 = {'독수리','참새','부엉이'} print( len(동물) ) # 길이 print( '여우' in 육상동물 ) # 여우 검색 : in 연산자 print( '여우' in 조류) # 여우 검색 : in 연산자 # print( 동물[2] ) # 인덱스 연산 : 3번째 동물은? print( 육상동물.union(해상동물) ) # 합집합 print( 육상동물 | 해상동물 ) # 합집합 새로운동물 = 육상동물 | 해상동물 print( 새로운동물.intersection(육상동물) ) # 교집합 print( 새로운동물.intersection(해상동물) ) # 교집합 print( 새로운동물 & 해상동물 ) # 교집합 print( 새로운동물.difference(육상동물) )# 차집합 print( 새로운동물.difference(해상동물) )# 차집합 print( 새로운동물-해상동물 )# 차집합 print( 새로운동물.symmetric_difference(육상동물) )# 대칭차집합 print( 새로운동물 ^ 육상동물 )# 대칭차집합 # 집합에서 제공하는 메서드 동물.add('인간') # 데이터 추가 print(동물) 동물.discard('인간') # 데이터 추가 print(동물) 해상동물.remove('고등어') # 데이터 제거 print(해상동물) 육상동물.pop() # 데이터 확인후 제거 print(육상동물) 동물.clear() print(동물) ### 패킹, 언패킹 # 패킹 packing : 여러 데이터를 변수 하나에 묶어 담기 # 언패킹 unpacking : 변수에 담긴 데이터를 여러 변수에 풀어 놓기 members = (1,2,3,4,5) # 튜플 생성 (packing) a,b,c,d,e = members # 튜플에 저장된 데이터를 언패킹 print(c) members = 1,2,3,4,5 # 패킹시 () 생략 가능 x,y,z = members # 언패킹시 데이터수와 변수갯수 일치 x,y,*z = members # 언패킹시 변수 갯수 불일치시 처리방법 print(z) # n, k, e, m = input().split() a, b, c = 1, 2, 3 # 변수 초기화에 패킹, 언패킹 사용 # 연습문제 풀이 x = [1,2,3,4,5,6,7,8,9] print(x) x.append(10) # 요소 하나를 리스트에 추가 print(x) x.append( [11,12] ) # 하나 이상 요소를 리스트에 추가 print(x) x.remove(11) # 값으로 제거 x.remove(12) print(x) x.reverse() # 요소를 역순으로 배치 print(x) print(x.pop()) print(x) x = [10,5,4,1] # 정렬 안된 리스트 print(x) x.sort() # 리스트 정렬 print(x) # 1,4,5,10 x.insert(3,7) # 10 앞에 7을 삽입 print(x) print(x.count(4)) # 지정한 요소 수 print(x.index(5)) # 요소의 위치값 출력 z = { 1,1,1,2,2,3,3,3 } print(z) # 요소는 모두 3개 z.add(1) # 의미없는 코드 print(z) # 어쨌든 3개 def myRange(start, end, hop = 1): retVal = start while retVal <= end: yield retVal retVal += hop hap =0 for i in myRange(1,5,2): # 결과 : 9 # 종료값이 포함된 range 함수 작성 # 결국, 리스트 형태의 값이 출력 #for i in range(1,5,2): # i : 1, 3 # 결과 : 4 #for i in [1,3,5]: # i : 1, 3, 5 hap += i print(hap) def myRange2(start, end, hop = 1): retVal = start while retVal <= end: #yield retVal #retrun retVal ?? # 중간에 계산결과를 출력 또는 처리 yield retVal # 실행중에 계산된 값은 generator 타입에 저장해 둠 print(retVal) retVal += hop myRange2(1,5,3) a = myRange2(1,5,3) # yield 로 넘긴 데이터는 순환형식의 generator 타입 생성 print(a) print( next(a) ) # generator 타입에 저장된 값은 iterator 형식으로 다룰 수 있음 # iterator 는 리스트에 저장된 객체를 순환하며 하나씩 꺼내 사용하는 자료구조 print( next(a) ) print( next(a) ) for i in a: # generator 타입에 저장된 값은 print(i) # for 문으로도 출력 가능
c367877e183cedf3c2a2b17d6a4ccea036984742
ansarhub/python
/gcd1.py
141
3.84375
4
a=int(input("enter a number")) b=int(input("enter a number")) i=1 while(i<=a and i<=b): if(a%i==0 and b%i==0): gcd=i i=i+1 print(gcd)
e7db5c284c6061f542c0d4dcb0a911c48697759c
jcarball/python-programs
/funciones.py
502
3.59375
4
def mensaje(numero): print("Ingresa un número:", numero) mensaje(1) print() def mensaje(numero): print("Ingresa un número:", numero) numero = 1234 mensaje(1) print(numero) print() def presentar(primerNombre, segundoNombre): print("Hola, mi nombre es", primerNombre, segundoNombre) presentar("Luke", "Skywalker") presentar("Jesse", "Quick") presentar("Clark", "Kent") def strangeFunction(n): if(n % 2 == 0): return True print(strangeFunction(2)) print(strangeFunction(1))
e0abca4cdbb58398cb4b2b870f4d821adf137133
punch2177-cmis/punch2177-cmis-cs2
/cs2quiz3.py
2,133
4.53125
5
#Section 1: Terminology # 1) What is a recursive function? #A recursive function is a funcation that calls itself within the function # # 1 pt # 2) What happens if there is no base case defined in a recursive function? #The recursive function will keep calling itself and there will be an error. # # # 3) What is the first thing to consider when designing a recursive function? #The base case # # # 4) How do we put data into a function call? #You assign it in a variable # wrong # # 5) How do we get data out of a function call? #You return or print the data # # 1 point #Section 2: Reading # Read the following function definitions and function calls. # Then determine the values of the variables a1-d3. #a1 = 6 #a2 = 8 #a3 = -1 # 2 points #b1 = 2 #b2 = 1 #b3 = 3 # 1 point #c1 = -2 #c2 = 4 #c3 = 45 #3 points #d1 = -4 (wrong) #d2 = 8 #d3 = -4 # 1 point #Section 3: Programming #Write a script that asks the user to enter a series of numbers. #When the user types in nothing, it should return the average of all the odd numbers #that were typed in. #In your code for the script, add a comment labeling the base case on the line BEFORE the base case. #Also add a comment label BEFORE the recursive case. #It is NOT NECESSARY to print out a running total with each user input. # +2 base case is present (MUST BE LABELED) 2 points # +2 recursive case is present (MUST BE LABELED) 2 points # +1 base case returns sum/ct (or equivalent) 0 points # +2 recursive case filters even numbers 2 points # +1 recursive case increments sum and ct correctly 1 point # +1 recursive case returns correct recursive call 0 point # +1 main function present AND called 1 point def average(total, amount): number = raw_input("Next number: ") #Base case if number == "" and amount != 0 and total != 0: print amount/total elif number == "" and amount == 0 and total == 0: print " " #Recursive case elif float(number) % 2 == 0: average(total, amount) #Recursive case else: average(total + 1, amount + float(number)) def main(): total = 0 amount = 0 average(total, amount) main()
908d6e6463824640d88a1cba1e0c920feb987151
pavan-2001/Python-Basics
/Classes/Basic_classes/Modifying object properties.py
472
4.125
4
class person: def __init__(self,first_name='Default_first_name',second_name='Default_second_name'): self.first_name=first_name self.second_name=second_name def hello(self): print(f'Hey user this is a member function that says HELLO to the person') print(f'Hello !! ',self.first_name,self.second_name) p1=person() p1.first_name='pavan' p1.second_name='kumar' print(f'{p1.first_name} {p1.second_name}') """ Output: pavan kumar """
a641c07ad1068c74c171439b18ef9141f18bd820
minzhou1003/intro-to-programming-using-python
/practice5/11_11.py
610
3.78125
4
# minzhou@bu.edu def decimal2binary(number): binary_seq = [] while number: binary_seq.append(number % 2) number = number // 2 while len(binary_seq) < 9: binary_seq.append(0) return binary_seq[::-1] def print_res(binary_seq): for i in range(9): if binary_seq[i] == 0: binary_seq[i] = 'H' else: binary_seq[i] = 'T' for j in [0, 3, 6]: res = ' '.join(binary_seq[j:j+3]) print(res) def main(): number = int(input('Enter a number between 0 and 511: ')) print_res(decimal2binary(number)) main()
3923ba595510ae791fad648eaf36ad307088a344
LucaCappelletti94/dictances
/dictances/chebyshev.py
870
3.640625
4
"""Determine the Chebyshev distance beetween the given dictionaries.""" from typing import Dict def chebyshev(a: Dict, b: Dict) -> float: """Determine the Chebyshev distance beetween the given dictionaries. Parameters ---------------------------- a: Dict, First dictionary to consider. b: Dict, Second dictionary to consider. Returns ---------------------------- Return the Chebyshev distance beetween the given dictionaries. """ result = 0 bget = b.__getitem__ aget = a.__getitem__ for key, a_val in a.items(): try: result = max(result, abs(a_val - bget(key))) except KeyError: result = max(result, a_val) for key, b_val in b.items(): try: aget(key) except KeyError: result = max(result, b_val) return result
36c940c3e8ade41a5c18d8e8daacd59f5efdd239
ColinBeeby-Developer/LondonUsers
/integration_tests/test_londonersapi.py
1,842
3.5625
4
''' Module contains integration tests for londoners API ''' import unittest import requests class TestLondonersApi(unittest.TestCase): def testUsersLondon_cityLeeds(self): ''' Test to ensure that 404 is returned when an unknown city is passed in ''' (text, statusCode) = self._performCall('http://localhost:8000/users/leeds', 'GET') self.assertRegex(text, '404 Not Found', 'Returned text is not as expected') self.assertEqual(404, statusCode, 'Returned status code is not as expected') def testUsersLondon_post(self): ''' Test to ensure that POSTing to the end point gives an error ''' (text, statusCode) = self._performCall('http://localhost:8000/users/london', 'POST') self.assertRegex(text, 'method is not allowed', 'Returned text is not as expected') self.assertEqual(405, statusCode, 'Returned status code is not as expected') def _performCall(self, url, verb): ''' Perform the curl call ''' response = None if verb == 'GET': response = requests.get(url) elif verb == 'POST': response = requests.post(url) if not response.status_code: return ('', 999) return (response.text, response.status_code) if __name__ == "__main__": # import sys;sys.argv = ['', 'Test.testName'] unittest.main()
5505d40dd55bb9feb8359d959658d1f2108593a3
Skp80/mle-tech-interviews
/data-structure-challenges/leetcode/268. Missing Number.py
1,893
4.0625
4
""" Given an array nums containing n distinct numbers in the range [0, n], return the only number in the range that is missing from the array. Follow up: Could you implement a solution using only O(1) extra space complexity and O(n) runtime complexity? Example 1: Input: nums = [3,0,1] Output: 2 Explanation: n = 3 since there are 3 numbers, so all numbers are in the range [0,3]. 2 is the missing number in the range since it does not appear in nums. Example 2: Input: nums = [0,1] Output: 2 Explanation: n = 2 since there are 2 numbers, so all numbers are in the range [0,2]. 2 is the missing number in the range since it does not appear in nums. Example 3: Input: nums = [9,6,4,2,3,5,7,0,1] Output: 8 Explanation: n = 9 since there are 9 numbers, so all numbers are in the range [0,9]. 8 is the missing number in the range since it does not appear in nums. Example 4: Input: nums = [0] Output: 1 Explanation: n = 1 since there is 1 number, so all numbers are in the range [0,1]. 1 is the missing number in the range since it does not appear in nums. Constraints: n == nums.length 1 <= n <= 104 0 <= nums[i] <= n All the numbers of nums are unique. Learnings: - Can be solved with manipulation: initialize an integer to nnn and XOR it with every index and value, we will be left with the missing number. - It can also be solved with the Gauss Formula (expected_sum = len(nums)*(len(nums)+1)//2), then substract the actual sum - The "obvious" solution would be: sol = 0 for i in range(len(nums)): sol += (i+1-nums[i]) return sol """ from typing import List class Solution: def missingNumber(self, nums: List[int]) -> int: sol = 0 for i in range(len(nums)): sol ^= i sol ^= nums[i] return sol ^ len(nums) sol = Solution().missingNumber(nums=[9, 6, 4, 2, 3, 5, 7, 0, 1]) print(sol == 8)
8e91a7f48f4542e8f9b5290f2a50d4c805d6744a
eharris99/class
/ascii2.py
171
3.796875
4
#Name: Elise Harris #Date: January 31, 2019 #This program prints ascii mess=input('Enter a phrase: ') print("In ASCII: ") for j in range(0,len(mess)): print(ord(mess[j]))
766aade3a15cc9b6458c88ed849b8e74c979d79a
koketsomotse/Snake-Game-Python-
/snakegame.py
4,378
3.828125
4
#imporintg modules import turtle import time import random import os delay = 0.1 #score score = 0 high_score = 0 #set up the game screen wn=turtle.Screen() wn.title("Snake Game in Python") wn.setup(width=600, height=600) #remives the animation wn.tracer(0) wn.bgcolor("green") #Creating a Snake head head = turtle.Turtle() head.shape("circle") head.speed(0) head.color("grey") head.penup() head.goto(0,0) head.direction = "stop" #Creating the snake food food = turtle.Turtle() food.shape("square") food.speed(0) food.color("red") food.penup() food.goto(0,100) segments = [] #Pen pen = turtle.Turtle() pen.speed(0) pen.color("white") pen.penup() pen.hideturtle() pen.goto(0,260) pen.write("Score: 0 High Score 0", align="center", font=("Courier", 24, "normal")) #Functions def go_up(): if head.direction != "down": head.direction = "up" def go_down(): if head.direction != "up": head.direction = "down" def go_left(): if head.direction != "right": head.direction = "left" def go_right(): if head.direction != "left": head.direction = "right" #moving the head of the snake def move(): if head.direction == "up": y = head.ycor() #moving 20 pixels each time head.sety(y + 20) if head.direction == "down": y = head.ycor() #moving 20 pixels each time head.sety(y - 20) if head.direction == "left": x = head.xcor() #moving 20 pixels each time head.setx(x - 20) if head.direction == "right": x = head.xcor() #moving 20 pixels each time head.setx(x + 20) #Keyboard bindings wn.listen() wn.onkeypress(go_up,"Up") wn.onkeypress(go_down,"Down") wn.onkeypress(go_left,"Left") wn.onkeypress(go_right,"Right") #main game loop while True: wn.update() #checking for a collision with the boader if head.xcor()> 290 or head.xcor()<-290 or head.ycor()>290 or head.ycor()<-290: time.sleep(1) head.goto(0,0) head.direction = "stop" #hide segments for segment in segments: segment.goto(1000,1000) #clear the segment segments.clear() #reset score score = 0 pen.clear() pen.write("Score: {} High Score {}".format(score,high_score), align="center", font=("Courier", 24, "normal")) #check to see if the head has collided with the food if head.distance(food) < 20: #Move the food on a random spot on the screen x = random.randint(-290,290) y = random.randint(-290,290) food.goto(x,y) #adding a segemnt new_segment = turtle.Turtle() new_segment.speed() new_segment.shape("square") new_segment.color("blue") new_segment.penup() segments.append(new_segment) #increasing the score score= score + 10 #check for the high score if score > high_score: high_score = score pen.clear() pen.write("Score: {} High Score {}".format(score,high_score), align="center", font=("Courier", 24, "normal")) #Move the end segment first in reverse order for index in range(len(segments)-1,0,-1): x = segments[index-1].xcor() y = segments[index -1].ycor() segments[index].goto(x,y) #move segment 0 to where the head is if len(segments) >0: x = head.xcor() y = head.ycor() segments[0].goto(x,y) move() #check for collison with the body segments for segment in segments: if segment.distance(head) < 20: time.sleep(1) head.goto(0,0) head.direction = "stop" #hide segments for segment in segments: segment.goto(1000,1000) #clear the segment segments.clear() #clears the score score = 0 pen.clear() pen.write("Score: {} High Score {}".format(score,high_score), align="center", font=("Courier", 24, "normal")) time.sleep(delay) #this keeps the window game always open wn.mainloop()
94f87e3709da20a54ad12126536d8a2b5032e4e0
OphelieAbb/Projets_Python
/Annee_bissextile.py
548
3.921875
4
annee = input("Saisissez une année :") try: annee = int(annee) # Conversion de l'année if annee<=0: raise ValueError("l'année saisie est négative ou nulle") except ValueError: print("La valeur saisie est invalide (l'année est peut-être négative).") if annee % 4 == 0: bissextile = True elif annee % 100 == 0: bissextile = True elif annee % 400 == 0: bissextile = True else : bissextile = False if bissextile : print("L'année est bissextile!") else: print("L'année n'est pas bissextile.")
237825c21138bb6d50e033de78d08aaf907dfe3d
Sirpy-Palaniswamy/HackerRank-Solutions
/Iterable-and-Iterators.py
489
3.546875
4
#Problem """ You are given a list of N lowercase English letters. For a given integer K, you can select any K indices (assume 1-based indexing) with a uniform probability from the list. Find the probability that at least one of the K indices selected will contain the letter: 'a'. """ #Code from itertools import combinations n = int(input()) l = input().split() k = int(input()) C = list(combinations(l, k)) f = filter(lambda c: 'a' in c, C) print("{0:.4}".format(len(list(f))/len(C)))
f22d0886ef0b20f13ce8427575efb721b37ad485
minminmail/PrepareData
/MaxMin.py
2,347
3.53125
4
# -*- coding: utf-8 -*- class MaxMin: # dataFile = open(r"C:\phd_algorithms\datasets_2021\A1\tra.dat","r") f1_max = -1 f1_min = 100 f2_max = -1 f2_min = 100 class_green_number = 0 class_red_number = 0 def __init__(self,dataFile): self.dataFile = dataFile def get_max_min(self): #file = open("C:\phd_algorithms\datasets_2021\A1\tra.dat","r") dataFileOpen = open(self.dataFile,"r") lines = dataFileOpen.readlines() #print(lines) for line in lines: #print(line) if "@" not in line and "f1" not in line : line_list = line.split(",") print(line_list) class_value = line_list[2] class_value = class_value.strip() print("class_value is :" +class_value) if class_value == "green": self.class_green_number=self.class_green_number + 1 elif class_value == "red" : self.class_red_number = self.class_red_number + 1 else: print("class_value is not green or red" ) if line_list[0]!="f1": f1_value = float(line_list[0]) if f1_value >self.f1_max: self.f1_max = f1_value if f1_value<self.f1_min: self.f1_min = f1_value f2_value = float(line_list[1]) if f2_value > self.f2_max: self.f2_max = f2_value if f2_value <self.f2_min: self.f2_min = f2_value else: print("@ is in line :"+line) print("f1_min is :" +"%.3f" % (self.f1_min) ) print("f1_max is :" +"%.3f" %(self.f1_max)) print("f2_min is :" +"%.3f" %(self.f2_min)) print("f2_max is :" +"%.3f" %(self.f2_max)) print("class_green_number is :" +str(self.class_green_number)) print("class_red_number is :" +str(self.class_red_number)) IR_value = int(self.class_green_number/self.class_red_number) print("IR_value is :" +str(IR_value))
f1cbc11872774d0465a6f2b0a0c213fb09e3ae35
stuntgoat/search
/util/__init__.py
420
3.8125
4
""" Utility functions for search problems and solutions. """ def path_from_start(current_node, parent_map): """ Return a list of nodes in order from the starting node to the current node. """ path = [current_node] while True: current_node = parent_map.get(current_node) if not current_node: break path.append(current_node) path.reverse() return path
c0d6393b5f1c18b4945600a1c9b53c7ae9b96701
juhideshpande/LeetCode
/ReverseLinkedList.py
533
3.796875
4
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution(object): def reverseList(self, head): """ :type head: ListNode :rtype: ListNode """ prev=None current=head while(current!=None): next=current.next current.next=prev prev=current current=next self.head=prev return prev
c30e99e5204cfbe4344e6add5b10aaa48c4fc817
skumarpi/sphinx-example
/examplecode/functions.py
232
4.03125
4
def x_squared(x): """ A function to return the square of X. Args: x (float): A float or numpy array Returns: float: The value of x-squared """ return x*x def x_cubed(x): return x*x*x
715f2cc3ee1caf4fef0662f48da3edb7b9984464
madeibao/PythonAlgorithm
/PartA/py二叉树的前序遍历.py
538
3.6875
4
from typing import List class TreeNode(object): def __init__(self,x): self.val = x self.left = None self.right = None class Solution(object): def preOrder(self,root)->List[int]: res = [] def dfs(root): # 调用外部的变量的值。 nonlocal res if not root: return res.append(root.val) dfs(root.left) dfs(root.right) dfs(root) return res if __name__ == "__main__": s =Solution() n2 = TreeNode(2) n3 = TreeNode(3) n4 = TreeNode(4) n2.left = n3 n2.right = n4 print(s.preOrder(n2))
b940011987b8bee25d298b280399701048e16c96
snowlance7/Python-Projects
/week2/Sales Tax Calculator/stcUI_module.py
488
4.03125
4
def get_input(): print("\nENTER ITEMS (ENTER 0 TO END)") item_cost = -1 total = 0.00 while item_cost != 0: item_cost = float(input("Cost of item: ")) total += item_cost return total def display_total(total): print("Total: " + str(total)) def display_sales_tax(sales_tax): print("Sales tax: " + str(sales_tax)) def display_total_after_tax(total_after_tax): print("Total after tax: " + str(total_after_tax))
deeeeb17ae60e2bec02f474d74d3b2ff2fa2b186
leeejin/python_
/Assignment_5weeks/6W_ex1.py
167
3.875
4
age = int(input('나이는?')) mon = int(input('요금은?')) if age>=65: print('요금은',mon * 50/100,'입니다') else: print('요금은',mon,'입니다')
7e0bb490e940a70e4854ed778acff682c498a26b
hoang-ng/LeetCode
/Array/131.py
871
3.921875
4
# 131. Palindrome Partitioning # Given a string s, partition s such that every substring of the partition is a palindrome. # Return all possible palindrome partitioning of s. # Example: # Input: "aab" # Output: # [ # ["aa","b"], # ["a","a","b"] # ] class Solution(object): def partition(self, s): rs = [] self.backtrack(s, 0, [], rs) return rs def backtrack(self, s, start, tempList, rs): if start == len(s): rs.append(tempList) else: for i in range(start, len(s)): if self.isPalindrome(s, start, i): self.backtrack(s, i + 1, tempList + [s[start : i + 1]], rs) def isPalindrome(self, s, low, high): while low < high: if s[low] != s[high]: return False low += 1 high += 1 return True
989d2604f268defc382b0336c5f6dc82f4d96e6e
BeniyamL/alx-higher_level_programming
/0x08-python-more_classes/2-rectangle.py
2,489
4.3125
4
#!/usr/bin/python3 """ class defintion for Rectangle """ class Rectangle: """ Rectangel class """ @property def width(self): """ getter method of width Arguments: nothing Returns: the width of the rectangel """ return self.__width @width.setter def width(self, value): """ setter method for the width Arguments: the width value Returns: nothing """ if type(value) is not int: raise TypeError("width must be an integer") if value < 0: raise ValueError("width must be >= 0") self.__width = value @property def height(self): """ getter method for height Arguments: nothing Returns: the height of the rectangle """ return self.__height @height.setter def height(self, value): """ setter metod for height Arguments: the height value Returns: nothing """ if type(value) is not int: raise TypeError("height must be an integer") if value < 0: raise ValueError("height must be >= 0") self.__height = value def __init__(self, width=0, height=0): """ initialize the widht and height of the rectangel Arguments: width: the width of the rectangle height: the height of the rectangle Returns: nothing """ if type(width) is not int: raise TypeError("width must be an integer") if width < 0: raise ValueError("width must be >= 0") if type(height) is not int: raise TypeError("height must be an integer") if height < 0: raise ValueError("height must be >= 0") self.__width = width self.__height = height def area(self): """ function to find the area of the rectangle Arguments: nothing Returns: the area of the rectangle """ return (self.__width * self.__height) def perimeter(self): """ fucntion to find perimeter of the ractangle Arguments: nothing Returns: the perimeter of the rectangle """ if self.__width == 0 or self.__height == 0: return (0) return (2 * (self.__width + self.__height))
2ed1707aec010c3e6f9c503f702c258fc001311a
pimbi98/Python
/Udemy/AprendeAProgramarPythonConProyectos/10POO/107HerenciaMultiple.py
458
3.65625
4
class A(): def mensaje(self): print("Esto es clase A") def primera(self): print("ESTAS DENTRO DE CLASE A") class B(): def mensaje(self): print("Esto es clase B") def segunda(self): print("ESTAS DENTRO DE CLASE B") class C(A,B): pass c = C() c.mensaje() #Toma la primer clase declarada. En este caso sería A. c.primera() #Me situo en clase A. c.segunda() #Paso a tomar la herencia segunda de la clase B.
3003c4d43dea35a9ab3ae733aeb03a306b30b25a
msagi/advent-of-code-2020
/12/solution.py
1,264
4.34375
4
# https://adventofcode.com/2020/day/12 from dataclasses import dataclass @dataclass class Ferry: directions = ['N', 'E', 'S', 'W'] north: int = 0 east: int = 0 facing: int = 1 # directions[facing] = 'E' def navigate(self, action: str, value: int): if action == 'N': self.north += value return if action == 'S': self.north -= value return if action == 'E': self.east += value return if action == 'W': self.east -= value return if action == 'R': value = int((value % 360) / 90) self.facing = (self.facing + value) % len(self.directions) return if action == 'L': value = int(360 - (value % 360) / 90) self.facing = (self.facing + value) % len(self.directions) return if action == 'F': self.navigate(self.directions[self.facing], value) return def get_manhattan_distance(self) -> int: return abs(self.north) + abs(self.east) ferry = Ferry() with open('input.txt', 'r') as f: for line in f: ferry.navigate(line[:1], int(line[1:])) print(ferry.get_manhattan_distance())
a424866970aa0002e806903b5cbd09b518cbb260
key70/day0411
/ex03.py
2,372
3.59375
4
# 어떤 feature가 그것을 결정하는 가장 중요한 요인인가를 파악중요하다. # 그것을 결정하는데 필요한 데이터를 수집하는것이 중요 import numpy as np import pandas as pd from sklearn import linear_model, model_selection names = ['age','workclass','fnlwgt','education','education-num','marital-status', 'occupation','relationship','race','sex','capital-gain','capital-loss','hours-per-week', 'native-country','income'] df = pd.read_csv("../Data/adult.data.txt", header=None, names=names) df = df[['age','workclass','education','occupation', 'sex','race','hours-per-week','income'] ] new_df = pd.get_dummies(df) print(new_df.head()) print(new_df.columns) x = new_df.iloc[:,:-2] y = new_df.iloc[:,-1] #문제와 답의 차수를 확인해 봅시다. print(x.shape) #(32561, 44) 2차원 print(y.shape) #(32561,) 1차원 train_x, test_x, train_y, test_y = model_selection.train_test_split(x,y) lr = linear_model.LogisticRegression() lr.fit(train_x,train_y) #훈련용 데이터와 답을 갖고 학습을 시킨다. n = [[47, ' Private', ' Prof-school',' Prof-specialty', ' Female',' White',60, ' <=50K']] n_df = pd.DataFrame(n, columns=['age','workclass','education','occupation', 'sex','race','hours-per-week','income']) df2 = df.append(n_df) #알고자하는 데이터를 훈련시킨 feature의 수와 동일하게 하기 위하여 #원래 원본데이터의 맨마지막에 추가시키고 #one-hot Encoding을 합시다. one_hot = pd.get_dummies(df2) print(len(one_hot.columns)) #51 print(len(new_df.columns)) #51 pred_x = np.array( one_hot.iloc[-1, :-2]).reshape(1,-1) pred_y = lr.predict(pred_x) print(pred_y) # n_df = pd.DataFrame(n, columns=['age','workclass','education','occupation', # 'sex','race','hours-per-week','income']) #연습) 고객의 나이, 직업분류, 학력, 직업, 성별, 인종, 주당근무시간을 # 입력받아 연봉이 50000달러 이상이면 "대출가능" # 그렇지 않으면 "대출불가능"을 출력하는 웹어프리케션을 구현합니다. # 단, 직업분류, 학력, 직업, 성별, 인종은 # 우리가 훈련시킬 데이터 adult.data.txt의 내용으로 제한하도록 합니다.
fae5afce687ed1b7eee4063990c345b689fe9414
ChristianF23/Listas_Pilas_Colas
/ListaEncadenada.py
2,175
3.515625
4
from ListaAbstracta import ListaAbstracta class Nodo: """ Representa un nodo para la lista encadenada """ elemento = None siguiente = None def __init__(self, elemento, siguiente): self.elemento = elemento self.siguiente = siguiente class ListaEncadenada(ListaAbstracta): Primero = None tamano = 0 Ultimo = None def agregar(self, Elemento): """ O(n) :param Elemento: :return: """ nuevo = Nodo(Elemento, None) if self.tamano == 0: self.Primero = nuevo else: self.Ultimo.siguiente = nuevo self.Ultimo = nuevo self.tamano += 1 def quitar(self, Elemento): anterior = None auxiliar = self.Primero while auxiliar != None: siguiente = auxiliar.siguiente if auxiliar.elemento == Elemento: anterior.siguiente = siguiente self.tamano -=1 return auxiliar.elemento anterior = auxiliar auxiliar = siguiente def editar(self, index, Elemento): if index >= self.tamano: raise IndexError(f'{index} esta fuera del rango de la lista') aux = self.Primero for i in range (index): aux = aux.siguiente aux.elemento = Elemento def index_of(self, Elemento): indexVar = -1 nodoIndex = self.Primero for i in range (self.tamano): if nodoIndex.elemento == Elemento: indexVar = i return indexVar else: nodoIndex = nodoIndex.siguiente return indexVar def elemento_en(self, index): if index >= self.tamano: raise IndexError(f'{index} esta fuera del rango de la lista') nodoBuscado = self.Primero for i in range(index): nodoBuscado = nodoBuscado.siguiente return nodoBuscado.elemento def __repr__(self): listaRep = [] aux = self.Primero while aux != None: listaRep.append(aux.elemento) aux = aux.siguiente return listaRep
5b9f56a182635ed76e51b4e7ba35cad58e4e313a
hughluo/wexort_img
/rect2circle.py
1,529
3.578125
4
from PIL import Image from math import sqrt from sys import argv def rect2square(img): w, h = img.size if w > h: padding = (w - h) / 2 cropped_img = img.crop((padding, 0, padding + h, h)) else: padding = (h - w) / 2 cropped_img = img.crop((0, padding, w, padding + w)) return cropped_img def square2circle(img): if not img.size[0] == img.size[1]: raise SystemExit('Input Image is not square') else: img = img.convert("RGBA") pixels = img.load() # create the pixel map center_plot = int((img.size[0]) / 2) for i in range(img.size[0]): # for every col: for j in range(img.size[1]): # for every row distance = sqrt((i - center_plot) ** 2 + (j - center_plot) ** 2) if distance > center_plot: pixels[i,j] = (255, 255, 255, 0) # set the colour accordingly # img.show() # out_path = image_path.split('.')[0] + '_out.png' return img def rect2circle(img): return square2circle(rect2square(img)) def main(): try: in_img = Image.open('input.png') except FileNotFoundError: try: in_img = Image.open('input.jpg') except FileNotFoundError: raise SystemExit('No file named input.png or input.jpg') out_path = 'output.png' # in_img = Image.open(in_path) out_img = rect2circle(in_img) # out_img.show() out_img.save(out_path, "PNG") if __name__ == '__main__': main()
f73820bb598d8094245c8097a2799fbc6d7672d3
SalihTasdelen/Hackerrank_Python
/Check_Strict_Superset.py
334
3.53125
4
# Enter your code here. Read input from STDIN. Print output to STDOUT aset = set(map(int, input().split())) flag = 0 for _ in range(int(input())): tset = set(map(int, input().split())) if aset.issuperset(tset): flag = 1 else: flag = 0 break if flag == 1: print("True") else: print("False")
33c0bc7a0fdb2c73448b4e046ca1d7b34d0d7266
jungyr24/algo-rhythm
/이코테/CH07 이진 탐색/떡볶이 떡 만들기.py
1,335
3.5
4
# 갖고 있는 떡 들에서 기준 길이만큼 자르고 남은 자투리 떡들을 모아서 손님한테 판매 # 손님이 요청한 총 떡의 길이가 M일 때 적어도 M만큼의 떡을 얻기 위해 절단기에 설정할 수 있는 높이의 최댓값을 구하는 프로그램 def binary(rice, target, start, end): global m_target if start > end: return m_target mid = (start+end) // 2 # 떡 자르기 total = 0 for r in rice: if mid > r: continue total += (r-mid) # ------ 내 코드 --- 오답 # if total == target: # return mid # if total > target: # m_target = mid # return binary(rice, target, mid+1, end) # else: # return binary(rice, target, start, mid-1) # ------------------ if total < target: # 떡의 양이 부족하면 더 자르기 return binary(rice, target, start, mid-1) else: # 떡의 양이 충분한 경우 덜자르기 m_target = mid # 최대한 덜 잘랐을 때가 정답이므로, 여기서 기록 return binary(rice, target, mid+1, end) n, m = map(int, input().split()) rice = list(map(int, input().split())) m_target = 0 # rice.sort() 정렬 필요없음 result = binary(rice, m, 0, rice[-1]) print(result) """ 4 6 19 15 10 17 """
7dac6ae18904018c6dd8105d9b0b960b1ad1f4ab
navazl/cursoemvideopy
/ex106.py
153
3.8125
4
while True: ajuda = str(input('[FIM para terminar] help: ')).upper() help(ajuda) if ajuda == 'FIM': break print('Obrigado por usar!')
a3fb3104e1fdaae2df4096164708d0f045d4dc2d
rishabhvaish/Python
/Search/Hash Tables: Ice Cream Parlor.py
589
3.765625
4
#!/bin/python3 import math import os import random import re import sys # Complete the whatFlavors function below. def whatFlavors(cost, money): cost_map = {} for i, c in enumerate(cost): sunny = c johnny = money - c if johnny in cost_map.keys(): print(cost_map[johnny]+1, i+1) else: cost_map[c] = i if __name__ == '__main__': t = int(input()) for t_itr in range(t): money = int(input()) n = int(input()) cost = list(map(int, input().rstrip().split())) whatFlavors(cost, money)
a54997c186fc07315a436987b02a5c135412cc74
LeynilsonThe1st/python
/curso-em-video/Desafio57.py
174
3.625
4
import colors sair = False while not sair: sexo = str(input('Degite o seu sexo: ')) if sexo in 'Mm' or sexo in 'Ff': sair = True print(colors.red, 'Terminou')
5d52463d60e1f348fe25b1d58f4eba1d8a7a5a8f
helioh2/oficina2018
/templates/template_funcao.py
634
3.625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- import unittest ''' PROBLEMA: <enunciado do problema> ''' #ESCREVA O CÓDIGO AQUI '''Para cada nova funcao criada, voce deve criar uma funcao dentro da classe Test para testá-la, conforme o template ''' class Test(unittest.TestCase): pass #retirar esta linha após colocar primeiro teste #... ''' <<template>> def test_<nome_funcao>(self): self.assertEqual(<chamada_da_funcao>, <resultado_esperado>) self.assertEqual(<chamada_da_funcao>, <resultado_esperado>) ... ''' unittest.main() #não excluir (a menos que esteja rodando como unit test no PyCharm)
eb3d1bcec574412af74d846fe1736275ac1631ce
osmanozden/basic_python_fundamental
/dictionary.py
627
3.5
4
#Bir key birde volue bilgisi ile çaışmasını istedğimiz ifadeler {} ile kullanılır --> # sozluk1 ={"ADAPAZAR":54,"İSTANBUL":34,"SAMSUN":55} # print(sozluk1["ADAPAZAR"]) #BU SEKİLDE CALISIRLAR. # sozluk1["ADAPAZAR"] =99 #SONRADAN BU SEİLDE ATAMA YAPILABİLİR. # print(sozluk1) #İç İçe SÖZLÜKLER EKLEYEBİLİYORUZ. kullanicilar={ "osmanozden":{ "roller":["yonetici","misafirKullanici"], "email":"ozden.osman@hotmail.com", "telefon":"53662", "dogumYili":1998, #"yas":2020-int(kullanicilar["osmanozden"]["dogumYili"]) } } print(kullanicilar["osmanozden"]["yas"])
ee5b552661dfc603c19b02949cec5ea9172b9c26
l2m2/leetcode
/search-insert-position/main.py
654
3.875
4
''' @File: main.py @Author: leon.li(l2m2lq@gmail.com) @Date: 2018-09-15 21:54:00 @Last Modified By: leon.li(l2m2lq@gmail.com>) @Last Modified Time: 2018-09-15 22:05:29 ''' class Solution: def searchInsert(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ for i in range(len(nums)): if nums[i] == target: return i elif nums[i] > target: return i return len(nums) if __name__ == "__main__": so = Solution() nums = [1,3,5,6] print(so.searchInsert(nums, 5) == 2) print(so.searchInsert(nums, 2) == 1) print(so.searchInsert(nums, 7) == 4) print(so.searchInsert(nums, 0) == 0)
5e0a712ee4d0ece37fefe6b8931e510edc25d85a
greenfox-zerda-lasers/brigittaforrai
/week-04/day-03/copy02.py
305
3.9375
4
from tkinter import * root = Tk() canvas= Canvas(root, width="300", height="300") canvas.pack() def square_line(a): x = a b = a for l in range(0, 6): square = canvas.create_rectangle(x, x, x+a, x+a, fill= "purple") x = x+a a = a +b square_line(10) root.mainloop()
148cc73e2c0cdf84d63783a85fea5ea989492bdb
codexdelta/DSA
/tree/bst.py
2,759
3.875
4
__author__ = 'ashwin' # binary search tree in python """ user: bst = Tree() bst.insert(14) bst.preorder() bst.inorder() bst.postorder() class insert (self, data) find (self, data) preorder() postorder() inorder() Node : insert(self, data) find(self, data) preorder() postorder() inorder() """ class Node: def __init__(self, val): self.value = val self.leftChild = None self.rightChild = None def insert(self,data): if self.value == data: #this is to check whether there is no duplicate datas in our tree return False elif self.value > data: if self.leftChild: return self.leftChild.insert(data) else: self.leftChild = Node(data) return True else: if self.rightChild: return self.rightChild.insert(data) else: self.rightChild = Node(data) return True def find(self, data): if(self.value == data): return True elif self.value > data: if self.leftChild: return self.leftChild.find(data) else: return False else: if self.rightChild: return self.rightChild.find(data) else: return False def preorder(self): if self: print (str(self.value)) if self.leftChild: self.leftChild.preorder() if self.rightChild: self.rightChild.preorder() def postorder(self): if self: if self.leftChild: self.leftChild.postorder() if self.rightChild: self.rightChild.postorder() print (str(self.value)) def inorder(self): if self: if self.leftChild: self.leftChild.inorder() print (str(self.value)) if self.rightChild: self.rightChild.inorder() class Tree: def __init__(self): self.root = None def insert(self, data): if self.root: return self.root.insert(data) else: self.root = Node(data) return True def find(self, data): if self.root: return self.root.find(data) else: return False def preorder(self): print("Preorder:") self.root.preorder() def postorder(self): print("postorder:") self.root.postorder() def inorder(self): print("inorder:") self.root.inorder() bst = Tree() number = raw_input().split(" ") print(bst.insert(10)) print(bst.insert(15)) print(bst.insert(20)) bst.preorder()
b290ca2c53f1eb44fa7c9b0f5dfeec8fc66e969c
Aswin-Sureshumar/Python-Programs
/For.py
259
4.375
4
##for letter in 'python': ##print ('current letter:',letter) fruits=['banana','mango','apple'] ##for fruit in fruits: ##print ('current fruit:',fruit) ##print('good bye') for index in range(len(fruits)): print ('current fruit:',fruits[index])
267c4cb347d11740d15560d592dcf3ddd7fdfae6
MulengaKangwa/PythonCoreAdvanced_Files
/142WritingMutipleStrings.py
140
4
4
f=open("myfile.txt","w") print("Enter Text(Type # when you are done)") s='' while s != '#': s = input() f.write(s+"\n") f.close()
878aa0c89c766f4a5106f43278469b839fd0c124
AakashOfficial/ChallengeTests
/challenge_1/python/wost/main.py
262
4.15625
4
def reverse_string(string): for i in range(len(string) - 1, -1, -1): print(string[i], end="") print() def main(): reverse_string("this was a triumph") reverse_string("hello world") reverse_string("42") if __name__ == "__main__": main()
9b8eaf92a3384ae848cae589c602cbf9bb952432
soumya9988/Python_Machine_Learning_Basics
/Python_Basic/5_Dictionaries/basics_of_dict.py
436
3.640625
4
spam = {'Alice' : 30, 'planets' : ['mars', 'venus', 'earth', 'pluto'], 'pi' : 3.14, 1: 13} # Key, values and items in dictionary print(spam.keys()) print(spam.values()) print(spam.items()) # setdefault method in dict spam.setdefault('colour', 'black') print(spam) spam.setdefault('colour', 'pink') print(spam) # get() method in dict with default value print(spam.get('Alice', 50)) print(spam.get('Alan', 50))
cc44973070dee6c4209a828622ee36fd886eee32
MerajBighamain/python_projects-1
/reverse_str.py
261
4.125
4
def reverse_str_v1(s): r='' for char in s: r=char+r print("\n",r) s=input("give a string:\n") reverse_str_v1(s) #------------------------- def reverse_str_v2(s): r='' for i in range(len(s)-1,-1,-1): r=r+s[i] print(r)
2f689dab16d5d9e8467ee14fc2f84f3888b67060
Rockyzsu/StudyRepo
/python/my_py_notes_万物皆对象/算法/tree.py
1,081
3.609375
4
#!/usr/bin/env python # encoding: utf-8 import json from collections import defaultdict def tree(): """ 定义一棵树 python 字典的特性,赋值操作必须事先声明,所以这里使用 collections 很方便的为字典设置初始值 :return: """ return defaultdict(tree) if __name__ == '__main__': users = tree() users['jack_1']['jack_2_1']['jack_3_1'] = {} users['jack_1']['jack_2_1']['jack_3_2'] = {} users['jack_1']['jack_2_2'] = {} users['jack_1']['jack_2_2']['jack_3_1'] = {} users['lily_1']['lily_2_1']['lily_3_1'] = {} users['lily_1']['lily_2_2']['lily_3_2'] = {} users['lily_1']['lily_2_3']['lily_3_3'] = {} users['emma_1']['emma_2_1'] = {} # 打印 users 原始结构 print(users) # 打印 users json 结构 print(json.dumps(users, indent=4)) # 第一层(users的key) print([i for i in users]) # 第二层(users子节点的key) print([i for i in users['jack_1']]) # 第三层(users孙节点的key) print([i for i in users['jack_1']['jack_2_1']])
9a1e0977d5690f5ae6ca7f608bf5f09e048c5220
ricarcon/programming_exercises
/2021/maxSubArray.py
591
3.796875
4
import sys def maxSubArray(nums): min_index = 0 max_index = 0 current_min_index = 0 current_max_index = 0 maxsum = 0 current_sum = 0 for i in range(len(nums)): if nums[i] > 0: current_sum += nums[i] current_max_index = i elif current_sum > maxsum: maxsum = current_sum max_index = i else: min_index = i return nums[min_index:max_index + 1] # Driver code if __name__ == "__main__": print(maxSubArray([12, 11, -1, 10, 5, 6, 2, 30]))
ed379a6dce86ce57032a41a083a9562c8c52e982
Jaskirat1/jaskirat
/venv/controller.py
306
3.953125
4
#Arithmetic Ooperators:+,-,%,** dish1= 100 dish2= 400 bill = dish1 + dish2 print ("bill is:",bill) #Assume taxes to be 5% taxes = .05*bill print("taxes:",taxes) totalbill =bill +taxes print("Totalbill",totalbill) num1= 2 num2 =3 num3 = num1//num2 print("num3:",num3) num= 149 data= num//100 print(data)
8366bb4ffeed75644a304bbccd7db5a1f47ad999
doplab/act-tp
/2021/week06/solutions/question5-1.py
734
3.578125
4
def recherche_binaire_recursive(L, s, r, x): if r >= s: mid = int((s + r)/2) print(f'Le milieu de la liste {L} est {L[mid]} situé à l\'indice {mid}') if L[mid] == x: return mid elif L[mid] > x: return recherche_binaire_recursive(L, s, mid-1, x) else: # on peut aussi utiliser mid mais mid+1 evite une comparaison # de plus car cette comparaison est faite en amont return recherche_binaire_recursive(L, mid+1, r, x) else: return -1 L=[1,3,4,5,7,8,9,15] s = 0 r = len(L)-1 #8 --> première moitié = 4 -->"7" in L --> 7>5 --> deuxième moitié = (0+4)/2 = 2, etc. x = 8 print(recherche_binaire_recursive(L,s, r, x))
0e37d9fdbd4fd231ecf9d42977117f7557b12812
WindWalker19/Traslator
/translate.py
982
4.53125
5
# The translate function converts all the vowels to a. Just for fun to look how the words look like if i convert the vowel letter # present in them. #first we want to ask the user for an input text. def translate(phrase): #get an empty string where we could store the letters. new_phrase = "" #Then we want to loop through every letter. for letters in phrase: #Check if any of the letter consists of the vowel letter. #converts all the letters to lowercase and check for vowels. if letters.lower() in "aeiou": #check if letter is upper case. Helps solve caps issues. if letters.isupper(): new_phrase += "A" else: # if letters == "a" or letters == "e" or letters == "i" or letters == "o" or letters == "u": #convert the vowel letter to a. new_phrase += "a" else: new_phrase += letters return(new_phrase) print(translate("Umbrella"))
686f5bf2361dadf1e1c8dbd4cd94e2d6fb0fa5f9
leodan87/EjerciciosPython
/dictsFecha.py
573
4.1875
4
''' Escribir un programa que pregunte una fecha en formato dd/mm/aaaa y muestre por pantalla la misma fecha en formato dd de <mes> de aaaa donde <mes> es el nombre del mes. ''' meses={'01':'Enero', '02':'Febrero','03':'Marzo', '04':'Abril', '05':'Mayo','06':'Junio', '07':'Julio', '08':'Agosto','09':'Septiembre', '10':'Octubre', '11':'Noviembre','12':'Diciembre'} fecha=input('Fecha (dd-mm-aaaa): ') flista = fecha.split('-') print(flista) print('{0} de {1} de {2} donde {1} es el nombre de mes'.format( flista[0], meses[flista[1]], flista[2] ) )
d65f2347f9e73a045e5b05728c497f91b3bfb714
raianyrufino/URI-OnlineJudge
/1066.py
385
3.53125
4
contpar = 0 contim = 0 contpos = 0 contneg = 0 for i in range(5): i = int(raw_input()) if i % 2 == 0: contpar += 1 else: contim += 1 if i > 0: contpos += 1 elif i < 0: contneg += 1 print "%d valor(es) par(es)" %(contpar) print "%d valor(es) impar(es)" %(contim) print "%d valor(es) positivo(s)" %(contpos) print "%d valor(es) negativo(s)" %(contneg)
2771b06176016bc62796393fdf98220aa6c64db9
Joshcosh/AutomateTheBoringStuffWithPython
/Lesson_23.py
1,727
4.5625
5
# %% # 1 | What does it take to recognize a phone number without regex # 415-555-0000 - Phone number # 415,550,0000 - Not a phone number def isPhoneNumber(text): if len(text) != 12: return False # not a phone number for i in range(0, 3): if not text[i].isdecimal(): return False # no area code if text[3] != '-': return False # missing dash for i in range(4, 7): if not text[i].isdecimal(): return False # no first 3 digits if text[3] != '-': return False # missing second dash for i in range(8, 12): if not text[i].isdecimal(): return False # missing last 4 digits return True print(isPhoneNumber('415-555-1234')) print(isPhoneNumber('hello')) # Would be useless to recognize a phone number within a larger message # message = 'Call me 415-555-1011 tomorrow, or at 415-555-9999 for my office line.' message = 'Call me 415-555-101 tomorrow, or at 415-555-a999 for my office line.' foundNumber = False for i in range(len(message)): chunk = message[i:i+12] if isPhoneNumber(chunk): print('Phone number found: ' + chunk) foundNumber = True if not foundNumber: print('Could not find any numbers.') # This is too much code............ # %% # 2 | Do the same thing with simple regex import re message = 'Call me 415-555-1011 tomorrow, or at 415-555-9999 for my office line.' # message = 'Call me 415-555-101 tomorrow, or at 415-555-a999 for my office line.' phoneNumRegex = re.compile(r'\d\d\d-\d\d\d-\d\d\d\d') mo = phoneNumRegex.search(message) # mo stands for Match Object print('re.search = ' + mo.group()) mo = phoneNumRegex.findall(message) # mo stands for Match Object print(mo)
b35fcc06f47e901c0b4f7f21ddd942360241d099
portugol/decode
/Algoritmos Traduzidos/Python/Algoritmos traduzidos[Diogo]/ex4.py
111
3.53125
4
a=input('Digite o numero de três casas:') d=0 d=int(a)/100%10 print('Algarismo na casa das centenas:',int(d))
ff3b04f6a055c1b57d4f912824cdd92fbafe5e94
MTrajK/coding-problems
/Arrays/find_one_missing_number.py
940
4.34375
4
''' Find the missing number in a sequence Find the only missing integer in a sequence, all numbers are integers and they're smaller or equal to N+1 (N is length of the array). Input: [2, 1, 4] Output: 3 ========================================= Searching for 1 unknown, math problem. Use the sum formula for the first N numbers to compute the whole sum of the sequence. After that sum all elements from the array, and when you subtract those 2 numbers, you'll get the missing number. Sum formula = N*(N+1)/2 Time Complexity: O(N) Space Complexity: O(1) ''' ############ # Solution # ############ def missing_number(nums): s = sum(nums) n = len(nums) + 1 # sum formula (sum of the first n numbers) = (N*(N+1))/2 return n * (n + 1) // 2 - s ########### # Testing # ########### # Test 1 # Correct result => 4 print(missing_number([2, 3, 1])) # Test 2 # Correct result => 3 print(missing_number([2, 1, 4]))
1f3b503110d129a36b6cd46f265a148679a05476
Hemanthtm2/Python
/exceptions.py
152
3.734375
4
#!/usr/bin/python filename=raw_input("Enter the file name") try: f=open("filename","r") except IOError: print "There is no file named",filename
67ee5f2cdc78b6f77cce1f0156448aa78fb66adc
j1-aggie/python-challenge-
/PyBank/PyBank.py
2,714
3.984375
4
# pybank # import the os module import os # module for reading csv file import csv # set the path for the data file PyBankcsv = os.path.join('.' , 'Resources' , 'Budget_Data.csv') # Set Variables Total_Months = 0 Net_Profit = 0 Greatest_Increase_Profits = 0 Greatest_Decrease_Losses = 0 Monthly_changes = [] Greatest_Month_Increase = 0 Greatest_Month_Decrease = 0 CountofMonths = [] # open and read the csv with open(PyBankcsv, newline='') as csvfile: # reader specifies delimiter csvreader = csv.reader(csvfile, delimiter=',') # read header row first csv_header = next(csvreader) row = next(csvreader) # calculate total number of months previous_row = int(row[1]) Total_Months += 1 # Amount of Profit/Losses - Net Net_Profit += int(row[1]) # Setting variables for rows Greatest_Increase_Profits = int(row[1]) Greatest_Month_Increase = row[0] # read each row for row in csvreader: Total_Months += 1 Net_Profit += int(row[1]) # change from month to month revenue_change = int(row[1]) - previous_row Monthly_changes.append(revenue_change) previous_row = int(row[1]) CountofMonths.append(row[0]) # greatest increase if int(row[1]) > Greatest_Increase_Profits: Greatest_Increase_Profits = int(row[1]) Greatest_Month_Increase = row[0] # greatest decrease if int(row[1]) < Greatest_Decrease_Losses: Greatest_Decrease_Losses = int(row[1]) Greatest_Month_Decrease = row[0] # average change with date average_change = sum(Monthly_changes)/len(Monthly_changes) highest = max(Monthly_changes) lowest = min(Monthly_changes) # output # print out print(f"Financial Analysis") print(f"-----------------------------------------") print(f"Total Months: {Total_Months}") print(f"Total: ${Net_Profit}") print(f"Average Change: ${average_change:.2f}") print(f"Greatest Increase in Profits:, {Greatest_Month_Increase},(${highest})") print(f"Greatest Decrease in Profits:, {Greatest_Month_Decrease}, (${lowest})") #file to write to output_file = os.path.join('.', 'Analysis', 'Final_Analysis_PyBank.txt') with open(output_file, 'w',) as txtfile: # write new data txtfile.write(f"Financial Analysis\n") txtfile.write(f"-----------------------------------\n") txtfile.write(f"Total Months: ${Total_Months}\n") txtfile.write(f"Total: ${Net_Profit}\n") txtfile.write(f"Average Change: ${average_change}\n") txtfile.write(f"Greatest Increase in Profits:, {Greatest_Month_Increase}, (${highest})\n") txtfile.write(f"Greatest Decrease in Profits:, {Greatest_Month_Decrease}, (${lowest})\n")
1a7001821a003d90655ef3b989987023ea313550
csparpa/robograph
/robograph/datamodel/nodes/lib/randoms.py
2,798
3.546875
4
import random import uuid from robograph.datamodel.base import node class IntegerRandomizer(node.Node): """ This node gives a random integer from the specified range. Randomization has a uniform pdd and range defaults to: [0-10) Requirements: range_lower --> lower boundary or randomization range range_upper --> upper boundary or randomization range Eg: IntegerRandomizer(range_lower=3, range_upper=45) """ _reqs = ['range_lower', 'range_upper'] DEFAULT_RANGE_LOWER = 0 DEFAULT_RANGE_UPPER = 10 def output(self): if self._params['range_lower'] is None: lo = self.DEFAULT_RANGE_LOWER else: lo = self._params['range_lower'] if self._params['range_upper'] is None: hi = self.DEFAULT_RANGE_UPPER else: hi = self._params['range_upper'] return random.randint(lo, hi) class FloatRandomizer(node.Node): """ This node gives a random float from the specified range. Randomization has a uniform pdd and range defaults to: [0.0-1.0) Requirements: range_lower --> lower boundary or randomization range range_upper --> upper boundary or randomization range Eg: FloatRandomizer(range_lower=2.2, range_upper=3.6) """ _reqs = ['range_lower', 'range_upper'] DEFAULT_RANGE_LOWER = 0. DEFAULT_RANGE_UPPER = 1. def output(self): if self._params['range_lower'] is None: lo = self.DEFAULT_RANGE_LOWER else: lo = self._params['range_lower'] if self._params['range_upper'] is None: hi = self.DEFAULT_RANGE_UPPER else: hi = self._params['range_upper'] return random.uniform(lo, hi) class GaussianRandomizer(node.Node): """ This node gives a random float sampled with a Gaussian pdd of the given expected value mu and standard deviation sigma. Mu and sigma default to 0.0 and 1.0 respectively. Requirements: mu --> expected value of the Gaussian pdd sigma --> standard deviation value of the Gaussian pdd Eg: GaussianRandomizer(mu=4.7, sigma=8.68) """ _reqs = ['mu', 'sigma'] DEFAULT_MU = 0.0 DEFAULT_SIGMA = 1.0 def output(self): if self._params['mu'] is None: mu = self.DEFAULT_MU else: mu = self._params['mu'] if self._params['sigma'] is None: sigma = self.DEFAULT_SIGMA else: sigma = self._params['sigma'] return random.gauss(mu, sigma) class Uuid4Randomizer(node.Node): """ This node gives a random UUID4 value. Requirements: none Eg: Uuid4(mu=4.7, sigma=8.68) """ _reqs = [] def output(self): return uuid.uuid4()
2186ca62d22541a6c799300d8f223da382195153
jyq920203/python
/SoloLearn网站课程/propertyTest.py
377
3.90625
4
# 写代码的时候遇到很有意思的一个问题,就是在我使用property的时候,我定义的方法跟我的属性名称不一致,结果debug的时候,多出来一个属性 class A: pramA="" pramB="" @property def pramA(self): return self.pramA @pramA.setter def pramA(self,value): self.pramA=value a=A() a.pramA = "b"
c8293311adfaf58008ec1d179af8f329b1de7d4d
tongxindao/shiyanlou
/shiyanlou_cs892/animation.py
342
3.703125
4
#_*_ coding: utf-8 _*_ import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation fig, ax = plt.subplots() x = np.arange(0, 2 * np.pi, 0.01) line, = plt.plot(x, np.sin(x)) def update(i): line.set_ydata(np.sin(x + i / 10.0)) return line animation = animation.FuncAnimation(fig, update) plt.show()
f1ad55ba2dae13342e60e075d11798ee83a4c959
madisontg/Intro-programs-part-two
/cities_in_countries.py
777
3.796875
4
# Madison Thorburn-Gundlach # Due November 11, 2015 # exercise 17 # establish a dictionary cities = {} # open a file for reading file = open("cities.txt", "r") # go through the file line by line for line in file: # create a list for each city line = line.strip() city = line.split(", ") # if the second index (the country) is in the dictionary, += 1 the value of that key if city[1] in cities.keys(): cities[city[1]] += 1 # if not add a new index value thingy else: cities.update({city[1]:1}) print(cities) # go through the file line by line for line in file: # suck down the city line = line.strip() thing = line.split(",") print(thing) # append to the dictionary # report number of cities in a country
5a9bffdd07233affcd6c862b3a6eb388651a371c
renchao7060/studynotebook
/基础学习/p68.py
1,016
3.6875
4
#猴子吃桃问题:猴子第一天摘下若干个桃子,当即吃了一半,还不瘾,又多吃了一个。 #第二天早上又将剩下的桃子吃掉一半,又多吃了一个。以后每天早上都吃了前一天剩下的一半零一个。 #到第10天早上想再吃时,见只剩下一个桃子了。求第一天共摘了多少。 ''' 这题得倒着推。第10天还没吃,就剩1个,说明第9天吃完一半再吃1个还剩1个,假设第9天还没吃之前有桃子p个, 可得:p * 1/2 - 1 = 1,可得 p = 4。以此类推,即可手算出。 代码思路为:第10天还没吃之前的桃子数量初始化 p = 1,之后从9至1循环9次,根据上述公式反推为 p = (p+1) * 2 可得第1天还没吃之前的桃子数量。for循环中的print()语句是为了验证推算过程而增加的。代码如下: ''' p=1 for i in range(9,0,-1): # p=(p+1)<<1 p=(p+1)*2 print('第%s天吃之前还有%s个桃子' % (i, p)) print('第1天共摘了%s个桃子' % p)
975a4e47959aeb74b07098726cc8e240efb7d371
DarioCozzuto/list
/access list items.py
1,051
4.5625
5
#List items are indexed and you can access them by referring to the index number: thislist = ["apple", "banana", "cherry"] print(thislist[1]) #-1 refers to the last item, -2 refers to the second last item etc. thislist = ["apple", "banana", "cherry"] print(thislist[-1]) #This will return the items from position 2 to 5. #Remember that the first item is position 0, #and note that the item in position 5 is NOT included thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"] print(thislist[2:5]) #This example returns the items from the beginning to, but NOT including, "kiwi": thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"] print(thislist[:4]) #This example returns the items from "cherry" to the end: thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"] print(thislist[2:]) #Check if "apple" is present in the list: thislist = ["apple", "banana", "cherry"] if "apple" in thislist: print("Yes, 'apple' is in the fruits list")
6c27dc894628f6de885d3521fdb7a5c45fb83eac
Programmer-Admin/binarysearch-editorials
/Largest Tree Sum Path.py
985
3.984375
4
""" Largest Tree Sum Path For each node, we can check whats the path with the greatest sum that goes through it by checking the max value of the following possibilites: - The path starting at the node (if children are negative), - The path coming from the left child, - The path coming from the right child, - The path coming from one children, and going down in the next. Then, the maximum path coming out of the node can either come from the left, the right or start at the node. """ # class Tree: # def __init__(self, val, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def solve(self, root): mx=0 def dfs(node): nonlocal mx if not node: return 0 l=dfs(node.left) r=dfs(node.right) mx=max(mx,l+node.val, r+node.val, l+r+node.val) return max(l+node.val,r+node.val,node.val) dfs(root) return mx
7743c91823ffdbf069e86478bd5754d325a0fabc
MinhKMA/ghichep-python
/exercises/Ex1,2_Chapter3-.py
862
3.890625
4
#Exercise 1: Rewrite your pay computation to give the employee 1.5 times the hourly rate for hours worked above 40 hours. #Exercise 2: Rewrite your pay program using try and except so that your program handles non-numeric input gracefully by printing a message and exiting the program. ==================================================================== while True: try: hour = float(input('Enter Hours:')) rate = float(input('Enter Rate:')) break except: print('Vui long nhap mot so') while hour < 0: print('vui long nhap so duong') hour = float(input('Enter Hours:')) break while rate < 0: print('vui long nhap so duong') rate = float(input('Enter Rate:')) break if hour > 40: x = (hour - 40) * rate * 1.5 + 40 * rate print ('pay:',x) else: x = hour * rate print ('pay:',x)
d30102e793c3d74d08c5ef1f1bc7d4f583945252
NasirOrosco/Python
/Comments/CommentsDebug.py
561
4.28125
4
''' Created on Dec 4, 2020 @author: NasirOrosco ''' ''' The goal of this function is to calculate the volume of an object, when the user inputs height, width, and depth. The function should print the sentence plus the volume and return the volume.''' def volumeCalculator(height, width, depth): area = height * width volume = depth * area sentence = "The volume of this object is: " #This prints out the sentence with the calculated volume. print(sentence + volume) return volume #Leave the next line alone volumeCalculator(5, 5, 5)
a174a379279da459d9e82d3429303ab193b86024
karanjhand/Catch_The_Thief
/flappybird/swap.py
137
3.796875
4
def swap(a,b): tmp = a print(a) print(b) print(tmp) a = b print(a) print(b) print(tmp) b = tmp print(a) print(b) print(tmp)
5e1517280f26db60b40402416d7ec4d5c3f35cf5
willian8000/uri-online-judge
/Problems/1040.py
720
3.5625
4
import math a, b, c, d = map(float, input("").split(" ")) media = round((a * 0.2) + (b * 0.3) + (c * 0.4) + (d * 0.1), 2) def truncate(f): return math.floor(f * 10 ** 1) / 10 ** 1 if media >= 7.0: print("Media: {0}".format(truncate(media))) print("Aluno aprovado.") elif 5 <= media < 7.0: print("Media: {0}".format(truncate(media))) print("Aluno em exame.") e = float(input()) print("Nota do exame: {0}".format(e)) media = (media + e) / 2.0 if media >= 5.0: print("Aluno aprovado.") else: print("Aluno reprovado.") print("Media final: {0}".format(truncate(media))) else: print("Media: {0}".format(truncate(media))) print("Aluno reprovado.")
22dc3e63b45d093f5b8678a6ea42d581e2fde85c
azulus/interviewprep
/solutions/algorithms/algorithm_knuth_shuffle.py
1,373
3.90625
4
import random # Class which maintains a shuffled and unshuffled list of chars class Shuffler: def __init__(self): print "initializing", self self._shuffled = [] self._unshuffled = [] # add a character to the shuffler def addChar(self, char): self._unshuffled.append(char) charLen = len(self._shuffled) shuffleIdx = random.randint(0, charLen) if (shuffleIdx == charLen): self._shuffled.append(char) else: self._shuffled.append(self._shuffled[shuffleIdx]) self._shuffled[shuffleIdx] = char # get the unshuffled version of the string def getUnshuffledString(self): return "".join(self._unshuffled) # get the shuffled version of the string def getShuffledString(self): return "".join(self._shuffled) inputStr = "abcdefghijklmnopqrstuvwxyz" shuffler = Shuffler() for char in inputStr: shuffler.addChar(char) shuffled = shuffler.getShuffledString() unshuffled = shuffler.getUnshuffledString() # compare the strings allFound = True for char1 in inputStr: found = False for char2 in unshuffled: if (char1 == char2): found = True if (found == False): allFound = False if (allFound == False): print "ALL CHARACTERS WERE NOT FOUND" else: print "UNSHUFFLED:", shuffler.getUnshuffledString() print "SHUFFLED:", shuffler.getShuffledString() print "ALL CHARACTERS WERE FOUND"
dbb6df55149a5c5498ca95a6335b4879a9e26e91
sctu/sctu-ds-2019
/1806101061李劲潮/day20190409/stack.py
221
3.96875
4
#定义栈 stack = [] #push stack.append(1) stack.append(2) stack.append(3) for i in range(1,11): stack.append(i) #pop print(stack.pop()) #pop一直到栈不为空 while len(stack) is not 0: print(stack.pop())
2d983a00af8e4f9a69c1b4a82a44a4cf04dd0845
eggeggss/BigData
/ch04/19for6-exam99No4.py
203
3.796875
4
#!/usr/bin/env # -*- coding:utf-8 -*- for x in range(1,10): for y in range(1,10): if x==4 or y==4: print("") else: print(" %d*%d=%d" % ( x,y,x*y)) print("end")
07a2788df754316a37eb4f914c4eec7417310e49
toddaulwurm/extras
/selection_sort.py
274
3.859375
4
def selectionSort(list): for i in range(0, len(list)): min = i for j in range(i+1, len(list)): if list[min] > list[j]: min=j list[i], list[min] = list[min], list[i] print(list) selectionSort([1,3,4,2,5,8,7,6,9])
e89c38149f147786647bccc4ffff4948664569e8
Aasthaengg/IBMdataset
/Python_codes/p04033/s927676383.py
311
3.546875
4
a,b = map(int,input().split()) if a > 0: print("Positive") exit(0) if (a == 0 or b == 0) or (a < 0 and b > 0): print("Zero") exit(0) # only negative a,b cases left from this point on if (a == b): print("Negative") exit(0) if (a - b) % 2 == 1: print("Positive") else: print("Negative")
72a8f8cf816b6702816bb86c24104ee5941fc19a
yuchien302/LeetCode
/leetcode257.py
932
3.828125
4
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def binaryTreePathsHelper(self, root, s): """ :type root: TreeNode :rtype: List[str] """ ans = [] if root.left: ans += self.binaryTreePathsHelper(root.left, s + "->" + str(root.left.val)) if root.right: ans += self.binaryTreePathsHelper(root.right, s + "->" + str(root.right.val)) if root.left is None and root.right is None: ans = [s] return ans def binaryTreePaths(self, root): """ :type root: TreeNode :rtype: List[str] """ if root is None: return [] return self.binaryTreePathsHelper(root, str(root.val))
a16ff0d97b2f854d34c9434476d9142710734596
sashaobucina/interview_prep
/python/hard/median_of_two_sorted_arrays.py
881
4.03125
4
""" There are two sorted arrays nums1 and nums2 of size m and n respectively. Find the median of the two sorted arrays. NOTE: This solution is in O(n) time and is not optimized """ def findMedianSortedArraysBad(nums1: list, nums2: list) -> float: nums3 = [] i, j, m, n = 0, 0, len(nums1), len(nums2) while i < m and j < n: if nums1[i] < nums2[j]: nums3.append(nums1[i]) i += 1 else: nums3.append(nums2[j]) j += 1 while i < m: nums3.append(nums1[i]) i += 1 while j < n: nums3.append(nums2[j]) j += 1 totalLen = len(nums3) if totalLen % 2 != 0: return float(nums3[totalLen // 2]) else: return (nums3[totalLen // 2 - 1] + nums3[totalLen // 2]) / 2 if __name__ == "__main__": nums1, nums2 = [1, 3, 5, 8, 9, 10], [2, 4, 6, 7, 11, 14] print(findMedianSortedArraysBad(nums1, nums2)) # expected value - 6.5