blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
c5d090dc7cff09586213ae05f2368df0bdaa4167
b1ueskydragon/PythonGround
/dailyOne/P154/stack_with_heapq.py
1,084
4.125
4
""" Implement a stack API using ONLY a heap. most recently := largest """ from time import time import heapq class Stack: def __init__(self): self.phq = PriorityHeapq() def push(self, item): """ adds an element to the stack. :param item: """ self.phq.push(item, time()) def pop(self): """ removes and returns the most recently added element. """ if not self.phq.heap: raise IndexError('nothing on the stack') return self.phq.pop() class PriorityHeapq: """ Impl a `Heap` with making value a pair (Tuple). """ def __init__(self): self.heap = [] def push(self, item, priority): """ adds a new key to the heap. :param item: :param priority: """ heapq.heappush(self.heap, (-priority, item)) # Tuple def pop(self): """ removes and returns the max value of the heap. :return: """ _, item = heapq.heappop(self.heap) # Tuple return item
22a6d280e0c85f4982576a3c0acbf736d9c2c068
gspindev/Competitive-Coding
/src/geeksforgeeks/arrays/easy/CountTheElements.py
721
3.515625
4
def get_greatest_smallest(a, low, high, target): result = -1 while low <= high: mid = (low + high) // 2 if a[mid] <= target: result = mid low = mid + 1 else: high = mid - 1 return result def get_count(a, target): result = get_greatest_smallest(a, 0, len(a) - 1, target) + 1 return result def main(): t = int(input()) while t > 0: n = int(input()) a = [int(i) for i in input().split()] b = [int(i) for i in input().split()] b.sort() q = int(input()) while q > 0: target = int(input()) print(get_count(b, a[target])) q -= 1 t -= 1 main()
fcddb8272a1250dbaef6c6b7900624caacfb9dc0
B05611003/108-2_python_hw
/3021.py
540
3.8125
4
score = int(input()) if score not in range(1,101): print("input out of range") elif score >= 90: print("%.1f\n%s"%(4.3,'A+')) elif score >= 85: print("%.1f\n%s"%(4.0,'A')) elif score >= 80: print("%.1f\n%s"%(3.7,'A-')) elif score >= 77: print("%.1f\n%s"%(3.3,'B+')) elif score >= 73: print("%.1f\n%s"%(3.0,'B')) elif score >= 70: print("%.1f\n%s"%(2.7,'B-')) elif score >= 67: print("%.1f\n%s"%(2.3,'C+')) elif score >= 63: print("%.1f\n%s"%(2.0,'C')) elif score >= 60: print("%.1f\n%s"%(1.7,'C-')) else: print("%d\n%s"%(0,'F'))
5e48797954bca77ba3b676c86083ec772ce8b576
ITouray/python-prep
/pluralSight/rock_paper_scissors.py
434
3.984375
4
player1 = input("do you want rock, paper, or scissors?\n ") player2 = input("do you want rock, paper, or scissors?\n ") if player1 == player2: print("there is a tie") elif player1 == 'paper' and player2 == 'rock': print("player 1 wins") elif player1 == 'rock' and player2 == 'scissors': print("player 1 wins") elif player1 == 'scissors' and player2 == 'paper': print("player 1 wins") else: print("player 2 wins")
b64304f13cade823ab76b9f52bfb5ff1c4b0a74a
SeA-xiAoD/LearningPython
/LeetCode/204/CountPrimes.py
474
3.71875
4
from math import sqrt class Solution(object): def countPrimes(self, n): """ :type n: int :rtype: int """ if n <= 2: return 0 res = [True] * n res[0] = res[1] = False for i in range(2, int(sqrt(n)) + 1): if res[i] == True: for j in range(2, (n-1)//i+1): # start from 2 to avoid primes res[i*j] = False return sum(res)
2d9933403686d0d1407d6655a196033c5eeb0f3c
Steven-Eardley/pibot_motor
/Moves.py
2,279
4.4375
4
"""Some primitive movement definitions""" import Robot def go_straight(speed=50, distance=0): """ Travel forwards or backwards in a straight line. :param speed: Speed to travel, as % of maximum :param distance: Distance to travel, in millimetres. +ve for forwards, -ve for backwards :return: 0 for success; 1 for failure """ power = speed_to_power(speed) r = Robot.get_robot() r.ctl.SetMotor1(power + Robot.R_OFFSET) r.ctl.SetMotor2(power) print "straight:\t{0}mm at {1}% speed".format(distance, speed) def rotate(speed=50, degrees=0): """ Rotate the bot while stationary. :param degrees: Number of degrees to rotate, +ve for clockwise, -ve for anticlockwise :return: 0 for success; 1 for failure """ r = Robot.get_robot() print "rotate:\t{0} deg at {1}% speed".format(degrees, speed) def rotate_min(speed=50, heading=0): """ Slightly smarter stationary rotate method which chooses its own direction of rotation :param heading: New heading to point towards (0-360) :return: 0 for success; 1 for failure """ r = Robot.get_robot() heading = heading % 360 if 180 - heading >= 0: rotate(speed, heading) else: rotate(speed, -(360 - heading)) def stop(): """ Stop the robot :return: 0 for success; 1 for failure """ r = Robot.get_robot() r.stop() ################################## # Helper functions for movement # ################################## def speed_to_power(speed_percentage): """Get the motor power setting for a given speed""" return Robot.MAX_POWER * (speed_percentage / 100.0) if __name__ == "__main__": """ Do a quick test if this file is executed """ control_sequence = [ lambda: go_straight(distance=10), lambda: go_straight(distance=-10), lambda: rotate(degrees=90), lambda: rotate(degrees=-90), lambda: rotate_min(heading=180), lambda: rotate_min(heading=180), lambda: rotate_min(heading=315), lambda: rotate_min(heading=45), lambda: rotate_min(heading=60), lambda: rotate_min(heading=300) ] test_robot = Robot.get_robot(init_commands=control_sequence) test_robot.cs.exec_stack(wait_time=1)
0824ef7922a450f50423e06b5427b7c8e5dc788e
Ragmthy/fuzzy-garbanzo
/block_generator.py
882
3.53125
4
# -*- coding: utf-8 -*- """ Created on Fri Aug 10 17:13:16 2018 @author: ragini.gurumurthy """ #Code a blockchain in Python yo import datetime import hashlib class Block: def __init__(self, previous_block_hash,data,timestamp): self.previous_block_hash = previous_block_hash self.data = data self.timestamp = timestamp self.hash = self.get_hash() @staticmethod def genesis_block(): return Block("0", "Here is the initial data string", datetime.datetime.now()) def get_hash(self): header_bin = (str(self.previous_block_hash)+ str(self.data)+ str(self.timestamp)) inner_hash = hashlib.sha256(header_bin.encode()).hexdigest().encode() outer_hash = hashlib.sha256(inner_hash).hexdigest() return outer_hash
6cf9545f702d0e77175143e40edc7739262109e4
nmpluta/Python
/Exam/l4.py
388
3.53125
4
# -*- coding: utf-8 -*- # L4 (5) policzy liczbę łańcuchów w liście, dłuższych niż 5, w których pierwszy i ostatni znak są takie same def l4(lst): count = 0 # test = [] for e in lst: if len(e) > 5 and e[0] == e[-1]: count += 1 # test.append(e) # print(test) return count print(l4(["tralalla", "xsdx", "teeeest", "aaaaaa"]))
a2f26fb68c98d438d43b29cd5a94fe7e6b198028
aomisai/progm-practica
/main.py
411
3.796875
4
print("hello world") # Variables: guardan data #Tipos de variable # String: texto nombre = "8" print(nombre) # integer: numero entero # double: numero con decimal fechaNacimiento = 1994 fechaActual = 2020 edadActual = fechaActual - fechaNacimiento print(edadActual) # matematicas # % modulus = resto de la division nombre1 = "Gustavo" nombre2 = "Adolfo" print(nombre1 + str(fechaActual))
ef31e06bf861990b01865d8284ad7948842531e5
nmotwani0/python
/types_of_methods.py
675
3.796875
4
class Student: School = "SHMIT" def __init__(self,m1,m2,m3): self.m1 = m1 self.m2 = m2 self.m3 = m3 def avg(self): return (self.m1+self.m2+self.m3)/3 #mutator method def set_m1(self,m1): self.m1 =m1 #accessor method def get_m1(self): return self.m1 @classmethod def schoolInfo(cls): return cls.School @staticmethod def info(): print("hello this is class of python") s1 = Student(23,56,86) s2 = Student(28,87,53) print(s1.avg()) print(s2.avg()) s1.set_m1(100) print("New m1",s1.get_m1()) print("New avg",s1.avg()) print(Student.schoolInfo()) Student.info()
163515d89cdeeaefc6e9aa387cc60867d816a32d
diljasigurdar/dilja
/Assignments/Assignment.6/6.string_methods.py
600
4.15625
4
name = input("Input a name: ") first, second = name.split(", ") firstUpper = first[0].upper() firstFinal = firstUpper + first[1:] second = second.upper() second = second[0] transformed = second + ". " + firstFinal print(transformed) #Given a name in the format #lastname, firstname #where there is exactly one comma and exactly one space, transform the name into the format #first_initial. lastname #where #* first_inital and lastname are both capitalized #* there is exactly one period and space following the first_initial #For example, given s='ghandi, mahatma' #the output will be #M. Ghandi
b2dc2f16530b5638293ed032a76fc6d23e619c67
vijaym123/Materialised-View
/polar/lakes.py
19,045
3.953125
4
import numpy as np import pylab import itertools import math from matplotlib import pyplot as plt import timeit class PolygonsTouching(Exception): """ This exception is triggered when two polygons touch at one point. This is for internal use only and will be caught before returning. """ def __init__(self, x=0, y=0): self.x, self.y = x, y def __str__(self): return 'The tested polygons at least touch each other at (%f,%f)'\ % (self.x, self.y) def shift(self, dx, dy): self.x += dx self.y += dy def pair_overlapping(polygon1, polygon2, digits=None): """ Find out if polygons are overlapping or touching. The function makes use of the quadrant method to find out if a point is inside a given polygon. polygon1, polygon2 -- Two arrays of [x,y] pairs where the last and the first pair is the same, because the polygon has to be closed. digits -- The number of digits relevant for the decision between separate and touching or touching and overlapping Returns 0 if the given polygons are neither overlapping nor touching, returns 1 if they are not overlapping, but touching and returns 2 if they are overlapping """ def calc_walk_summand(r1, r2, digits=None): """ Calculates the summand along one edge depending on axis crossings. Follows the edge between two points and checks if one or both axes are being crossed. If They are crossed in clockwise sense, it returns +1 otherwise -1. Going through the origin raises the PolygonsTouching exception. Returns one of -2, -1, 0, +1, +2 or raises PolygonsTouching """ x, y = 0, 1 # indices for better readability summand = 0 # the return value tx, ty = None, None # on division by zero, set parameters to None if r1[x] != r2[x]: ty = r1[x] / (r1[x] - r2[x]) # where it crosses the y axis if r1[y] != r2[y]: tx = r1[y] / (r1[y] - r2[y]) # where it crosses the x axis if tx == None: tx = ty if ty == None: ty = tx # if tx == ty and tx==None: # print "R1", r1 # print "R2", r2 # tx = 0 # ty = 0 rsign = pylab.sign if digits != None: rsign = lambda x: pylab.sign(round(x, digits)) sign_x = rsign(r1[x] + tx * (r2[x] - r1[x])) sign_y = rsign(r1[y] + ty * (r2[y] - r1[y])) if (tx >= 0) and (tx < 1): if (sign_x == 0) and (sign_y == 0): raise PolygonsTouching() summand += sign_x * pylab.sign(r2[y] - r1[y]) if (ty >= 0) and (ty < 1): if (sign_x == 0) and (sign_y == 0): raise PolygonsTouching() summand += sign_y * pylab.sign(r1[x] - r2[x]) return summand def current_and_next(iterable): """ Returns an iterator for each element and its following element. """ iterator = iter(iterable) item = iterator.next() for next in iterator: yield (item, next) item = next def point_in_polygon(xy, xyarray, digits=None): """ Checks if a point lies inside a polygon using the quadrant method. This moves the given point to the origin and shifts the polygon accordingly. Then for each edge of the polygon, calc_walk_summand is called. If the sum of all returned values from these calls is +4 or -4, the point lies indeed inside the polygon. Otherwise, if a PolygonsTouching exception has been caught, the point lies on ond of the edges of the polygon. Returns the number of nodes of the polygon, if the point lies inside, otherwise 1 if the point lies on the polygon and if not, 0. """ moved = xyarray - \ xy # move currently checked point to the origin (0,0) touching = False # this is used only if no overlap is found walk_sum = 0 for cnxy in current_and_next(moved): try: walk_sum += calc_walk_summand(cnxy[0], cnxy[1], digits) except PolygonsTouching, (e): e.shift(*xy) touching = True if (abs(walk_sum) == 4): return len(xyarray) elif touching: return 1 else: return 0 def polygons_overlapping(p1, p2, digits=None): """ Checks if one of the nodes of p1 lies inside p2. This repeatedly calls point_in_polygon for each point of polygon p1 and immediately returns if it is the case, because then the polygons are obviously overlapping. Returns 2 for overlapping polygons, 1 for touching polygons and 0 otherwise. """ degree_of_contact = 0 xyarrays = [p1, p2] for xy in xyarrays[0]: degree_of_contact += point_in_polygon(xy, xyarrays[1], digits) if degree_of_contact >= len(xyarrays[1]): return 2 if degree_of_contact > 0: return 1 else: return 0 way1 = polygons_overlapping(polygon1, polygon2, digits) way2 = 0 # Only if the polygons are not already found to be overlapping if way1 < 2: way2 = polygons_overlapping(polygon2, polygon1, digits) return max(way1, way2) def collection_overlapping_serial(polygons, digits=None): """ Similar to the collection_overlapping function, but forces serial processing. """ result = [] pickle_polygons = [p.get_xy() for p in polygons] for i in xrange(len(polygons)): for j in xrange(i + 1, len(polygons)): result.append((i, j, pair_overlapping( pickle_polygons[i], pickle_polygons[j], digits))) return result def __cop_bigger_job(polygons, index, digits=None): """ This is a helper to efficiently distribute workload among processors. """ result = [] for j in xrange(index + 1, len(polygons)): result.append((index, j, pair_overlapping(polygons[index], polygons[j], digits))) return result def collection_overlapping_parallel(polygons, digits=None, ncpus='autodetect'): """ Like collection_overlapping, but forces parallel processing. This function crashes if Parallel Python is not found on the system. """ import pp ppservers = () job_server = pp.Server(ncpus, ppservers=ppservers) pickle_polygons = [p.get_xy() for p in polygons] jobs = [] for i in xrange(len(polygons)): job = job_server.submit(__cop_bigger_job, (pickle_polygons, i, digits, ), (pair_overlapping, PolygonsTouching, ), ("pylab", )) jobs.append(job) result = [] for job in jobs: result += job() # job_server.print_stats() return result def collection_overlapping(polygons, digits=None): """ Look for pair-wise overlaps in a given list of polygons. The function makes use of the quadrant method to find out if a point is inside a given polygon. It invokes the pair_overlapping function for each combination and produces and array of index pairs of these combinations together with the overlap number of that pair. The overlap number is 0 for no overlap, 1 for touching and 2 for overlapping polygons. This function automatically selects between a serial and a parallel implementation of the search depending on whether Parallel Python is installed and can be imported or not. polygons -- A list of arrays of [x,y] pairs where the last and the first pair of each array in the list is the same, because the polygons have to be closed. digits -- The number of digits relevant for the decision between separate and touching or touching and overlapping polygons. Returns a list of 3-tuples """ try: import pp # try if parallel python is installed except ImportError: return collection_overlapping_serial(polygons, digits) else: return collection_overlapping_parallel(polygons, digits) class Node(): ROOT = 0 BRANCH = 1 LEAF = 2 #_______________________________________________________ # In the case of a root node "parent" will be None. The # "rect" lists the minx,minz,maxx,maxz of the rectangle # represented by the node. def __init__(self, parent, lakeids, rect): global countLeaf self.parent = parent self.rect = rect self.lakes = lakeids self.children = [None, None, None, None] if parent == None: self.depth = 0 else: self.depth = parent.depth + 1 if self.parent == None: self.type = Node.ROOT if len(self.lakes) == 1: self.type = Node.LEAF self.children = None countLeaf+=1 #print (self.rect[0], self.rect[1]), self.rect[2]-self.rect[0], self.rect[3]-self.rect[1] drawRect = plt.Rectangle((self.rect[0], self.rect[1]), self.rect[2]-self.rect[0], self.rect[3]-self.rect[1], ec='#000000', color='red') ax.add_patch(drawRect) #print "Leaf number :", countLeaf elif len(self.lakes) == 0: self.type = Node.LEAF self.children = None drawRect = plt.Rectangle((self.rect[0], self.rect[1]), self.rect[2]-self.rect[0], self.rect[3]-self.rect[1], ec='#000000', color='white') ax.add_patch(drawRect) else: self.type = Node.BRANCH drawRect = plt.Rectangle((self.rect[0], self.rect[1]), self.rect[2]-self.rect[0], self.rect[3]-self.rect[1], ec='#000000', color='white') ax.add_patch(drawRect) self.constructQuadtree() #_______________________________________________________ # Recursively subdivides a rectangle. Division occurs # ONLY if the rectangle spans a "feature of interest". def __createQuadrants__(self): quadrants = dict() quadrants[0] = np.array([[self.rect[0], self.rect[1]], [(self.rect[2] + self.rect[0]) / 2,self.rect[1]], [(self.rect[2] + self.rect[0]) / 2, (self.rect[3] + self.rect[1]) / 2], [self.rect[0],(self.rect[3] + self.rect[1]) / 2], [self.rect[0], self.rect[1]]]) quadrants[1] = np.array([[(self.rect[2] + self.rect[0]) / 2, self.rect[1]], [self.rect[2],self.rect[1]], [self.rect[2], (self.rect[3] + self.rect[1]) / 2], [(self.rect[2] + self.rect[0]) / 2,(self.rect[3] + self.rect[1]) / 2], [(self.rect[2] + self.rect[0]) / 2, self.rect[1]]]) quadrants[2] = np.array([[(self.rect[2] + self.rect[0]) / 2, (self.rect[3] + self.rect[1]) / 2], [self.rect[2],(self.rect[3] + self.rect[1]) / 2], [self.rect[2], self.rect[3]], [(self.rect[2] + self.rect[0]) / 2,self.rect[3]], [(self.rect[2] + self.rect[0]) / 2, (self.rect[3] + self.rect[1]) / 2]]) quadrants[3] = np.array([[self.rect[0], (self.rect[3] + self.rect[1]) / 2], [(self.rect[2] + self.rect[0]) / 2, (self.rect[3] + self.rect[1]) / 2], [(self.rect[2] + self.rect[0]) / 2, self.rect[3]], [self.rect[0],self.rect[3]], [self.rect[0], (self.rect[3] + self.rect[1]) / 2]]) return quadrants def quardToRect(self, quadrant): return [quadrant[0][0], quadrant[0][1], quadrant[2][0], quadrant[2][1]] def constructQuadtree(self): quadrants = self.__createQuadrants__() # print "Self Quad :", self.rect # if self.rect[2]-self.rect[0] != self.rect[3] - self.rect[1]: # print "quad 0", quadrants[0] # print "quad 1", quadrants[1] # print "quad 2", quadrants[2] # print "quad 3", quadrants[3] lakesQuad = dict() lakesQuad[0] = [] lakesQuad[1] = [] lakesQuad[2] = [] lakesQuad[3] = [] for lakeid in self.lakes: try : if pair_overlapping(lakesDict[lakeid], quadrants[0]) > 0: lakesQuad[0].append(lakeid) if pair_overlapping(lakesDict[lakeid], quadrants[1]) > 0: lakesQuad[1].append(lakeid) if pair_overlapping(lakesDict[lakeid], quadrants[2]) > 0: lakesQuad[2].append(lakeid) if pair_overlapping(lakesDict[lakeid], quadrants[3]) > 0: lakesQuad[3].append(lakeid) except TypeError : print lakeid pass print self.depth #print self.quardToRect(quadrants[0]) self.children[0] = Node(self,lakesQuad[0],self.quardToRect(quadrants[0])) self.children[1] = Node(self,lakesQuad[1],self.quardToRect(quadrants[1])) self.children[2] = Node(self,lakesQuad[2],self.quardToRect(quadrants[2])) self.children[3] = Node(self,lakesQuad[3],self.quardToRect(quadrants[3])) def lakesBoundingRectangle(lakes): values = dict() values["max-x"] = 0 values["max-y"] = 0 values["min-x"] = None values["min-y"] = None for lid in lakes: for v in lakes[lid]: if v[0] > values["max-x"]: values["max-x"] = v[0] if v[1] > values["max-y"]: values["max-y"] = v[1] if values["min-x"] == None or v[0] < values["min-x"]: values["min-x"] = v[0] if values["min-y"] == None or v[1] < values["min-y"]: values["min-y"] = v[1] values["max-x"] = 2 ** (math.ceil(math.log(values["max-x"], 2))) values["max-y"] = 2 ** (math.ceil(math.log(values["max-y"], 2))) values["min-x"] = 0 values["min-y"] = 0 return values def readLakes(filename): lines = [line.strip() for line in open(filename)] lakes = dict() for i in lines: lake_id = int(i.split(" ")[0]) data = [int(i) for i in i.split(" ")[1].split(" ")] lakes[lake_id] = zip(data[::2], data[1::2]) lakes[lake_id] = np.array([list(cartesianToPolar(pts)) for pts in lakes[lake_id]]) return lakes def rectToQuad(rect): return np.array([[rect[0],rect[1]], [rect[2],rect[1]], [rect[2], rect[3]], [rect[0],rect[3]], [rect[0],rect[1]]]) def samplingLakes(node, region): nodePolygon = rectToQuad(node.rect) lakeSet = set() if pair_overlapping(nodePolygon,region): if node.type == Node.LEAF: try: return set([node.lakes[0]]) except IndexError: return set() else: lakeSet = lakeSet.union(samplingLakes(node.children[0],region)) lakeSet = lakeSet.union(samplingLakes(node.children[1],region)) lakeSet = lakeSet.union(samplingLakes(node.children[2],region)) lakeSet = lakeSet.union(samplingLakes(node.children[3],region)) return lakeSet else: return set() def queryLakes(node,region,regionC): lakes = samplingLakes(node,region) output = set() for lakeid in lakes: try : if pair_overlapping(lakesDict[lakeid],region): output.add(lakeid) except : pass #output = finalSearch(output,regionC) return output def bruteForce(region, regionC): output = set() for lakeid in lakesDict: try : if pair_overlapping(lakesDict[lakeid],region): output.add(lakeid) except : pass #output = finalSearch(output,regionC) return output def wrapper(func, *args, **kwargs): def wrapped(): return func(*args, **kwargs) return wrapped def timeSearch(root,region, regionC, times=100): wrapped = wrapper(queryLakes, root, region, regionC) print "time for Quad-Tree search : ", timeit.timeit(wrapped, number=times) wrapped = wrapper(bruteForce, region, regionC) print "time for Brute force search : ", timeit.timeit(wrapped, number=times) return None def cartesianToPolar(pts) : r = math.sqrt(pts[0]**2+pts[1]**2) try : theta = math.atan(pts[1]*1.0/pts[0]) except : print "hi" theta = math.pi/2 return (r,theta) def cartesianToPolarSearch(rect): minR = math.sqrt(rect[0]**2+rect[1]**2) maxR = math.sqrt(rect[2]**2+rect[3]**2) minTheta = math.atan(rect[1]*1.0/rect[2]) maxTheta = math.atan(rect[3]*1.0/rect[0]) return [minR, minTheta, maxR, maxTheta] def readLakesC(filename): lines = [line.strip() for line in open(filename)] lakes = dict() for i in lines: lake_id = int(i.split(" ")[0]) data = [int(i) for i in i.split(" ")[1].split(" ")] lakes[lake_id] = zip(data[::2], data[1::2]) lakes[lake_id] = np.array([list(pts) for pts in lakes[lake_id]]) return lakes def finalSearch(lakes, region): result = [] for lake in lakes: try : if pair_overlapping(lakesDictC[lake],region): result.append(lake) except : print lake pass return result if __name__ == "__main__": filename = "./MN_LAKES_400.txt" global ax,fig global lakesDict, countLeaf, lakesDictC lakesDict = dict() lakesDict = readLakes(filename) lakesDictC = dict() lakesDictC = readLakesC(filename) for lakes in [11354, 2604, 2524, 2902, 11234, 7480, 7798]: try : del(lakesDict[lakes]) del(lakesDictC[lakes]) except : pass values = lakesBoundingRectangle(lakesDict) rect = [values["min-x"], values["min-y"], values["max-x"], values["max-y"]] fig = plt.figure() ax = fig.add_subplot(1,1,1) ax.axis((values["min-x"], values["max-x"], values["min-y"], values["max-y"])) fig.suptitle('Quad-Tree Example', fontsize=18) countLeaf=0 root = Node(None, lakesDict.keys(), rect) #plt.show() minPt = [200000, 200000] maxPt = [400000, 400000] region = rectToQuad(cartesianToPolarSearch([minPt[0],minPt[1],maxPt[0],maxPt[1]])) lakes = queryLakes(root, region, rectToQuad([minPt[0],minPt[1],maxPt[0],maxPt[1]])) print "QuadTree search: ", lakes lakes1 = bruteForce(region, rectToQuad([minPt[0],minPt[1],maxPt[0],maxPt[1]])) print "Brute force search ", lakes1 timeSearch(root, region, rectToQuad([minPt[0],minPt[1],maxPt[0],maxPt[1]]))
8f1a26c38bf0d3b47cc4bf0d1018b7344c6e139c
zenmeder/leetcode
/94.py
579
4.0625
4
#!/usr/local/bin/ python3 # -*- coding:utf-8 -*- # __author__ = "zenmeder" # 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 inorderTraversal(self, root): res, stack = [], [] while True: while root: stack.append(root) root = root.left if not stack: return res node = stack.pop() res.append(node.val) root = node.right a = TreeNode(1) b = TreeNode(2) c = TreeNode(3) a.right = b b.left = c print(Solution().inorderTraversal(a))
7bf55972f4a9ce84dc80396c16817035c1f04c52
LilianBob/__python_fundamentals
/for_loop_basicII.py
4,693
4.5
4
# Biggie Size - Given a list, write a function that changes all positive numbers in the list to "big". def biggie_size(list): for i in range (0, len(list), 1): if list [i]>0: list[i] = "big" return list print (biggie_size([-1, 3, 5, -5])) # Example: biggie_size([-1, 3, 5, -5] # ) returns that same list, but whose values are now [-1, "big", "big", -5] # Count Positives - Given a list of numbers, create a function to replace the last value with the number of positive values. (Note that zero is not considered to be a positive number). # Example: count_positives([-1,1,1,1]) changes the original list to [-1,1,1,3] and returns it # Example: count_positives([1,6,-4,-2,-7,-2]) changes the list to [1,6,-4,-2,-7,2] and returns it def count_positives (list): count =0 for i in range (len(list)): if list[i]>0: count += 1 list [len(list)-1] = count return list print(count_positives([1, 6, -4, -2, -7, -2])) # Sum Total - Create a function that takes a list and returns the sum of all the values in the array. # Example: sum_total([1,2,3,4]) should return 10 # Example: sum_total([6,3,-2]) should return 7 def sum_total (list): sum=0 for i in range (len(list)): sum+= list[i] return sum print(sum_total([6, 3, -2])) # Average - Create a function that takes a list and returns the average of all the values. # Example: average([1,2,3,4]) should return 2.5 def average (list): sum=0 avg=None for i in range (len(list)): sum+= list[i] avg= sum/len(list) return avg print (average([1, 2, 3, 4])) # Length - Create a function that takes a list and returns the length of the list. # Example: length([37,2,1,-9]) should return 4 # Example: length([]) should return 0 def length (list): return len(list) print (length([37, 2, 1, -9 ])) # Minimum - Create a function that takes a list of numbers and returns the minimum value in the list. If the list is empty, have the function return False. # Example: minimum([37,2,1,-9]) should return -9 # Example: minimum([]) should return False def minimum (list): if len(list)<=0: return False min = list[0] for num in range (len(list)): if list[num]< min: min = list[num] return min print (minimum([37, 2, 1, -9])) print (minimum([])) # Maximum - Create a function that takes a list and returns the maximum value in the array. If the list is empty, have the function return False. # Example: maximum([37,2,1,-9]) should return 37 # Example: maximum([]) should return False def maximum (list): if len(list)<=0: return False max = list[0] for num in range (len(list)): if list[num]> max: max = list[num] return max print (maximum ([37, 2, 1, -9])) print (maximum([])) # Ultimate Analysis - Create a function that takes a list and returns a dictionary that has the sumTotal, average, minimum, maximum and length of the list. # Example: ultimate_analysis([37,2,1,-9]) should return {'sumTotal': 31, 'average': 7.75, 'minimum': -9, 'maximum': 37, 'length': 4 } def ultimate_analysis (list): list_dict={'sumTotal': 0, 'average': None, 'minimum': list[0], 'maximum': list[0], 'length': len(list)} for i in range (len(list)): list_dict ['sumTotal'] += list[i] if list[i] < list_dict['minimum']: list_dict['minimum'] = list[i] if list[i] > list_dict['maximum']: list_dict['maximum'] = list[i] list_dict['length'] = len(list) list_dict['average'] = list_dict['sumTotal']/len(list) return list_dict print(ultimate_analysis([37, 2, 1, -9])) # Reverse List - Create a function that takes a list and return that list with values reversed. Do this without creating a second list. # (This challenge is known to appear during basic technical interviews.) # Example: reverse_list([37,2,1,-9]) should return [-9,1,2,37] # def reverse_list(list): # rlist= [] # for i in range (len(list)-1, -1, -1): # rlist.append(list[i]) # return rlist # print (reverse_list ([37, 2, 1, -9])) # def reverse_list(list): # half_len = len(list)//2 # for i in range (half_len): # list[i], list[len(list)-1-i] = list[len(list)-1-i], list[i] # return list # print (reverse_list ([37, 2, 1, -9])) def reverse_list(list): for i in range ((len(list))//2): temp = list [i] list[i] = list[(len(list)-1 -i)] list[(len(list)-1 -i)] = temp return list print (reverse_list([37, 2, 1, -9]))
6cb64b4621d97da5fffa6264e5a7da4c3ef84853
ideaqiwang/leetcode
/Array/118_PascalTriangle.py
1,196
4.0625
4
''' 118. Pascal's Triangle Given an integer numRows, return the first numRows of Pascal's triangle. In Pascal's triangle, each number is the sum of the two numbers directly above it as shown: 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 Example 1: Input: numRows = 5 Output: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]] Example 2: Input: numRows = 1 Output: [[1]] ''' class Solution: ''' Solution 1: Dynamic Programming: Use the previous row to calculate the next row. ''' def generate(self, numRows): triangles = [] for r in range(numRows): row = [1] * (r+1) for i in range(1, r): row[i] = triangles[-1][i-1] + triangles[-1][i] triangles.append(row) return triangles ''' Solution 2: DFS ''' def dfs(self, rowNum, triangles): if rowNum == 0: return self.dfs(rowNum-1, triangles) row = [1] * rowNum for i in range(1, rowNum-1): row[i] = triangles[-1][i-1] + triangles[-1][i] triangles.append(row) def generate2(self, numRows): triangles = [] self.dfs(numRows, triangles) return triangles
7be1e1c2cc80ba9f7e8debb213b8390f48f604d7
yuehongxia/lala
/0529/yanse.py
1,659
3.5
4
#coding=utf-8 # # 图像像素访问.通道分离与合并 # ''' #访问像素点,模拟带有模拟椒盐现象的图片 import cv2 import numpy as np def salt(img, n): for k in range(n): i = int(np.random.random() * img.shape[1]) j = int(np.random.random() * img.shape[0]) if img.ndim == 2: img[j,i] = 255 elif img.ndim == 3: img[j,i,0]= 255 img[j,i,1]= 255 img[j,i,2]= 255 return img if __name__ == '__main__': img = cv2.imread("test1.jpg") saltImage = salt(img, 1000) cv2.imshow("Salt", saltImage) cv2.waitKey(0) cv2.destroyAllWindows() ''' import cv2 import numpy as np img = cv2.imread("0601.jpg") #分离方法1:使用OpenCV自带的split函数 b, g, r = cv2.split(img) #分离方法2:通过访问cv2.split(img)数组来分离 #b = cv2.split(img)[0] #g = cv2.split(img)[1] #r = cv2.split(img)[2] ''' 分离方法3:直接操作NumPy数组来完成分离 注意:需要先要开辟一个相同大小的图片出来。这是由于numpy中数组的复制有些需要注意的地方 b = np.zeros((img.shape[0],img.shape[1]), dtype=img.dtype) g = np.zeros((img.shape[0],img.shape[1]), dtype=img.dtype) r = np.zeros((img.shape[0],img.shape[1]), dtype=img.dtype) b[:,:] = img[:,:,0] g[:,:] = img[:,:,1] r[:,:] = img[:,:,2] ''' cv2.imwrite("old/Blue.jpg", b) cv2.imwrite("old/Red.jpg", r) cv2.imwrite("old/Green.jpg", g) #合并RGB(b,g,r 顺序没写对,不会合成原图) merged = cv2.merge([b,g,r]) cv2.imshow("merged", merged) cv2.waitKey(0) cv2.destroyAllWindows()
3b953a1e5764d6914011e835300b22afb8be6a79
Emirates2008/Tarun_2008
/triangle.py
369
4.1875
4
print ("Please enter the sides of the triangle in numerical order") a = float(input("Enter side 1 of triangle.")) b = float(input("Enter side 2 of triangle.")) c = float(input("Enter side 3 of triangle.")) if (a == b == c): print ("The triangle is equalateral") elif (a != b != c): print ("The triangle is scalene") else: print ("the triangle is isoceles")
1f1ab016dab2ab8e63bd64d4b90e3b0c2ffc3762
Datriks/Python_Repo
/array-exercises-homework.py
2,896
3.53125
4
# -*- coding: utf-8 -*- """ Created on Wed Apr 15 08:06:32 2020 @author: Juvette """ #Data revenue = [14574.49, 7606.46, 8611.41, 9175.41, 8058.65, 8105.44, 11496.28, 9766.09, 10305.32, 14379.96, 10713.97, 15433.50] expenses = [12051.82, 5695.07, 12319.20, 12089.72, 8658.57, 840.20, 3285.73, 5821.12, 6976.93, 16618.61, 10054.37, 3803.96] #calculate Profit as a diference between revenue and expenses profit = list([]) for i in range(0, len(revenue)): profit.append(revenue[i]-expenses[i]) print(profit) #%% #Calculate Tax As 30% Of Profit And Round To 2 Decimal Points tax = [round(i*0.30,2) for i in profit] print(tax) #%% #Calculate profit ater tax profit_after_tax = list([]) for i in range(0, len(profit)): profit_after_tax.append(profit[i]-tax[i]) profit_after_tax = [round((i),2) for i in profit_after_tax] print(profit_after_tax) #%% #Calculate The Profit Margin As Profit After Tax Over Revenue #Round To 2 Decimal Points, Then Multiply By 100 To Get % profit_margin = list([]) for i in range (0, len(profit)): profit_margin.append(profit_after_tax[i] / revenue[i]) #round the profit_margin profit_margin = [round((i*100),2) for i in profit_margin] print(profit_margin) #%% #Calculate The Mean Profit After Tax For The 12 Months mean_pat = sum(profit_after_tax) / len(profit_after_tax) print(mean_pat) #%% #Find The Months With Above-Mean Profit After Tax good_months = list([]) for i in range(0, len(profit)): good_months.append(profit_after_tax[i] > mean_pat) print(good_months) #%% #Bad Months Are The Opposite Of Good Months! bad_months = list([]) for i in range(0, len(profit)): bad_months.append(not(good_months[i])) print(bad_months) #%% #The Best Month Is Where Profit After Tax Was Equal To The Maximum of Profit after tax best_month = list([]) for i in range(0, len(profit)): best_month.append(profit_after_tax[i] == max(profit_after_tax)) print(best_month) #%% #The Worst Month Is Where Profit After Tax Was Equal To The Minimum Profit after Tax worst_month = list([]) for i in range(0, len(profit)): worst_month.append(profit_after_tax[i] == min(profit_after_tax)) print(worst_month) #%% #Convert All Calculations To Units Of One Thousand Dollars revenue_1000 = [round(i/1000,2) for i in revenue] expenses_1000 = [round(i/1000,2) for i in expenses] profit_1000 = [round(i/1000,2) for i in profit] profit_after_tax_1000 = [round(i/1000,2) for i in profit_after_tax] #%% revenue_1000 = [int(i) for i in revenue_1000] expenses_1000 = [int(i) for i in expenses_1000] profit_1000 = [int(i) for i in profit_1000] profit_after_tax_1000 = [int(i) for i in profit_after_tax_1000] print(revenue_1000) print(expenses_1000) print(profit_1000) print(profit_after_tax_1000)
5fec2e2d78b2ba4c36fde1d3a763e29d11699ce9
SMU-UbiComp-Class/ICA1_Serial
/python_plot_animated.py
1,061
3.984375
4
#============================================ # plotting in real time example import time # for sleeping import random # for generating random data from matplotlib import pyplot as plt from collections import deque # create a queue of size N size_of_queue = 25 init_queue_value = -1 data = deque([init_queue_value] * size_of_queue) # setup the plot # show at 0:20 on the x axis and 0:10 on y axis ax = plt.axes(xlim=(0, 20), ylim=(0, 10)) line, = plt.plot(data) # get handle to the "line" that we use for updating the plot plt.ion() # interactive plots can do not block on "show" plt.show() # show the plot on the screen # do this until the queue is all filled in for i in range(0, len(data)): # get a random number # and add number to the queue data.appendleft(random.randint(1, 10)) data.pop() # pop the last number off to keep queue size the same line.set_ydata(data) # set the data plt.draw() # and draw it out time.sleep(0.1) # simulate some down time plt.pause(0.0001) # pause so that the drawing updates
261f0e89cd21fe428a45fd097ed1b45da01d105a
RaimundoGallino/holbertonschool-higher_level_programming
/0x0C-python-almost_a_circle/models/base.py
2,523
3.546875
4
#!/usr/bin/python3 '''file that defines the Base class''' import json from os import path class Base: '''define the Base class''' __nb_objects = 0 def __init__(self, id=None): '''class constructor''' Base.__nb_objects += 1 if id is not None: self.id = id else: self.id = Base.__nb_objects def integer_validator(self, name, value): """define integer_validator method""" if type(name) != str: raise TypeError("name must be a string") if type(value) is not int: raise TypeError("{} must be an integer".format(name)) elif value < 0 and (name == "x" or name == "y"): raise ValueError("{} must be >= 0".format(name)) elif value <= 0 and (name == "width" or name == "height"): raise ValueError("{} must be > 0".format(name)) @staticmethod def to_json_string(list_dictionaries): """define integer_validator method""" if list_dictionaries is None or len(list_dictionaries) == 0: list_dictionaries = [] return json.dumps(list_dictionaries) @classmethod def save_to_file(cls, list_objs): """define integer_validator method""" name = str(cls.__name__) + ".json" list_j = [] with open(name, "w", encoding="utf-8") as f: if list_objs is not None: for i in list_objs: list_j.append(cls.to_dictionary(i)) f.write(cls.to_json_string(list_j)) else: f.write(cls.to_json_string(list_j)) @staticmethod def from_json_string(json_string): """define integer_validator method""" if json_string is None or len(json_string) == 0: return [] else: return json.loads(json_string) @classmethod def create(cls, **dictionary): """create a dummy instance""" dummy = cls(3, 4) if cls.__name__ == "Rectangle" else cls(3) dummy.update(**dictionary) return dummy @classmethod def load_from_file(cls): """create a dummy instance""" name = str(cls.__name__) + ".json" list_j = [] if path.exists(name): with open(name, 'r', encoding='utf-8') as f: content = cls.from_json_string(f.read()) for obj in content: list_j.append(cls.create(**obj)) return list_j else: return list_j
faefe6b66e783c7586e30982fb2dfa71eb30f4ea
sandyqlin/python_projects
/stock_analysis.py
4,670
4.4375
4
# Plotting the Rise of Computers # For this lesson, we have specifically downloaded the historical stock data of Microsoft, Inc. and Apple Computer, Inc. # from the dates they each went public (which are March 13, 1986 and December 12, 1980, respectively) to July 1, 2015. # Let's first read both datasets into Pandas DataFrame objects and take a quick look at Microsoft's stock. import pandas apple_stock = pandas.read_csv("AAPL_historical_stock.csv") microsoft_stock = pandas.read_csv("MSFT_historical_stock.csv") # First 10 rows of Microsoft Stock data microsoft_stock.head(10) # 2: Columns # Yahoo! Finance gave us the following fields of information for each day: # Open - the price the stock opened at # High - the highest price the stock hit # Low - the lowest price the stock dropped to # Close - the final price the stock settled at # Volume - the trading volume, or amount of stock traded # Adj Close - the adjusted Close price # To easily slice and filter these dates and timestamps, we need to specify using Pandas that we want the Date column to be treated as a datetime64 data type. # The datetime64 data type, or dtype, is highly optimized for querying and interacting with dates like the ones we have in both datasets. # Let's use Pandas to convert the Date columns of both DataFrame objects to datetime64 dtypes, using the Pandas' to_datetime() function, # and then print the dtypes of both DataFrame objects to confirm. # Using pandas.to_datetime() to convert both datasets' Date columns microsoft_stock['Date'] = pandas.to_datetime(microsoft_stock['Date']) apple_stock['Date'] = pandas.to_datetime(apple_stock['Date']) # Use .dtypes and filter to info on ['Date'] column microsoft_date_datatype = microsoft_stock.dtypes['Date'] apple_date_datatype = apple_stock.dtypes['Date'] print("Microsoft Date Datatype: " + str(microsoft_date_datatype)) print("Apple Date Datatype: " + str(apple_date_datatype)) # Plotting Columns # We will learn about a library called Matplotlib, which makes it easy to plot all kinds of graphs just by specifying the data we want visualized. # Let's first plot the full time series of the closing stock prices. # Importing the pyplot sub-library from matplotlib library and referring to it as "plt" import matplotlib.pyplot as plt # plt.plot() tells Python to create a new plot and what the X (first argument) and Y (second argument) axes are plt.plot(microsoft_stock['Date'], microsoft_stock['Close']) # plt.title() details how we want the current plot to be titled plt.title("Microsoft: Historical Closing Stock Price Until Jul 1, 2015") # plt.show() reveals the plot we've been specifying plt.show() # New plot, repeat for Apple as we did with Microsoft plt.plot(apple_stock['Date'], apple_stock['Close']) plt.title("Apple: Historical Closing Stock Price Until Jul 1, 2015") plt.show() # 5: Trading Volume # Let's now visualize the historical time series of the trading volume for both companies. # The trading volume is measured by the number of shares that were exchanged in trades made that day. # Plotting trading volumes for the respective stocks helps us identify rare and important events in the market or in the company, # because investors will be more likely to buy or sell shares at that time. # Here we use "color=___" to specify color plt.plot(microsoft_stock['Date'], microsoft_stock['Volume'], color="blue") plt.title("Microsoft: Trading Volume") plt.show() # Repeat for Apple! plt.plot(apple_stock['Date'], apple_stock['Volume'], color="green") plt.title("Apple: Trading Volume") plt.show() # Filtering and Plotting # Let's now take advantage of Pandas' filtering capabilities, that we explored in previous lessons, # to zoom in to the peak of the Dot Com bubble (1999 - 2002) for both companies and plot the results. import matplotlib.dates as mdates # Filter dates to be greater than Jan 1, 1999 but less than Jan 1, 2002 microsoft_bubble = microsoft_stock[(microsoft_stock['Date'] > '1999-01-01') & (microsoft_stock['Date'] < '2002-01-01')] plt.plot(microsoft_bubble['Date'], microsoft_bubble['Volume']) # .gcf() - returns the current figure (or plot) fig_msft = plt.gcf() # autofmt_xdate(): auto-format X-axis to look nice plt.gcf().autofmt_xdate() plt.title("Microsoft Stock: Dot Com Crash") plt.show() # Repeat for Apple! apple_bubble = apple_stock[(apple_stock['Date'] > '1999-01-01') & (apple_stock['Date'] < '2002-01-01')] plt.plot(apple_bubble['Date'], apple_bubble['Volume']) # .gcf() - returns the current figure (or plot) fig_aapl = plt.gcf() # autofmt_xdate(): auto-format X-axis to look nice fig_aapl.autofmt_xdate() plt.title("Apple Stock: Dot Com Crash") plt.show()
962fd39921b87ed58699c72857809502c0e197b4
yandrea888/ejercicios_conceptos_basicos_python
/algoritmo2.py
235
3.765625
4
#Ejercicio 2 dolar = float(input("Ingrese el valor actual del dolar: ")) cDolares = float(input("Ingrese la cantidad de Dolares para su conversión: ")) cPesos = dolar*cDolares print(cDolares, "dólares, equivalen a ", cPesos, "Pesos")
47b479918abb0c7a0b9c79ad02fdb8bd194363ed
jhyang12345/algorithm-problems
/problems/bst_level_min_sum.py
1,150
3.921875
4
# You are given the root of a binary tree. Find the level for the binary tree with the minimum sum, and return that value. # # For instance, in the example below, the sums of the trees are 10, 2 + 8 = 10, and 4 + 1 + 2 = 7. So, the answer here should be 7. class Node: def __init__(self, value, left=None, right=None): self.val = value self.left = left self.right = right def minimum_level_sum(root): level = 1 queue = [(root, level)] dict = {} while queue: cur, level = queue.pop(0) if level not in dict: dict[level] = cur.val else: dict[level] += cur.val if cur.left: queue.append([cur.left, level + 1]) if cur.right: queue.append([cur.right, level + 1]) ret = None for x in dict: if ret == None: ret = dict[x] else: ret = min(dict[x], ret) return ret # 10 # / \ # 2 8 # / \ \ # 4 1 2 node = Node(10) node.left = Node(2) node.right = Node(8) node.left.left = Node(4) node.left.right = Node(1) node.right.right = Node(2) print(minimum_level_sum(node))
3cac5be07e436bbf672d302ffdb12f03d1b90af8
hectormiranda8/PrimsAlgorithm
/src/ciic4025-prims.py
1,843
3.796875
4
from collections import defaultdict import heapq example_graph = { 'A': {'B': 2, 'C': 3}, 'B': {'A': 2, 'C': 12, 'D': 10, 'E': 4}, 'C': {'A': 3, 'B': 12, 'F': 5}, 'D': {'B': 10, 'E': 7}, 'E': {'B': 4, 'D': 7, 'F': 16}, 'F': {'C': 5, 'E': 16, 'G': 9}, 'G': {'F': 9}, } def create_spanning_tree(graph, root_node): mst = defaultdict(set) # Minimum Spanning Tree set explored = {root_node} # Set containing explored nodes edge_nodes = [ # Array containing all linked nodes to the root node # with its corresponding weights (weight, root_node, linked_node) for linked_node, weight in graph[root_node].items() ] heapq.heapify(edge_nodes) # Turn edge_nodes into a heap array while edge_nodes: # While there's something in the heap do: weight, from_node, to_node = heapq.heappop(edge_nodes) if to_node not in explored: # For all unexplored edges do: explored.add(to_node) # Add node to the explored set mst[from_node].add(to_node) # Heap is sorted, therefore we can set the # to_node as the linked node for the from_node for next_node, weight in graph[to_node].items(): # Check which nodes we have to explore from the # to_node that now will become the from_node if next_node not in explored: # If node is not explored, then we have to explore it heapq.heappush(edge_nodes, (weight, to_node, next_node)) return mst print(dict(create_spanning_tree(example_graph, 'D'))) # Output: {'D': {'E'}, 'E': {'B'}, 'B': {'A'}, 'A': {'C'}, 'C': {'F'}, 'F': {'G'}}
911e87587a15b7988f89d7cc168da677009dfb3f
YeisonPC/Python
/dolares a la semana.py
803
3.5625
4
from datetime import datetime nombreCripto=input("Nombre de la Criptomoneda: ") cantCripto=float(input("Cantidad acumulada de la Criptomoneda: ")) cotizacion=float(input("Cotización por US$ del día de la Criptomoneda: ")) hora = datetime.now() hora=hora.strftime("%d/%m/%y %I:%M:%S %p") print("La fecha completa y hora en la que obtuvo la información fue:"+str(hora)) valorTotal= cantCripto * cotizacion Tasa=1.05 print("Ud. Posee un total de US$ "+str(valorTotal)) valorTotal1=valorTotal *Tasa valorTotal2=valorTotal1*Tasa valorTotal3=valorTotal2*Tasa valorTotal4=valorTotal3*Tasa valorTotal5=valorTotal4*Tasa valorTotal6=valorTotal5*Tasa valorTotal7=valorTotal6*Tasa ganancia= valorTotal7-valorTotal print("Su ganancia luego de una semana es: "+str(ganancia)+"USD")
4e611c2e087609c10820c51091099ef9e36e90c0
Manevle16/PythonUTDDataScienceWorkshop
/October27/DSPython/5_MissingData.py
496
3.796875
4
import numpy as np import pandas as pd d = {'A': [1, 2, np.nan], 'B': [5, np.nan, np.nan], 'C': [1, 2, 3]} print(d) df = pd.DataFrame(d) print(df) #print(df.dropna()) #Drops all rows with NaN value #print(df.dropna(axis=1)) #Drops all cols with NaN value # print(df) #print(df.dropna(thresh=2)) #Drops all rows with less than 2 NaN values #print(df) #print(df.fillna(value=2)) #Replaces all NaN values with 2 print(df.fillna(value=df['A'].mean())) #Replaces all NaN values with the mean of col A
86f6b483770281404878a29aaca696287dbc4c73
ThiagoDiasV/curso-programacao-python-bastter
/D9/d9_ex2.py
456
3.59375
4
def calcula_listas_aninhadas(lista_ou_nao): if not isinstance(lista_ou_nao, list): return f"Você inseriu um objeto do tipo {type(lista_ou_nao)}, que não é uma lista e não pode ser processado por nosso programa. Tente novamente." contador_sublistas = 0 for item in lista_ou_nao: if isinstance(item, list): contador_sublistas += 1 return f"A lista inserida contém {contador_sublistas} lista(s) aninhadas"
453477969b13819d358f1ef9a6a949b91bbebde5
joepuzzo/Learning
/Python/TCPServer.py
752
3.53125
4
#A simple TCP Server implimentation from socket import * serverPort = 12000 #Creat a TCP v4 socket serverSocket = socket(AF_INET,SOCK_STREAM) #Like UPD we bind the port number to the socket serverSocket.bind((‘’,serverPort)) #We tell the socket to listen (1 max amount of qued connects) serverSocket.listen(1) print ‘The server is ready to receive’ while 1: #Create a specific connect socket for 'this' client connectionSocket, addr = serverSocket.accept() #Recive the data sentence = connectionSocket.recv(1024) #mod the data capitalizedSentence = sentence.upper() #send mod data back connectionSocket.send(capitalizedSentence) #close the connection for others to get in connectionSocket.close()
64f0caa0a0a7f45e837f88b311b880b69668274e
Allykazam/Card_game
/cards.py
9,570
3.6875
4
import random class Cards: def __init__(self, face): self.face = face def __str__(self): if self.face < 11 and self.face > 1: return("I am a(n) {}".format(self.face)) elif self.face == 1: return("I am an Ace") elif self.face == 11: return ("I am a Jack") elif self.face == 12: return("I am a Queen") else: return("I am a King") class Red_cards(Cards): def __init__(self, face): Cards.__init__(self, face) self.color = 'Red' def __str__(self): if self.face < 11 and self.face > 1: return("I am a {} {}".format(self.color, self.face)) elif self.face == 1: return("I am a {} Ace") elif self.face == 11: return ("I am a {} Jack") elif self.face == 12: return("I am a {} Queen") else: return("I am a {} King") class Black_cards(Cards): def __init__(self, face): Cards.__init__(self, face) self.color = 'Black' def __str__(self): if self.face < 11 and self.face > 1: return("I am a {} {}".format(self.color, self.face)) elif self.face == 1: return("I am a {} Ace".format(self.color)) elif self.face == 11: return("I am a {} Jack".format(self.color)) elif self.face == 12: return("I am a {} Queen".format(self.color)) else: return("I am a {} King".format(self.color)) class Diamond_cards(Red_cards, Cards): def __init__(self, face): Red_cards.__init__(self, face) Cards.__init__(self, face) self.suit = 'Diamonds' def __str__(self): if self.face < 11 and self.face > 1: return("I am a(n) {} of {}\n".format(self.face, self.suit)) elif self.face == 1: return("I am an Ace of {}\n".format(self.suit)) elif self.face == 11: return ("I am a Jack of {}\n".format(self.suit)) elif self.face == 12: return("I am a Queen of {}\n".format(self.suit)) else: return("I am a King of {}\n".format(self.suit)) class Heart_cards(Red_cards, Cards): def __init__(self, face): Red_cards.__init__(self, face) Cards.__init__(self, face) self.suit = 'Hearts' def __str__(self): if self.face < 11 and self.face > 1: return("I am a(n) {} of {}\n".format(self.face, self.suit)) elif self.face == 1: return("I am an Ace of {}\n".format(self.suit)) elif self.face == 11: return ("I am a Jack of {}\n".format(self.suit)) elif self.face == 12: return("I am a Queen of {}\n".format(self.suit)) else: return("I am a King of {}\n".format(self.suit)) class Spade_cards(Black_cards, Cards): def __init__(self, face): Black_cards.__init__(self, face) Cards.__init__(self, face) self.suit = 'Spades' def __str__(self): if self.face < 11 and self.face > 1: return("I am a(n) {} of {}\n".format(self.face, self.suit)) elif self.face == 1: return("I am an Ace of {}\n".format(self.suit)) elif self.face == 11: return ("I am a Jack of {}\n".format(self.suit)) elif self.face == 12: return("I am a Queen of {}\n".format(self.suit)) else: return("I am a King of {}\n".format(self.suit)) class Club_cards(Black_cards, Cards): def __init__(self, face): Black_cards.__init__(self, face) Cards.__init__(self, face) self.suit = 'Clubs' def __str__(self): if self.face < 11 and self.face > 1: return("I am a(n) {} of {}\n".format(self.face, self.suit)) elif self.face == 1: return("I am an Ace of {}\n".format(self.suit)) elif self.face == 11: return ("I am a Jack of {}\n".format(self.suit)) elif self.face == 12: return("I am a Queen of {}\n".format(self.suit)) else: return("I am a King of {}\n".format(self.suit)) card_dictionary = { 1 : Diamond_cards(1), 2 : Diamond_cards(2), 3 : Diamond_cards(3), 4 : Diamond_cards(4), 5 : Diamond_cards(5), 6 : Diamond_cards(6), 7 : Diamond_cards(7), 8 : Diamond_cards(8), 9 : Diamond_cards(9), 10 : Diamond_cards(10), 11 : Diamond_cards(11), 12 : Diamond_cards(12), 13 : Diamond_cards(13), 14 : Heart_cards(1), 15 : Heart_cards(2), 16 : Heart_cards(3), 17 : Heart_cards(4), 18 : Heart_cards(5), 19 : Heart_cards(6), 20 : Heart_cards(7), 21 : Heart_cards(8), 22 : Heart_cards(9), 23 : Heart_cards(10), 24 : Heart_cards(11), 25 : Heart_cards(12), 26 : Heart_cards(13), 27 : Spade_cards(1), 28 : Spade_cards(2), 29 : Spade_cards(3), 30 : Spade_cards(4), 31 : Spade_cards(5), 32 : Spade_cards(6), 33 : Spade_cards(7), 34 : Spade_cards(8), 35 : Spade_cards(9), 36 : Spade_cards(10), 37 : Spade_cards(11), 38 : Spade_cards(12), 39 : Spade_cards(13), 40 : Club_cards(1), 41 : Club_cards(2), 42 : Club_cards(3), 43 : Club_cards(4), 44 : Club_cards(5), 45 : Club_cards(6), 46 : Club_cards(7), 47 : Club_cards(8), 48 : Club_cards(9), 49 : Club_cards(10), 50 : Club_cards(11), 51 : Club_cards(12), 52 : Club_cards(13), } card_deck = [] #test_full_house = [] test_three = [] for i in range(52): curr_card = card_dictionary.get(i+1) card_deck.append(curr_card) #print(curr_card) #print(card_deck) #test_full_house.append(card_deck[2]) #test_full_house.append(card_deck[15]) #test_full_house.append(card_deck[9]) #test_full_house.append(card_deck[22]) #test_full_house.append(card_deck[35]) test_three.append(card_deck[2]) test_three.append(card_deck[15]) test_three.append(card_deck[28]) test_three.append(card_deck[41]) test_three.append(card_deck[6]) for i in test_three: print(i) print() sysRan = random.SystemRandom() sysRan.shuffle(card_deck) def deal_cards(card_deck, size_of_hand): hand = [] for i in range(size_of_hand): hand.append(card_deck.pop()) return hand #def compare_hands(dealer_hand, player_hand): def check_straight(curr_deck): prev_val = 0 val_list = [] for i in curr_deck: val_list.append(i.face) val_list.sort() for i in val_list: if prev_val == 0: prev_val = i else: if (i - prev_val) != 1: return False else: #print(i - prev_val) prev_val = i return True def check_flush(curr_deck): match_suit = curr_deck[0].suit for i in curr_deck: if match_suit != i.suit: return False return True def check_straight_flush(curr_deck): if (check_straight(curr_deck)) and (check_flush(curr_deck)): return True else: return False def check_set_of_num(curr_deck, set_num): curr_val = 0 total_same = 0 set_num_found = False val_list = [] for i in curr_deck: val_list.append(i.face) val_list.sort() for i in val_list: if curr_val == 0: curr_val = i total_same += 1 else: if i == curr_val: total_same += 1 if total_same == set_num: set_num_found = True else: total_same = 0 curr_val = i total_same += 1 if set_num_found: return True else: return False def check_full_house(curr_deck): val_list = [] curr_val = 0 running_total = 0 was_two = False for i in curr_deck: val_list.append(i.face) val_list.sort() for i in val_list: if curr_val == 0: curr_val = i running_total += 1 else: if i == curr_val: running_total += 1 else: if (running_total == 3): running_total = 0 curr_val = i running_total += 1 elif (running_total == 2) and (was_two == False): running_total = 0 curr_val = i running_total += 1 was_two = True else: #means it is not currently 3, it is not 2, or it was 2 but there was already a pair return False return True def check_two_pair(curr_deck): num_pairs = 0 curr_val = 0 total_same = 0 val_list = [] for i in curr_deck: val_list.append(i.face) val_list.sort() for i in val_list: if curr_val == 0: curr_val = i total_same += 1 else: if i == curr_val: total_same += 1 if total_same == 2: num_pairs += 1 total_same = 0 curr_val = 0 else: total_same = 0 curr_val = i if num_pairs != 2: return False else: return True player_hand = deal_cards(card_deck, 5) dealer_hand = deal_cards(card_deck, 5) for i in player_hand: print(i) print("\n") for i in dealer_hand: print(i) print(check_full_house(player_hand)) #print(check_full_house(test_full_house)) print(check_set_of_num(test_three, 3))
7a5ce34e3c673672d1657342aba829c09941db5b
HongGyuSik/16PFC-abcd7413
/ex35/factorial.py
244
4.0625
4
# -*-coding:utf8 def factorial(n): if 1 == n: result = 1 elif 1 < n: result = n * factorial(n-1) return result if __name__ == '__main__': f = factorial(5) print (f) # 5!를 재귀호출법으로 표기함.
216c4841ef45a3829cbb572010d35e7b586d6b43
opwtryl/leetcode
/112路径总和.py
1,162
3.890625
4
''' 给定一个二叉树和一个目标和,判断该树中是否存在根节点到叶子节点的路径,这条路径上所有节点值相加等于目标和。 说明: 叶子节点是指没有子节点的节点。 示例: 给定如下二叉树,以及目标和 sum = 22, 5 / \ 4 8 / / \ 11 13 4 / \ \ 7 2 1 返回 true, 因为存在目标和为 22 的根节点到叶子节点的路径 5->4->11->2。 ''' # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def hasPathSum(self, root, sum): """ :type root: TreeNode :type sum: int :rtype: bool """ l=r=False if root: if all((not root.left,not root.right,root.val==sum)): return True if root.left: l=self.hasPathSum(root.left,sum-root.val) if root.right: r=self.hasPathSum(root.right,sum-root.val) return l or r
ccaea77b3502c0cb30baa0cc26e82015de502af9
xMrShadyx/SoftUni
/Programming Basic More Excercise/Simple_Operations_and_Calculations/10_Weather_Forecast_Part_2.py
237
3.96875
4
temp = float(input()) if temp <= 0: print('unknown') elif temp <= 11.9: print('Cold') elif temp <= 14.9: print('Cool') elif temp <= 20: print('Mild') elif temp <= 25.9: print('Warm') elif temp >= 26: print('Hot')
2ca84104a9cb5c3f84b2a81e141f49423beb557c
AlanLee97/Study_Python3
/MyStudy/ex10_module.py
1,277
3.84375
4
""" 1. import 语句 想使用 Python 源文件,只需在另一个源文件里执行 import 语句 """ # import test # test.hello() # num = test.sumf() # print(num) """ 2. from … import 语句 Python 的 from 语句让你从模块中导入一个指定的部分到当前命名空间中,语法如下: 这样就调用模块中的变量和函数等时可以不用每次都加上模块名 可以直接使用变量或函数等 """ # from test import hello,sumf # hello() # num = sumf() # print(num) # from … import * 语句 # 把一个模块的所有内容全都导入到当前的命名空间也是可行的,只需使用如下声明 # from test import * # hello() # num = sumf() # print(num) """ 3. __name__属性 一个模块被另一个程序第一次引入时,其主程序将运行。 如果我们想在模块被引入时,模块中的某一程序块不执行,我们可以用__name__属性来使该程序块仅在该模块自身运行时执行。 """ # if __name__ == '__main__': # print('程序自身在运行') # else: # print('我来自另一模块') """ 4. dir() 函数 内置的函数 dir() 可以找到模块内定义的所有名称。以一个字符串列表的形式返回: """ import sys, test print(dir(test)) print("\n") print(dir(sys))
a12e92b19c21b0082dfaee4fd0e55de9baa0a579
lws803/cs1010_A0167
/SomeProgs/Python Stuff/Coding Assignments/MeanMedianMode.py
2,345
4.15625
4
# Name: Tan Tze Guang # Class: 13S28 # Date: 26 March 2013 # This program finds the mean, median and mode of a list of numbers def mean(List): sums = 0 # A temporary storage for sum of numbers in list for items in range(len(List)): # Sums all numbers in the list sums = sums + items mean_num = sums/len(List) # Finds the 'Mean' here return mean_num def median(List): List.sort() # Changes the list into numerical order count = len(List) check = count % 2 # Checks whether the nuber is odd or even if check == 0: # Even number median_num = (List[(len(List))//2] + List[(len(List)//2)+1])/2 return median_num if check == 1: # Odd number median_num = List[(len(List)//2)] return median_num def mode(List): # Currently only can find 1 mode # Multiple modes will cause the smaller mode to be removed List.sort() frequency = [] # Creates a list to store values of frequency of value count = len(List) - 1 for items in List: freq = 0 # Ensures that freq is reset after every loop freq = List.count(items) frequency.append(freq) print("This is the current List:",List) print("Frequency of numbers is:",frequency) while count > 0: # This is to remove all non-mode numbers if frequency[0] == frequency[1]: List.pop(0) frequency.pop(0) elif frequency[0] > frequency[1]: List.pop(1) frequency.pop(1) elif frequency[0] < frequency[1]: List.pop(0) frequency.pop(0) count = count - 1 return List[0] def main(): print("This program finds the mean,median and mode of a list of numbers.") print("Currently, the program is only able to find 1 mode.") print("In the case of multiple modes, the smaller mode will be removed.") print("") numbers = [8,6,7,9,9,6,4,4,6,8,9,9,9,8,7,7,6] print("The list has",len(numbers),"numbers") print() mean_number = mean(numbers) print("The mean of this list of numbers is",mean_number) print() median_number = median(numbers) print("The median of this list of numbers is",median_number) print() mode_number = mode(numbers) print("The mode of this list of numbers is",mode_number) main()
016ac64a712604f1c8e2e681ac49cf1277b4a98c
RinaticState/python-work
/Chapter 8/great_magicians.py
803
3.921875
4
# -*- coding: utf-8 -*- """ Created on Wed Nov 22 07:03:23 2017 @author: Ayami """ #Assignment 8.10: Great Magicians def show_magicians(magicians): """Prints names of magicians from a list.""" for magician in magicians: print("Hello, " + magician.title() + ", are you ready for the big show ?") def make_great(magicians): great_magicians = [] while magicians: popped_magician = magicians.pop() great_magician = popped_magician + " the great" great_magicians.append(great_magician) for great_magician in great_magicians: magicians.append(great_magician) return magicians magicians = ['houdini', 'copperfield', 'takayama'] great_magicians = make_great(magicians[:]) show_magicians(great_magicians) show_magicians(magicians)
901a998697859a7531a4b5bd76a367079149bee7
gabriel-guobin/Learn-Python-the-Hard-Way
/ex29.py
480
4.15625
4
people = 10 cats = 30 dogs = 15 if people > cats: print ("Not so much cats! The world is saved!") if people < cats: print ("Too much cats! The world is doomed!") if people < dogs: print("The world is drooled on!") if people > dogs: print("The world is dry.") dogs += 5 if people >= dogs: print ("People are greater than or equal to dogs") if people <= dogs: print ("People are less than or equal to dogs") if people == dogs: print ("People are dogs(seriously)")
6d25ab2a065f915f44cdbc716332f4c1ba079db7
sudoFerraz/exercism
/python/leap/leap.py
292
4
4
#!/usr/bin/env python # -*- coding: utf-8 -*- def is_leap_year(year): if year%4 == 0: if year%100 == 0: if year%400 == 0: return True else: return False else: return True else: return False
33d53e5093927d9511b47712dd4675632492277c
dunmanhigh/y2math
/binary_search.py
1,949
3.5
4
import tkinter as tk window = tk.Tk() window.title("Binary search") frame = tk.Frame(window) frame.grid() def display_arr (arr, row_, mid_index=-1): for i in range (len(arr)): if i == len(arr)//2: tk.Label(frame, text=str(arr[i]), fg="yellow", bg="black").grid(row=row_, column=i+4) else: tk.Label(frame, text=str(arr[i]), fg="white", bg="black").grid(row=row_, column=i+4) def visualbin (): global frame frame.destroy() arr = array.get().split(",") target = target_.get() arr = [int(x) for x in arr] arr.sort() target = int(target) curr_row = 10 lower_bound = 0 upper_bound = len(arr)-1 frame = tk.Frame(window) frame.grid(row=curr_row) display_arr(arr, curr_row+1) curr_row += 1 found = False while lower_bound <= upper_bound: mid = (lower_bound+upper_bound)//2 tk.Label(frame, text="Mid: "+str(arr[mid]), fg="yellow", bg="black").grid(row=curr_row, column=1) display_arr(arr[lower_bound:upper_bound+1], curr_row, mid) if arr[mid] == target: tk.Label(frame, text="Found!").grid(row=curr_row+2, column=1) found = True break elif arr[mid] > target: upper_bound = mid-1 else: lower_bound = mid+1 curr_row += 2 if not found: tk.Label(frame, text="Not found!").grid(row=curr_row+2, column=1) tk.Label(window, text="Visualizing binary search", fg="white", bg="black").grid(row=1) array = tk.StringVar() array.set("1,2,3") target_ = tk.StringVar() target_.set("0") tk.Label(window, text="Enter the array (separated by commas): ").grid(row=2) tk.Entry(window, textvariable=array).grid(row=2, column=1) tk.Label(window, text="Enter the target: ").grid(row=3) tk.Entry(window, textvariable=target_).grid(row=3, column=1) tk.Button(window, text="Confirm entry",command=visualbin).grid(row=4)
4eaba97c8754bd158cbb378037d16543a2e0344e
spoonsandhangers/Term2_Python
/1b blackJack.py
2,626
4.09375
4
import random # import the random library # Set card1 and card2 to random integers between 1 and 11 inclusive. card1 = random.randint(1,11) card2 = random.randint(1,11) # print out the values of the players cards print("player card 1: ", card1) print("player card 2: ", card2) # Add together the players cards cardTotal = card1 + card2 # Print out the total of the players cards print("Player card total:", cardTotal) # if the players card total is not equal to 21 ask the player # if they want to stick or twist 's' or 't'. # this has an else statement on the same indent # for when the players total is 21. if cardTotal != 21: # add .lower() at the end of the input request to convert the input to # lower case userChoice = input("Would you like to twist 't' or stick 's'? ").lower() # if the player chooses 't' randomly select another card for them. if userChoice == "t": card3 = random.randint(1,11) print("player card 3:", card3) # Add this new card to the total cardTotal += card3 print("player new total:", cardTotal) # if the players card total is less than 21 # This if statement has an elif and else on the same indent. # The elif checks to see if the player has 21 # the else then runs if the player hasn't got 21 or less than 21. # As they must be bust. if cardTotal < 21: # set dealerCard1 and 2 to random numbers between 1 and 11 inclusive dealerCard1 = random.randint(1,11) dealerCard2 = random.randint(1,11) # print out these numbers. print("Dealer card 1:", dealerCard1) print("Dealer card 2:", dealerCard2) # Add up the values of the two cards dealerTotal = dealerCard1 + dealerCard2 print("Dealer card total:", dealerTotal) # if the dealers total is less than or equal to 17 # automatically deal them another card. if dealerTotal <= 17: dealerCard3 = random.randint(1,11) # Add this card to the dealers total. dealerTotal += dealerCard3 print("Dealers hand is less than 17 so they receive an extra card:", dealerCard3) print("Dealer total now:", dealerTotal) # these selection statements decide whether the dealer has 21 # if the dealer has more than 21 so is bust # if the dealers total is more than the players. if dealerTotal == 21: print("Dealer wins with 21!") elif dealerTotal > 21: print("Player wins, dealer is bust!") elif dealerTotal >= cardTotal: print("Dealer wins with:", dealerTotal) else: print("Player wins with:", cardTotal) elif cardTotal == 21: print("BlackJack! Well done player wins!") else: print("Dealer wins player is bust!") else: print("BlackJack! Well done player wins!")
8aba6598efe638499bcccd39dca33a3295ccf0bd
srvela/cursoPython
/3. Condicionales/condicionales.py
352
3.890625
4
condicion = True # Condicion Simple if(condicion): print("Verdadero") condicion1 = True # Condicion por default if(condicion1): print("Condicion 1") else: print("Valor default") condicion2 = False # Condicion Multiple if(condicion1): print("Condicion 1") elif(condicion2): print("Condicion 2") else: print("Valor de default")
f62c38e1ba47635c2183136f0ea65a84f3bdb98f
Nomadluap/TriodEnumeration
/pointIterators.py
925
3.625
4
''' pointIterators.py - Functions for iterating over Vertices and Points. ''' from abc import ABCMeta from config import N, M, T from mapping import Point, Vertex class VertexIterator(object): ''' An abstract base class for DomainVertexIterator and CodomainVertexIterator. ''' __metaclass__ = ABCMeta tmax = -1 def __init__(self): self.arm = 0 self.t = -1 def __iter__(self): return self def next(self): self.t += 1 if self.t > self.tmax: self.t = 1 self.arm += 1 if self.arm >= T: raise StopIteration return Vertex(self.arm, self.t) class DomainVertexIterator(VertexIterator): ''' An iterator to iterate over points in the domain. ''' tmax = N class CodomainVertexIterator(VertexIterator): ''' An iterator to iterate over points in the codomain ''' tmax = M
cc6cb63482cca1792220b189d92589e5a81d7db8
Hemalatah/Cracking-The-Coding-Interview
/sorting and searching.py
2,691
4.21875
4
###You are given two sorted arrays, A and B, and A has a large enough buffer at the end to hold B Write a method to merge B into A in sorted order def merge(arr1,arr2): arr1 = sorted(arr1); arr2 = sorted(arr2); new_arr = []; i, j = 0, 0; while i < len(arr1) and j < len(arr2): if arr1[i] > arr2[j]: new_arr.append(arr2[j]); j = j + 1; else: new_arr.append(arr1[i]); i = i + 1; while i < len(arr1): new_arr.append(arr1[i]); i = i + 1; while j < len(arr2): new_arr.append(arr2[j]); j = j + 1; return new_arr; print merge([2,4,7],[7,1,0]); ### Write a method to sort an array of strings so that all the anagrams are next to each other def sort_anagram(arr): return sorted(arr, cmp=lambda x,y: cmp(sorted(x),sorted(y))); print sort_anagram(["god", "dog", "abc", "cab", "man"]); ###Given a sorted array of n integers that has been rotated an unknown number of times,giveanO(logn)algorithmthat ndsanelementinthearray Youmayassume that the array was originally sorted in increasing order EXAMPLE: Input: nd 5 in array (15 16 19 20 25 1 3 4 5 7 10 14) Output: 8 (the index of 5 in the array) def find_pos(arr): for i in range(len(arr)-1): if arr[i+1] < arr[i]: return i + 1; def find_elem(arr, element): pos = find_pos(arr); left_arr = arr[:pos]; right_arr = arr[pos:]; if left_arr[0] > element: for i in right_arr: if i == element: return arr.index(element); for i in left_arr: if i == element: return arr.index(element); print find_elem([15, 16, 19, 20, 25, 1, 3, 4, 5, 7, 10, 14], 5); ### Given a sorted array of strings which is interspersed with empty strings, write a meth- od to nd the location of a given string def find_loc(arr, elem): mid = len(arr) - 1; if elem >= arr[mid]: for i in range(len(arr)-1, mid, -1): if arr[i] == elem: return i; for i in range(mid-1, 0, -1): if arr[i] == elem: return i; return -1; print find_loc(["at", "", "", "", "ball", "", "", "car", "", "", "dad", "", ""], "ballcar"); ### Given a matrix in which each row and each column is sorted, write a method to nd an element in it def find_mat(mat, elem, m, n): row = 0; col = n-1; while row < m and col >= 0: if mat[row][col] == elem: return True; elif mat[row][col] > elem: col = col - 1; else: row = row + 1 return False; print find_mat([[1,2,3],[4,5,6],[7,8,9]], 0, 3, 3); def circus_tower(arr): arr = sorted(arr); new_arr = []; new_arr.append(arr[0]); i = 1; for i in range(len(arr)): if arr[i][1] > arr[i-1][1] and new_arr[-1][1] < arr[i][1]: new_arr.append(arr[i]); return new_arr; print circus_tower([[65, 100], [70, 150], [56, 90], [75, 190], [60, 95], [68, 110]]);
bfe4264fdc26c4efd77a82cd97e1120cd496ee0a
saby95/Leetcode-Submissions
/Palindrome Numer.py
750
3.59375
4
class Solution(object): def isPalindrome(self, x): """ :type x: int :rtype: bool """ if x<0: return bool(0) s = "" while x>0: s += chr((x%10) + 48) x=x//10 return s==s[::-1] def stringToInt(input): return int(input) def main(): import sys def readlines(): for line in sys.stdin: yield line.strip('\n') lines = readlines() while True: try: line = lines.next() x = stringToInt(line) ret = Solution().isPalindrome(x) out = (ret) print out except StopIteration: break if __name__ == '__main__': main()
74bfbc9b57e5f523d498e75a2ffbe6118573a224
Raakeshtrip/test_Repo
/avarage.py
172
3.53125
4
def avarage(numbers): total= len(numbers) numinator=0.0 for number in numbers: numinator +=number return numinator/total print(avarage([10,11,12,13]))
c5ee98884e0c9311c6dbd7cbf3c4c9a6861366b5
pmbaumgartner/spacy-v3-project-startup
/startup.py
5,322
3.609375
4
import hashlib from pathlib import Path import questionary import srsly WELCOME = """Welcome to the spaCy project transfer script. The intent of this walkthrough script is to create a spaCy v3 project.yml file for an existing NLP project. You don't even have to be using a spaCy model (yet) - there are many features like assets and remotes that are helpful before your project is in a final state. For more on spaCy projects: https://spacy.io/usage/projects""" ORDER = """The order of this walkthrough is: 1. Project Information (Title + Description) 2. Add project directories 2. Add project assets/data Location 3. Templates/Placeholders """ project_yaml = {} questionary.print("Welcome!", style="bold") questionary.print(WELCOME, style="italic") questionary.print(ORDER) title = questionary.text("What's the title of the project?").ask() project_yaml["title"] = title description = questionary.text( "Please provide a short description of the project." ).ask() project_yaml["description"] = description project_directory = questionary.path( "What's the path to the current project directory?", only_directories=True ).ask() questionary.print(f"Great, we'll be using: {project_directory}") add_directories = questionary.confirm( f"Would you like to add current subdirectories of {project_directory} as project directories? (To ensure they exist for future commands and workflows)" ).ask() if add_directories: directories = list( p.name for p in Path(project_directory).glob("*") if p.is_dir() and not p.name.startswith(".") ) project_yaml["directories"] = directories print(f"{len(directories)} directories added.") assets_exist = questionary.confirm( "Is there an existing folder of data or assets the project uses you'd like to add?" ).ask() if assets_exist: assets = questionary.path( "Where is this directory located?", default=str(project_directory), only_directories=True, ).ask() assets_files = list(p for p in Path(assets).rglob("*") if p.is_file()) questionary.print(f"{len(assets_files)} asset files found.") add_md5 = questionary.confirm( "Would you like to add the md5 checksums to current asset files? (this can prevent future unnecessary redownloading)" ).ask() if add_md5: asset_md5s = [ hashlib.md5(Path(path).read_bytes()).hexdigest() for path in assets_files ] asset_data = [ { "dest": str(path.relative_to(project_directory)), "description": "", "checksum": md5, } for path, md5 in zip(assets_files, asset_md5s) ] project_yaml["assets"] = asset_data else: asset_data = [ {"dest": str(path.relative_to(project_directory)), "description": ""} for path in assets_files ] project_yaml["assets"] = asset_data else: asset_example = questionary.confirm("Would you like to add an example asset?").ask() if asset_example: asset_data = [ { "dest": "path/to/asset", "description": "Description of asset.", "url": "url to asset source", } ] project_yaml["assets"] = asset_data var_example = questionary.confirm( "Would you like to add an example variable? (For consistent argument or path use across multiple commands)" ).ask() if var_example: project_vars = {"example": "example1", "other_example": "another-example"} project_yaml["vars"] = project_vars remote_example = questionary.confirm( "Would you like to add an example remote storage? (For pushing/pulling workflow output)" ).ask() if remote_example: remote_vars = {"default": "s3://my-spacy-bucket", "local": "/mnt/scratch/cache"} project_yaml["remotes"] = remote_vars command_example = questionary.confirm("Would you like to add example commands?").ask() if command_example: commands = [ { "name": "make_temporary_file", "help": "make a temporary file (EXAMPLE)", "script": ["touch temporaryfile"], "outputs": ["temporaryfile"], }, { "name": "delete_temporary_file", "help": "Print listed files (EXAMPLE)", "script": ["rm -f temporaryfile"], "deps": ["temporaryfile"], }, ] project_yaml["commands"] = commands workflow_example = questionary.confirm( "Would you like to add a workflow example?" ).ask() if workflow_example: workflow = {"all": ["make_temporary_file", "delete_temporary_file"]} project_yaml["workflows"] = workflow output_path = Path(project_directory) / "project.yml" srsly.write_yaml(output_path, project_yaml) with output_path.open("a") as output_yaml: output_yaml.write("\n") output_yaml.write( "\n# This project.yml generated with https://github.com/pmbaumgartner/spacy-v3-project-startup" ) output_yaml.write( "\n# For more on spaCy projects, see: https://spacy.io/usage/projects and https://spacy.io/api/cli#project" ) output_yaml.write( "\n# And see the templates at: https://github.com/explosion/projects" ) questionary.print(f"Project yml output to {output_path}.")
291cf4d0176b88eb1a602c6a77c6bf4ba4dca86d
chris-peng-1244/python-quiz
/rotate_in_place.py
335
4.15625
4
def reverse(array, left, right): while left < right: array[left], array[right] = array[right], array[left] left += 1 right -= 1 def rotate(array, k): n = len(array) reverse(array, 0, n - k - 1) reverse(array, n - k, n - 1) reverse(array, 0, n - 1) return array print(rotate([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], 3))
823a4a4d5a3ec32f3b3d5e09f8e8dc0a99820178
JacksonYu92/Pong-Game-V2
/scoreboard.py
917
3.796875
4
from turtle import Turtle ALIGNMENT = "center" FONT = ("Courier", 22, "normal") class Scoreboard(Turtle): def __init__(self): super().__init__() self.color("white") self.penup() self.hideturtle() self.l_score = 0 self.r_score = 0 self.update_scoreboard() def update_scoreboard(self): self.clear() self.goto(0,300) self.write("Welcome to Jackson's Pong Game", align=ALIGNMENT, font=("Courier", 30, "normal")) self.goto(-250, 225) self.write(f"Left hand\n {self.l_score}", align=ALIGNMENT, font=FONT) self.goto(250, 225) self.write(f"Right hand\n {self.r_score}", align=ALIGNMENT, font=FONT) def l_point(self): self.l_score += 1 self.update_scoreboard() def r_point(self): self.r_score += 1 self.update_scoreboard()
b67b43d2738f406e39e81c717b0b53958c5180c4
mine1984/Advent-of-code
/2015/day16/day16b.py
2,620
3.515625
4
# You have 500 Aunts named "Sue". # The My First Crime Scene Analysis Machine (MFCSAM for short) can detect a few specific compounds in a given sample, as well as how many distinct kinds of those compounds there are. According to the instructions, these are what the MFCSAM can detect: # # children, by human DNA age analysis. # cats. It doesn't differentiate individual breeds. # Several seemingly random breeds of dog: samoyeds, pomeranians, akitas, and vizslas. # goldfish. No other kinds of fish. # trees, all in one group. # cars, presumably by exhaust or gasoline or something. # perfumes, which is handy, since many of your Aunts Sue wear a few kinds. # In fact, many of your Aunts Sue have many of these. You put the wrapping from the gift into the MFCSAM. It beeps inquisitively at you a few times and then prints out a message on ticker tape: # # children: 3 # cats: 7 # samoyeds: 2 # pomeranians: 3 # akitas: 0 # vizslas: 0 # goldfish: 5 # trees: 3 # cars: 2 # perfumes: 1 # You make a list of the things you can remember about each Aunt Sue. Things missing from your list aren't zero - you simply don't remember the value. # # What is the number of the Sue that got you the gift? # # In particular, the cats and trees readings indicates that there are greater than that many (due to the unpredictable nuclear decay of cat dander and tree pollen), while the pomeranians and goldfish readings indicate that there are fewer than that many. # # What is the number of the real Aunt Sue? class Aunt(): def __init__(self, string): self.name = string[1][:-1] self.clues = {} self.clues[string[2][:-1]] = int(string[3][:-1]) self.clues[string[4][:-1]] = int(string[5][:-1]) self.clues[string[6][:-1]] = int(string[7]) self.is_sender = self.find_out() def find_out(self): for clue in self.clues: if clue == 'cats' or clue == 'trees': if self.clues[clue] <= gift[clue]: return False elif clue == 'pomeranians' or clue == 'goldfish': if self.clues[clue] >= gift[clue]: return False elif self.clues[clue] != gift[clue]: return False return True gift = {'children': 3, 'cats': 7, 'samoyeds': 2, 'pomeranians': 3, 'akitas': 0, 'vizslas': 0, 'goldfish': 5, 'trees': 3, 'cars': 2, 'perfumes': 1} aunts = {} try: while True: string = input().split() name = string[1][:-1] aunts[name] = Aunt(string) except EOFError: pass for aunt in aunts: if aunts[aunt].is_sender: print(aunt)
da021d7eb0b1d4e8d9e86234cc036f87ba729096
GodfredGuru/Assignment
/list.py
510
4.15625
4
import datetime names = (input('PLEASE ENTER YOUR NAME: '),'kofi','kpogo','oriental') for name in names: if name ==names[0]: print(name,'is at index of 0') if name ==names[1]: print(name,'is at index of 1') if name ==names[2]: print(name,'is at index of 2') if name ==names[3]: print(name,'is at index of 3') nums = [10,3,4,5,7] print(max(nums)) today = datetime.datetime.today() print(today.day,today.month,today.year,today.hour,':',today.minute,today.second)
0137bd094e004f8f2cb128bc938253eef829b533
yousamasham/Date-GlobalPosition
/src/date_adt.py
5,406
4.09375
4
## @file date_adt.py # @author Yousam Asham # @brief This module creates date related calculations using several methods. This includes getting the next and previous day and calculation differences between two given days. # @date 09-01-2020 import datetime ## @brief An ADT for the class DateT # @details Some assumptions made include that the user will be inputting correct dates in order for the module to return some correct dates. class DateT: ## @brief A constructor for the DateT class # @details Initializes the attributes of the DateT objects, assuming that the user inputs correct/valid AD dates. # @param d represents the day number eg: 0-31 # @param m represents the month number eg: 1-12 # @param y represents the yea number eg: 2020 def __init__(self, d, m, y): self.d = d self.m = m self.y = y ## @brief A getter method for the day number. # @details Assumptions: None # @return The day number def day(self): return self.d ## @brief A getter method for the month number. # @details Assumptions: None # @return The month number def month(self): return self.m ## @brief A getter method for the year number. # @details Assumptions: None # @return The year def year(self): return self.y ## @brief A method to provide the next day. # @details Assumptions: Leap years occur every 4 years. # @return The day after the current object def next(self): if (self.m == 2) and (self.d == 28) and (self.y % 4 != 0): nextDate = DateT(1, self.m+1, self.y) elif ((self.m == 1) or (self.m == 3) or (self.m == 5) or (self.m == 7) or (self.m == 8) or (self.m == 10) or (self.m == 12)) and (self.d == 31): nextDate = DateT(1, self.m+1, self.y) if (nextDate.m == 13): nextDate.m = 1 nextDate.y += 1 elif ((self.m == 4) or (self.m == 6) or (self.m == 9) or (self.m == 11)) and (self.d == 30): nextDate = DateT(1, self.m+1, self.y) else: nextDate = DateT(self.d+1, self.m, self.y) return nextDate ## @brief A method to provide the previous day # @details Assumptions: Leap years occur every 4 years # @return The day before the current object def prev(self): if (self.d == 1): prevDate = DateT(self.d, self.m-1, self.y) if prevDate.m == 0: prevDate.m = 12 prevDate.y -= 1 prevDate.d = 31 elif (prevDate.m == 1) or (prevDate.m == 3) or (prevDate.m == 5) or (prevDate.m == 7) or (prevDate.m == 8) or (prevDate.m == 10) or (prevDate.m == 12): prevDate.d = 31 elif (prevDate.m == 2): if (prevDate.y % 4 == 0): prevDate.d = 29 else: prevDate.d = 28 else: prevDate.d = 30 else: prevDate = DateT(self.d-1, self.m, self.y) return prevDate ## @brief A method to provide whether the day provided is before the current day # @details Assumptions: None # @param d represents the day to be compared # @return True if the day is before the current day, false if the day is not before the current day def before(self, d): if (self.y < d.y): return True elif (self.m < d.m) and (self.y == d.y): return True elif (self.d < d.d) and (self.m == d.m): return True return False ## @brief A method to provide whether the day provided is after the current day # @details Assumptions: None # @param d represents the day to be compared # @return True if the day is after the current day, false if the day is not after the current day def after(self, d): if (self.y > d.y): return True elif (self.m > d.m) and (self.y == d.y): return True elif (self.d > d.d) and (self.m == d.m): return True else: return False ## @brief A method to provide whether the day provided is equal to the current day # @details Assumptions: A day is equal to another day if and only if they are the same day. # @param d represents the day to be compared # @return True if the day is equal to the current day, false if the day is not equal to the current day def equal(self, d): if (self.y == d.y) and (self.m == d.m) and (self.d == d.d): return True else: return False ## @brief Adds a specific number of days to a DateT objects # @details Assumptions: None # @param n represents the number of days to be added # @return The date after n days have been added to the DateT object def add_days(self, n): date = datetime.date(self.y, self.m, self.d) newDate = date + datetime.timedelta(days = n) newerDate = DateT(newDate.day, newDate.month, newDate.year) return newerDate ## @brief Calculates the difference in days between two dates # @details Assumptions: There are no things such as negative days, and so the value returned is always the absolute value. # @param d represents a date # @return The difference betweent the date object and d in days def days_between(self, d): currentDate = datetime.date(self.y, self.m, self.d) dDate = datetime.date(d.y, d.m, d.d) diff = currentDate - dDate return abs(diff.days) ## @citations https://www.programiz.com/python-programming/datetime
03445409fffb4f660a6630e0a6cceba20a8a8feb
otaviomatheus07/BlueTurma2B-mod1
/Modulo-1/projetoTeste01.py
2,289
4.1875
4
# Proposta de projeto de ficção interativa para avaliação de OO # Sugestão: completar com classes filhas colocando pessoas saudáveis, # trabalhos menos remunerados, casas melhor equipadas et cetera # Classe para a criação do objeto tipo relógio para iteração de tempo no programa; class Relogio: def __init__(self): # Construtor padrão com dois atributos assumidos; self.horas = 7 self.minutos = 0 def __str__(self): # Método para retornar mensagem; return f"{self.horas:02d}:{self.minutos:02d}" def avancaTempo(self, minutos): # Método para validar minutos em horas e alterar os contadores de minutos e de horas; self.minutos += minutos while(self.minutos >= 60): self.minutos -= 60 self.horas += 1 def atrasado(self): # Método para definir o ponto (tempo) para o inicio do atraso; return (self.horas > 8 or (self.horas == 8 and self.minutos > 0)) # Teste de alterações; tempo = Relogio() tempo.avancaTempo(60) tempo.atrasado() print(vars(tempo)) # classe paar criação do personagem; class Personagem: def __init__(self,nome): self.nome = nome self.nivel = "Junior" self.sujo = True self.fome = True self.medicado = False self.dinheiro = 0 self.salario = 100 def __str__(self): return f"Olá {self.nome} Você é um Programador {self.nivel} e acaba de ingressar á equipe Blue Edtech. Você está " + ("sujo" if self.sujo else "limpo")+", "+("com" if self.fome else "sem")+" fome e "+("" if self.medicado else "não ")+"tomou sua medicação. Você tem "+str(self.dinheiro)+" reais na sua conta." def dormir(self): self.sujo = True self.fome = True self.medicado = False # Teste de alterações; programador = Personagem("Janio") programador.dormir() print(vars(programador)) # Classe para armazenar quantidade de alimentos na dispensa da casa; class Dispensa: def __init__(self, remedios, cafe, almoco, jantar): self.remedios = remedios self.cafe = cafe self.almoco = almoco self.jantar = jantar # Teste de alterações; refeicoes = Dispensa(1, 1, 1, 1)
a003683c8bd5b925f79102b55d09dd5146d96531
M1c17/ICS_and_Programming_Using_Python
/Week5_Object_Oriented_Programming/Practice_Problems/__iter__,__next vs generator.py
851
3.75
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Feb 5 13:33:43 2019 @author: MASTER """ #write a clas with functions __iter__ & __next__ #powertwo class PowTwo: def __init__(self, max = 0): self.max = max def __iter__(self): self.n = 0 return self def __next__(self): if self.n > self.max: raise StopIteration result = 2 ** self.n self.n += 1 return result P1 = PowTwo(5) print((P1.__iter__())) print() print(next(P1)) print(next(P1)) print(next(P1)) print(next(P1)) print(next(P1)) #write a code with generator def PowTwo(max_N = 0): n = 2 while n < max_N: result = 2 ** n yield result n += 2 P2 = PowTwo(5) print(next(P2)) print(next(P2)) #print(next(P2)) #print(next(P2))
c00e8df850ec9aee140f32d4975c56e3cbd476f9
MattyMatiss/stuff
/Graphy/1.py
362
3.515625
4
>>> import numpy as np >>> a = np.arange(15).reshape(3, 5) >>> a array([[ 0, 1, 2, 3, 4], [ 5, 6, 7, 8, 9], [10, 11, 12, 13, 14]]) >>> a.shape (3, 5) >>> a.ndim 2 >>> a.dtype.name 'int64' >>> a.itemsize 8 >>> a.size 15 >>> type(a) <type 'numpy.ndarray'> >>> b = np.array([6, 7, 8]) >>> b array([6, 7, 8]) >>> type(b) <type 'numpy.ndarray'>
15d3c4ac27417f65b7913f058f902f8d6bb4093a
JazzikPeng/Algorithm-in-Python
/drunk_man_on_plane.py
413
3.71875
4
# mad man problem import numpy as np def rand(a, b): return np.random.randint(a, b+1, dtype=int) def mad_man(num): a = rand(1, num) # print(a) if a == 1 or num == 1: return True elif a == num: return False else: return mad_man(num+1-a) counter = 0 trials = 100000 for i in range(trials): if mad_man(3) == True: counter += 1 print(counter / trials)
d9f0e568a00d64cabf6e6df0170ae3e34aa09a8b
jiangjinjinyxt/crack_leetcode
/P0046.py
979
3.515625
4
""" problem 46: Permutations https://leetcode.com/problems/permutations/ solution: """ class Solution(object): def permute(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ if not nums: return [[]] else: return [[value] + i for idx, value in enumerate(nums) for i in self.permute(nums[:idx] + nums[idx+1:])] class Solution(object): def permute(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ length = len(nums) result = [] def helper(ans): if len(ans) == length: result.append(ans.copy()) else: for value in nums: if value not in ans: ans.append(value) helper(ans) ans.pop() helper([]) return result
24e5bd22ffb54d36623f423cab8ccaec95007a67
ThomL69/petits-jeux-Python
/carrés-magiques/magic-escalier.py
3,949
3.84375
4
#! /usr/bin/python # -*- coding: utf-8 -*- """ Carrés magiques =============== Ce programme génère des carrés magiques de taille quelconque mais impaire en utilisant la méthode diagonale décrite à la page : http://villemin.gerard.free.fr/Wwwgvmm/CarreMag/aaaMaths/Diagonal.htm Un carré magique est un carré de nombres dans lequel les sommes des nombres de chaque rangée, de chaque colonne et des deux diagonales sont égales. L'ordinateur demande la taille, seuls les nombres impairs sont acceptés. """ class carreMagique: def __init__(self, taille): self.taille = taille self.tableau = [[0 for x in range(taille)] for x in range(taille)] def calcule_carre(self): ligne = 1 col = 3 for valeur in range(1, (taille)**2+1): collision = False while(not self.setXYSafe(ligne, col, valeur)): #Debug print("Collision en {},{}".format(ligne,col)) if collision: ligne += 1 else: collision =True ligne += 2 col -= 1 if ligne <= 0: ligne = self.taille if col <= 0: col = self.taille if ligne > self.taille: ligne = 1 if col > self.taille: col = 1 else: ligne -= 1 col += 1 if ligne <= 0: ligne = self.taille if col <= 0: col = self.taille if ligne > self.taille: ligne = 1 if col > self.taille: col = 1 #Debug print("=> {},{}".format(ligne, col)) def affiche_carre(self): print("-"*30) compteur = 0 for i in range(1,self.taille + 1): compteur += self.getXY(i, 6-i) print(" {:>2d} =".format(compteur)) print("-"*30) compteur = 0 for ligne in range(1, self.taille + 1): print(" {:>2d}".format(ligne), end=" : ") for col in range(1, self.taille +1): print("{:>2d}".format(self.getXY(ligne, col)), end=" ") compteur += self.getXY(ligne, col) print(" = {}".format(compteur)) compteur = 0 print("-"*30) print(" : ", end='') compteur = 0 for col in range(1, self.taille + 1): for ligne in range(1, self.taille +1): compteur += self.getXY(ligne, col) print(compteur, end=" ") compteur = 0 compteur = 0 for i in range(1,self.taille + 1): compteur += self.getXY(i, i) print(" = {}".format(compteur)) print("-"*30) def getXY(self, x, y): x = x - 1 y = y - 1 return self.tableau[x][y] def setXY(self, x , y, valeur): print("Je mets {} en {},{}".format(valeur, x, y)) x = x - 1 y = y - 1 self.tableau[x][y] = valeur def setXYSafe(self, x , y, valeur): #Debug print("Je mets {} en {},{}".format(valeur, x, y)) x = x - 1 y = y - 1 if self.tableau[x][y] == 0: self.tableau[x][y] = valeur return True else: return False def choix_taille(): taille = 0 print("Choisissez la taille du carré") while (taille%2 == 0): taille = int(input("Entrez un nombre impair ==> ")) print("Calcul d'un carré de {}x{}".format(taille,taille)) return taille # Le programme commence ici if __name__ == "__main__": print("") print("Carrés magiques") print("===============") print("") taille = choix_taille() mon_carre = carreMagique(taille) mon_carre.calcule_carre() mon_carre.affiche_carre()
736d45eee55054c04be38e99104050af252647c3
Umid221/python-sariq-dev
/funksiyalar/#20 QIYMAT QAYTARUVCHI FUNKSIYA/#20 QIYMAT QAYTARUVCHI FUNKSIYA.py
957
3.703125
4
def malumotlar(ism, familiya, tug_yil, email, tug_joy='', tel_raqam=None): """Mijoz haqidagi ma'lumotlarni lug'at ko'rinishida qaytaruvchi funksiya""" mijoz = {'ism':ism, 'familiya':familiya, 'tug_yil':tug_yil, 'yosh':2021-tug_yil, 'email':email, 'tug_joy':tug_joy, 'tel_raqam':tel_raqam} return mijoz mijozlar = [] while True: ism = input('ismingizni kiriting: ') familiya = input('familiyangizni kiriting: ') tug_yil = int(input("Tug'ilgan yilingizni kiriting: ")) email = input("emailingizni kiriting: ") tug_joy = input("Tug'ilgan joyingizni kiriting: ") tel_raqam = input("Telefon raqamingizni kiriting: ") m = malumotlar(ism, familiya, tug_yil, email, tug_joy, tel_raqam) mijozlar.append(m) keyingisi = input("keyingisini kiritasizmi(ha/yo'q)? ") if keyingisi != 'ha': break for mijoz in mijozlar: print(mijoz)
748704c0c9541bc806cac9489eeaf4caa015dbbf
xFelipe/Estudos-Python
/1.py
312
3.734375
4
min=int(input("Quantidade de minutos gastos é de:")) if min<200: print ("A conta está no valor de R$:%6.2f" % (min*0.20)) else: if min<400: print ("A conta está no valor de R$:%6.2f" % (min*0.18)) else: print ("A conta está no valor de R$:%6.2f" % (min*0.15))
251ed6b10574b3e8817b6b1eaa15badf05cc05d5
Ekeopara-Praise/python-challenge-solutions
/Ekeopara_Praise/Phase 2/DATA STRUCTURES/Day58 Tasks/Task2.py
479
4.6875
5
'''2. Write a Python program to iterate over an enum class and display individual member and their value. Expected Output: Afghanistan = 93 Albania = 355 Algeria = 213 Andorra = 376 Angola = 244 Antarctica = 672 ''' import enum class Member(enum.Enum): Afghanistan = 93 Albania = 355 Algeria = 213 Andorra = 376 Angola = 244 Antarctica = 672 for i in (Member): print(f"Member name: {i.name}") print(f"Member value: {i.value}") print("")
b1c15ad16e5fec9a2587a4d96b40714050e22676
jjc521/E-book-Collection
/Python/Python编程实践gwpy2-code/code/loop/shrinking_list.py
300
3.921875
4
def remove_neg(num_list): """ (list of number) -> NoneType Remove the negative numbers from the list num_list. >>> numbers = [-5, 1, -3, 2] >>> remove_neg(numbers) >>> numbers [1, 2] """ for item in num_list: if item < 0: num_list.remove(item)
c0a7782db7cfc40543bf6fabd654947822965b17
saichandra172/SAIRAM17
/sairam.py
385
3.609375
4
Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:06:47) [MSC v.1914 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> import random >>> print("hello sai") hello sai >>> i=1 >>> for i in range(1,10): num=random.randint(1,10) print("enter ur guess") guess=urguess() if(guess==num): print("correct") else: print("no") [
7240b93e0854b1fe20716757a01248064e0a0867
spbgithub/projecteuler
/pe077.py
741
3.765625
4
'''Prime summations Problem 77 It is possible to write ten as the sum of primes in exactly five different ways: 7 + 3 5 + 5 5 + 3 + 2 3 + 3 + 2 + 2 2 + 2 + 2 + 2 + 2 What is the first value which can be written as the sum of primes in over five thousand different ways? ''' from num_theo import get_primes_n primes = get_primes_n() cache = {(2,2):1} def parts(n, p): if (n, p) == (2, 2): print("hi") if (n, p) in cache: return cache[(n, p)] if n < p: return 0 if n == p: return 1 retval = 0 for q in primes: if q > p: break retval += parts(n - p,q) cache[(n,p)] = retval return retval num = 3 qty = 0 while True: qty = sum([parts(num, p) for p in primes if p <= num]) if qty > 5000: print(num) break num +=1
3a3d6411512e24600062c9e4aab94ece846d2ad3
donc1everon/Algorithm
/les01/task_4.py
1,647
3.765625
4
# Задание - 4 # Написать программу, которая генерирует в указанном # пользователем диапазоне: # ● случайное целое число, # ● случайное вещественное число, # ● случайный символ. # Для каждого из трех случаев пользователь задает свои границы # диапазона. Если надо получить случайный символ от 'a' до 'f', # вводятся эти символы. Программа должна вывести на экран любой # символ алфавита от 'a' до 'f' включительно. # # Блок - схема # https://drive.google.com/file/d/1XCeHXRVWjGCsBVBxou9q1J_v8pEI1rSk/view?usp=sharing import random print('Введите начало и конец диапозона:') print('- Целые числа') print('- Вещественные числа') print('- Символы') n = input('n = ') m = input('m = ') if n.isdigit() and m.isdigit(): n = int(n) m = int(m) rand_num = random.randint(n, m) print(f'Случайное число в вашем диапозоне - {rand_num}') elif n.isalpha() and m.isalpha(): n = ord(n) m = ord(m) rand_num = random.randint(n, m) rand_sym = chr(rand_num) print(f'Случайный символ в вашем диапозоне - {rand_sym}') else: n = float(n) m = float(m) rand_num = random.uniform(n, m) print(f'Случайное число в вашем диапозоне - {rand_num}')
56b1477d4dccedf0cae6ddd83d0eb6c809648de0
Rakaneth/truesteel-text
/equip.py
901
3.59375
4
from dataclasses import dataclass from typing import Tuple, Optional @dataclass class DurableItem: """Represents an item that has durability.""" durability: int max_dur: int name: str def restore(self): self.durability = self.max_dur @property def is_broken(self) -> bool: return self.durability <= 0 @property def is_destroyed(self) -> bool: return self.durability <= -self.max_dur def __str__(self): return f"{self.name} {self.durability}/{self.max_dur}" @dataclass class ArmorStats(DurableItem): """Represents armor stats.""" defense: int @dataclass class WeaponStats(DurableItem): """Represents weapon stats.""" damage: str crit: Optional[str] = None atp: int=0 @dataclass class ImplementStats(DurableItem): """Represents a magic implement.""" pwr: int damage: str
2b67d762094e4dcca120c916628c1b4ff64aa71e
96no3/PythonStudy
/Python/201911/191121/2019112104.py
385
3.765625
4
from turtle import * textinput("入力してください","name") # 入力ダイアログ(str型) numinput("入力してください","number") # 入力ダイアログ(float型) while True: s = textinput("input","cmd") if s == "end": break forward(int(s)) left(90) onscreenclick(lambda *x:print(x)) # マウスで左クリックした座標を表示
4fe5c5f7400e5dfd560aca34dc916743be85abc2
nocommentcode/MachineLearning
/ReinforcementLearning/TabularRL/GridWorld.py
4,118
3.5625
4
class Grid: def __init__(self, rows, cols, start_pos, max_moves=300): self.max_moves = max_moves self.rows = rows self.cols = cols self.rewards = [[0 for _ in range(rows)] for _ in range(cols)] self.walls = [[False for _ in range(rows)] for _ in range(cols)] self.terminals = [] self.starting_pos = start_pos self.player_pos = start_pos self.moves = 0 """ Makes cell at loc a terminal cell """ def set_as_terminal(self, loc): self.terminals.append(loc) """ Makes cell at loc a wall """ def set_as_wall(self, loc): self.walls[loc[0]][loc[1]] = True """ Reset game """ def reset_game(self): self.player_pos = self.starting_pos self.moves = 0 """ Makes cell at loc have reward """ def set_reward(self, loc, reward): self.rewards[loc[0]][loc[1]] = reward """ Play Turn returns reward for next state """ def play_turn(self, action): new_pos = self.get_next_state(self.player_pos, action) self.player_pos = new_pos self.moves += 1 return self.get_reward(new_pos) """ Returns current state """ def get_current_state(self): return self.player_pos """ Returns state if action is taken """ def get_next_state(self, state, action): x = state[0] y = state[1] if action not in self.get_actions(state): raise Exception("{} is not allowed".format(action)) if action == "L": x -= 1 elif action == "R": x += 1 elif action == "D": y -= 1 elif action == "U": y += 1 return [x, y] """ Returns legal actions at state """ def get_actions(self, pos): actions = [] x = pos[0] y = pos[1] # left if x - 1 >= 0 and not self.walls[x - 1][y]: actions.append("L") # right if x + 1 <= self.cols - 1 and not self.walls[x + 1][y]: actions.append("R") # down if y - 1 >= 0 and not self.walls[x][y - 1]: actions.append("D") # up if y + 1 <= self.rows - 1 and not self.walls[x][y + 1]: actions.append("U") return actions """ returns list of [x,y] states """ def get_all_states(self): states = [] for x in range(self.cols): for y in range(self.rows): if not self.walls[x][y]: states.append([x, y]) return states """ returns reward at loc """ def get_reward(self, loc): return self.rewards[loc[0]][loc[1]] """ True is cell at loc is a wall """ def is_wall(self, loc): return self.walls[loc[0]][loc[1]] """ True is cell at loc is a terminal cell """ def is_terminal(self, loc): return loc in self.terminals """ :returns True if game is over """ def game_over(self): return self.player_pos in self.terminals or self.moves >= self.max_moves # --------- PRIVATES ------------- def find_occupier(self, loc): x = loc[0] y = loc[1] if self.player_pos == loc: return "X" if self.walls[x][y]: return "_" if loc in self.terminals: return "T" return " " def __str__(self): output = "" output += " " for _ in range(self.cols): output += " ___" output += "\n" for r in range(self.rows - 1, -1, -1): output += "{} ".format(r) for c in range(self.cols): output += "| {} ".format(self.find_occupier([c, r])) output += "|\n" output += " " for c in range(self.cols): output += "|___" output += "|\n" output += " " for i in range(self.cols): output += " {} ".format(i) output += "\n" return output
d41501caa3b9eb3e6952865cf16bddb60058f65a
AnkitJ9977/Python-Lab
/strings.py
984
4
4
Python 3.9.6 (tags/v3.9.6:db3ff76, Jun 28 2021, 15:26:21) [MSC v.1929 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license()" for more information. >>> print("Hello") Hello >>> print('Hello') Hello >>> a = "Hello" >>> print(a) Hello >>> a = """My Name is Ankit jaiswal.""" >>> print(a) My Name is Ankit jaiswal. >>> a = '''My Name is Ankit jaiswal.''' >>> print(a) My Name is Ankit jaiswal. >>> a = "Hello, World" >>> print(a[1]) e >>> a = "Hello, World" >>> print(len(a)) 12 >>> txt = "The best things in life are free" >>> print("free" in txt) True >>> KeyboardInterrupt >>> txt = "The best things in life are free" >>> if "free" in txt: ... print("Yes, 'free' is present.") ... Yes, 'free' is present. >>> txt = "The best things in life are free" >>> print("expensive" not in txt) True >>> txt = "The best things in life are free" >>> if "expensive" not in txt: ... print("No, 'expensive' is NOT present.") ... No, 'expensive' is NOT present. >>>
56ba37002dd5f1110faf5204d0800ce6e9a477ca
abhaysinh/Data-Camp
/Cleaning Data with PySpark/Cleaning Data with PySpark/01- DataFrame details/02-Defining a schema.py
882
4.09375
4
''' Defining a schema Creating a defined schema helps with data quality and import performance. As mentioned during the lesson, we'll create a simple schema to read in the following columns: Name Age City The Name and City columns are StringType() and the Age column is an IntegerType(). Instructions 100 XP Import * from the pyspark.sql.types library. Define a new schema using the StructType method. Define a StructField for name, age, and city. Each field should correspond to the correct datatype and not be nullable. ''' # Import the pyspark.sql.types library from pyspark.sql.types import * # Define a new schema using the StructType method people_schema = StructType([ # Define a StructField for each field StructField('name', StringType(), False), StructField('age', IntegerType(), False), StructField('city', StringType(), False) ])
59f4eb576b0e51986054c1078293e93c67c02bc9
Alejo2040/Algoritmos_programacion_C4G2
/Taller estructuras de control secuenciales/Ejercicio 9.py
318
3.828125
4
""" Entradas Horas trabajadas-->int-->H_T Precio de la hora-->int-->P_h Salidas Salario neto-->int-->S_n """ #Entradas P_h=float(input("Precio por cada hora trabajada: ")) H_t=int(input("Numero de horas trabajadas: ")) #Caja negra S=float((H_t*P_h)) S_n=int((S-S*0.20)) #Salida print("El salario neto es de:",S_n)
74876199388e33c4a9d73abcc6d285fae90630b4
FelpsFon/curso_python
/revisao/8_list.py
285
4.28125
4
# conceito de indexamento numerico # listas, estruturas de dados lineares, que permitem todas as operações, (criar, remover, atualizar, mover) lista = [0,1,2,3,4,5,6] # começa em 0 print(lista[5]) lista.append(8) lista.append(8) print(lista) for item in lista: print(item)
f45e10a409eead2c530000e85fd870a22de044a8
siddheshmhatre/Algorithms
/Sorting/quicksort.py
602
3.671875
4
import random def partition(A,l,r): piv = random.randint(l,r) temp = A[l] A[l] = A[piv] A[piv] = temp i = l + 1 for j in range(l+1,r+1): if A[j] < A[l]: temp = A[i] A[i] = A[j] A[j] = temp i = i + 1 temp = A[i-1] A[i-1] = A[l] A[l] = temp return i-1 def quicksort (A,l,r): if r<l: return else: pos = partition(A,l,r) quicksort(A,l,pos-1) quicksort(A,pos+1,r) if __name__ == "__main__": # Generate 10 random numbers unsorted = [] for i in range(10): unsorted.append(random.randint(0,100)) print unsorted quicksort(unsorted,0,len(unsorted)-1) print unsorted
b8dc76a17cd2f465a00d54f5cf2e7bdd13f4003b
ck564/HPM573S18_Kong_HW3
/HW3_P1.py
1,587
4.09375
4
# HW 3 Problem 1 class Patient: """base class""" def __init__(self, name): self.name = name def discharge(self): raise NotImplementedError ("This is an abstract method and needs to be implemented in derived classes.") class EmergencyPatient(Patient): def __init__(self, name): Patient.__init__(self, name) self.expected_cost = ED_cost def discharge(self): print("Discharged:", self.name, ", ED") class HospitalizedPatient(Patient): def __init__(self, name): Patient.__init__(self, name) self.expected_cost = hospitalized_cost def discharge(self): print("Discharged:", self.name, ", Hospitalized") class Hospital: def __init__(self): self.patients = [] self.costs = 0 def admit(self, Patient): self.patients.append(Patient) def discharge_all(self): for Patient in self.patients: Patient.discharge() self.costs += Patient.expected_cost def get_total_cost(self): return self.costs # Hospital patient costs ED_cost = 1000 hospitalized_cost = 2000 # Patients P1 = EmergencyPatient("Sally") P2 = EmergencyPatient("John") P3 = EmergencyPatient("Wayne") P4 = HospitalizedPatient("Claire") P5 = HospitalizedPatient("Everleigh") # Admitting patients Hospital1 = Hospital() Hospital1.admit(P1) Hospital1.admit(P2) Hospital1.admit(P3) Hospital1.admit(P4) Hospital1.admit(P5) # Discharging patients Hospital1.discharge_all() # Calculating total cost print("Total operating cost: $", Hospital1.get_total_cost())
575e1a8d94dd1e94f3a3a4ee095a7aefaaa24f1e
tzookb/x-team-exercises
/sprints/hashmaps/elie/two_strings.py
368
3.8125
4
# https://www.hackerrank.com/challenges/two-strings/problem def two_strings(s1, s2): hash = {s: True for s in s1} for s in s2: if hash.get(s): return 'YES' return 'NO' if __name__ == '__main__': q = int(raw_input()) for _ in xrange(q): s1 = raw_input() s2 = raw_input() print two_strings(s1, s2)
810ecb5d63ab8e3306e86750c9beb3c59b691265
havertok/misc
/Oa2_CellState.py
697
3.546875
4
#Solution to https://aonecode.com/amazon-online-assessment-oa2-cell-state-after-n-days numDays = 2; passedDays = 0; base = [1, 1, 1, 0, 1, 1, 1, 1]; altered = base.copy(); def getNewBit(x, y): if x == y: return 0; else: return 1; while(passedDays < numDays): index = 0; for num in base: if index == 0: altered[index] = getNewBit(0, base[index + 1]); elif index == len(base)-1: altered[index] = getNewBit(base[index - 1], 0); else: altered[index] = getNewBit(base[index - 1], base[index + 1]); index += 1; base = altered.copy(); print(altered, ' day:', passedDays); passedDays += 1;
be13bc28ddfda802e4914e931c73d86d5a7e8c6f
nsaylan/GlobalAIHubPythonCourse
/Quiz/quiz3.py
1,265
3.515625
4
#myList = [1,5,7,23,8,34,8,9,234,523,345] #max_list = myList[0] #indexOfMax = 0 #for i in range(1, len(myList)): # if myList[i] > max_list: # max_list = myList[i] # indexOfMax = i #print(indexOfMax) #randomDict = {1:"1", 2:["1", "2"], 3:["1", "2", "3"]} #for key, value in randomDict.items(): # for v in value: # print(v, end=" ") #customTuple = (10,20,40,30,50) #customTuple = customTuple[::-1] #for i in customTuple: # print(i, end=" ") #def change(customList): # customList[0] = 0 # customList.append(1) # return customList #randomList = [1,2,3,4,5,6] #print(change(randomList)) #D = {1:1, 2:"2", "1":2, "2":3} #D["1"] = 2 #print(D[D[D[str(D[1])]]]) #customDict = {i:i*i for i in range(5)} #print(customDict) #givenList = [x if x%2 else x*100 for x in range(1,5)] #print(givenList) #givenList = [5,4,6,6,3,7,7,2,0,8,5,7,7,3,3,6,2,2,2,1] #currentMax = givenList[0] #for i in givenList: # if i>currentMax: # currentMax = i #print(currentMax) #randomDict = {1:1, 2:"2", 3:"3", 4:4, 5:"5"} #for key, value in randomDict.items(): # if key == value: # print(key, end=" ") #randomDict = {1:1, 2:"2", 3:"3", 4:4, 5:"5", "1":1} #randomDict.pop(1) #randomDict.pop(1) #randomDict.pop(2) #print(randomDict)
7c0658ccf0f26d096b41924d4f3a52c816a0e5a3
upupupa/hillelHomeWork
/HW2/1.py
377
3.5625
4
#!/usr/bin/python3 # -*- encoding: utf-8 -*- def countsymbol(): s = "spam and eggs or eggs with spam" sL = list(s) sD = {} freq = 0 for i in range(0, len(sL)): sD[sL[i]] = 0 for i in range(0, len(sL)): if sL[i] in sL: freq = sD[sL[i]] + 1 sD[sL[i]] = freq print(sD) if __name__ == "__main__": countsymbol()
c17cf418190c92b822ac893acd9418351032a330
margaritamikitenko/amis_python71
/km71/Mykytenko_Marharyta/4/task10.py
236
3.96875
4
x1 = int(input()) y1 = int(input()) x2 = int(input()) y2 = int(input()) if x2 - x1 == y2 - y1: print('YES') elif x2 - x1 == y1 - y2: print('YES') elif (x1 == x2) or (y1 == y2): print('YES') else: print('NO')
b7f13f3e644bfccacb4eb7dd137cc6a4151c5423
marshalwang05/Year_10_Design
/Demo_Programs/loops.py
232
3.90625
4
for i in range (0,101,1): print(i) for i in range (-4, 63, 1): print(i) for i in range (04, 63, 2): print(i) for i in range (7, 151, 2): print(i) for i in range (151, 7, -4): print(i) for i in range (1000,1,-2): print(i)
6ebc0ac8120fd3e177a3e93444e142d9bd7c80ff
1258488317/master
/python/example/total.py
251
3.703125
4
#!/usr/bin/python def total(initial=5,*numbers,**keywords): count=initial for number in numbers: count += number for key in keywords: count += keywords[key] return count print(total(10,1,2,3,vegetables=50,fruits=100))
b52909cb55b69ea276783ab32b20161f57e3338f
Naveen-kumar01/data-structure-and-algorithms
/pro1.py
1,797
4.25
4
class Node: def __init__(self, data): self.data = data # Assign data self.next = None # Initialize next as null class LinkedList: def __init__(self): self.head = None def push(self, new_data): new_node = Node(new_data) new_node.next = self.head self.head = new_node def insertAfter(self, prev_node, new_data): if prev_node is None: print("The given previous node must in LinkedList.") return new_node = Node(new_data) new_node.next = prev_node.next prev_node.next = new_node def append(self, new_data): new_node = Node(new_data) if self.head is None: self.head = new_node return last = self.head while (last.next): last = last.next last.next = new_node def printList(self): temp = self.head while (temp): print(temp.data,end="->") temp = temp.next def Count(self): temp=self.head c=0 while(temp != None): temp=temp.next c+=1 print() print("no. of element are ",c) def rotate(self, k): temp=self.head temp1=self.head temp2=self.head c=1 while(c <k and temp is not None): temp=temp.next c+=1 temp1= temp while(temp.next!=None): temp=temp.next temp2 = temp temp2.next= self.head self.head= temp1.next temp1.next=None if __name__=='__main__': l = LinkedList() l.append(6) l.push(7); l.push(1); l.append(4) l.insertAfter(l.head.next, 8) l.printList() l.rotate(2) print('Created linked list is:',) l.printList()
5175ced15a7e1eef49eb0a1effa03b26cd1578d8
Pulkit2699/Math-and-AI
/envelope_sim.py
2,446
4.1875
4
# -*- coding: utf-8 -*- """ Created on Sun Mar 1 19:29:53 2020 @author: pulki """ import random def pick_envelope(switch, verbose): #Randomly distribute the three black/one red balls into two envelopes set1 = ['b','b','b','r'] Envelope0 = random.sample(set1,2) if(verbose == True): print("Envelope 0:", end = " ") for i in range (len(Envelope0)): if(verbose == True): print(Envelope0[i], end = " ") Envelope1 = set1.copy() Envelope1.remove(Envelope0[0]) Envelope1.remove(Envelope0[1]) if(verbose == True): print() print("Envelope 1:", end = " ") for i in range (len(Envelope1)): print(Envelope1[i], end = " ") print() #Randomly select one envelope index = random.randint(0,1) if(verbose == True): if(index == 0): print("I picked envelope 0") elif(index == 1): print("I picked envelope 1") #Randomly select a ball from the envelope ballIndex = random.randint(0,1) if(index == 0): chosen = Envelope0[ballIndex] if(verbose == True): print("and drew a ", chosen) elif(index == 1): chosen = Envelope1[ballIndex] if(verbose == True): print("and drew a ", chosen) if(chosen == 'r'): return True if(switch): if(index == 1): index = 0 if(verbose == True): print("Switch to envelope 0") elif(index == 0): index = 1 if(verbose == True): print("Switch to envelope 1") if(index == 0): if 'r' in Envelope0: return True else: return False elif(index == 1): if 'r' in Envelope1: return True else: return False def run_simulation(n): print("After",n, "simulations:") trueCounter = 0 for i in range(n): check = pick_envelope(True, False) if(check): trueCounter = trueCounter + 1 print("Switch successful:", trueCounter/n * 100,"%") trueCounter = 0 for i in range(n): check = pick_envelope(False, False) if(check): trueCounter = trueCounter + 1 print("No-switch successful:", trueCounter/n * 100,"%")
6f0e1eb2cd5288ad9a80e5d89698f696a428c88f
Astony/Homeworks
/homework8/tests/test_for_ORM.py
1,514
3.859375
4
import os import sqlite3 import pytest from homework8.task02.DataBaseClass import TableData def test_of_len_method(create_db): """Check len of TableData's instance""" with TableData(create_db, "presidents") as presidents: assert len(presidents) == 3 def test_get_item_method(create_db): """Check the method of getting item from db in case when item exists""" with TableData(create_db, "presidents") as presidents: assert presidents["Obama"] == ("Obama", "America", 2) def test_contains_method(create_db): """Check contain method""" with TableData(create_db, "presidents") as presidents: assert "Putin" in presidents assert not "West" in presidents def test_iteration_method(create_db): """Check that iteration protocol is working via list comprehension""" with TableData(create_db, "presidents") as presidents: presidents_name_list = [president["name"] for president in presidents] assert presidents_name_list == ["Trump", "Obama", "Putin"] def test_not_existing_db(): """Check if db doesn't exists in a directory it will caused Error instead of creating new db""" with pytest.raises(IOError, match=f"No such db"): with TableData("abacaba", "president") as presidents: print("hello") def test_wrong_arguments(create_db): """Check that it will be an error then we input wrong argument""" with TableData(create_db, "presidents") as presidents: assert presidents["Murphy"] == []
a47ee75036bf86e093fd2754a94b3a61a28ecaae
Shashank979/Advent-Of-Code-Solutions
/AdventOfCode2020/Problem6/problem6_part1.py
253
3.703125
4
def main(): total_count = 0 file1 = 'input_problem6.txt' input_file = open(file1).read().split("\n\n") for group in input_file: group = len(set(group.replace('\n', ''))) total_count += group print(total_count) main()
9816666de614fd7fc09de9816f43cb838c698525
kthr3e/python3
/practice/7-2.py
130
3.671875
4
# 引数と戻り値を追加する def sum(x, y): return x + y num1 = sum(3, 4) print(num1) num2 = sum(300, 400) print(num2)
94b1727bff42c3096e0cd68f3b2d63c21ae9af91
Muscio97/AAI
/NN/flowers.py
9,468
3.734375
4
from math import exp from random import seed, random, shuffle import operator class Neuron: # Create neuron def __init__(self): self.delta = 0 self.last_output = 0 # 0 because of inheritance def get_output_val(self): return 0 # clear preveus leurned delta def clear_delta(self): self.delta = 0 # because of inheritance a child class will overwrite this section of code @staticmethod def derivative(output): return output * (1.0 - output) # because of inheritance def calculate_delta_for_inputs(self): pass # because of inheritance def update_weights(self, learnRate): pass # because of inheritance def get_weights(self): return [] class HiddenNeuron(Neuron): # Create Hidden neuron in network/ load weights in to the network def __init__(self, inputs, is_loading=False): super().__init__() if is_loading: self.inputs = [] self.bias_weight = inputs[-1][0] for w in inputs[:-1]: if len(w[1]) == 0: self.inputs.append([w[0], InputNeuron()]) else: self.inputs.append([w[0], HiddenNeuron(w[1], True)]) else: self.bias_weight = random() if issubclass(type(inputs), Neuron): weight = 0 self.inputs = [[weight, inputs]] elif type(inputs) is list: if issubclass(type(inputs[0]), Neuron): self.inputs = self.gen_weights(inputs) elif type(inputs[0]) is list: if issubclass(type(inputs[0][1]), Neuron): self.inputs = inputs # Returns activation of neuron def get_output_val(self): val = 0 for neuron in self.inputs: val += neuron[0] * neuron[1].get_output_val() val += self.bias_weight # self.last_output = max(0, val) self.last_output = 1.0 / (1.0 + exp(-val)) return self.last_output @staticmethod # Create random weights. def gen_weights(inputs): newinputs = [] for i in inputs: weight = random() newinputs.append([weight, i]) return newinputs # Clear the learned delta. def clear_delta(self): super().clear_delta() for i in self.inputs: i[1].clear_delta() # Calc delta def calculate_delta_for_inputs(self): for neuron in self.inputs: neuron[1].delta += (neuron[0] * self.delta) * self.derivative(neuron[1].last_output) neuron[1].calculate_delta_for_inputs() # Updates the current weights based on given delta. def update_weights(self, learnRate): for i in self.inputs: i[1].update_weights(learnRate) i[0] += learnRate * self.delta * i[1].last_output self.bias_weight += learnRate * self.delta # Return the weights (for saving the network). def get_weights(self): w = [] for i in self.inputs: w.append([i[0], i[1].get_weights()]) w.append([self.bias_weight, []]) return w # Return the inputs (for loading the network). def get_inputs(self): if type(self.inputs[0][1]) == InputNeuron: inputs = [] for i in self.inputs: inputs.append(i[1]) return inputs return self.inputs[0][1].get_inputs() class InputNeuron(Neuron): # Creates the nueron def __init__(self): super().__init__() self.val = 0 # returns the value of the input neuron. def get_output_val(self): return self.val # Sets the value of the input neuron. def set_val(self, val): self.last_output = val self.val = val class NN: # Creates the network voor a given neurons 'n'. def __init__(self, n=None): if n is None: n = [] if len(n) > 1: #checks if there is an in/out-put seed(1) self.inputs = [] for i in range(n[0]): self.inputs.append(InputNeuron()) self.outputs = self.inputs.copy() for i in n[1:]: self.add_layer(i) else: self.inputs = [] self.outputs = [] # Adds a layer with 'n' neurons to the network. def add_layer(self, n): newoutput = [] for i in range(n): newoutput.append(HiddenNeuron(self.outputs)) self.outputs = newoutput # Propegates back over the network and changes the weigths to be more fitting to the excptect output. def backward_propagation(self, expected): for output in self.outputs: output.clear_delta() for j in range(len(self.outputs)): neuron = self.outputs[j] error = (expected[j] - neuron.last_output) neuron.delta = error * neuron.derivative(neuron.last_output) for output in self.outputs: output.calculate_delta_for_inputs() # data_set: set of data to use as inputs # learn_set: set of data of the expected result of the network # learn_rate: # n_epoch: number of times to loop # print_errors: print the amount of error per epoch def train(self, data_set, learn_set, learn_rate=1.0, n_epoch=50, print_errors=False): for epoch in range(n_epoch): combined = list(zip(data_set, learn_set)) shuffle(combined) data_set[:], learn_set[:] = zip(*combined) error = 0 for t in range(len(data_set)): outputs = self.run(data_set[t]) for i in range(len(outputs)): error += (learn_set[t][i] - outputs[i]) ** 2 self.backward_propagation(learn_set[t]) for o in self.outputs: o.update_weights(learn_rate) if print_errors: print('>epoch=%d, learnRate=%.3f, error=%.3f' % (epoch, learn_rate, error)) # Runs the algorithme and returns the output of the network def run(self, input): if len(input) is not len(self.inputs): return None for i in range(len(input)): self.inputs[i].set_val(input[i]) out = [] for o in self.outputs: out.append(o.get_output_val()) return out # Tests the network on bases of the givven data set. Will return a value of centriy of corretness and the resulting correctness. def test(self, dataSet, learnSet, print_result=False): combined = list(zip(dataSet, learnSet)) shuffle(combined) dataSet[:], learnSet[:] = zip(*combined) averagep = 0 correct = 0 for i in range(len(dataSet)): out = self.run(dataSet[i]) p = 0 for j in range(len(out)): if learnSet[i][j] == 1: p += out[j] if learnSet[i][j] == 0: p -= out[j] index, value = max(enumerate(out), key=operator.itemgetter(1)) if learnSet[i][index] == 1: correct += 1 averagep += p * 100 if print_result: print("Test: ", end='') print(learnSet[i], end='\t') print("Output: ", end='') print(out, end='\t') print(round(p * 100, 3), end='%\n') return [round(averagep / len(dataSet), 3), (correct / len(dataSet)) * 100] # Saves all the weights to list and returns this list def save(self): w = [] for o in self.outputs: w.append(o.get_weights()) return w #loads neural network (with the givven weigths) def load(self, weights): for w in weights: self.outputs.append(HiddenNeuron(w, True)) self.inputs = self.outputs[0].get_inputs() # If this isn't a import if __name__ == "__main__": # then import numpy import numpy as numpy # Make classifactions def converter_type(s): s = s.decode("utf-8") r = [0] * 3 if s == "Iris-setosa": r[0] = 1 elif s == "Iris-versicolor": r[1] = 1 elif s == "Iris-virginica": r[2] = 1 return r # Set datasets dataSet = numpy.genfromtxt("flowers.csv", delimiter=",", usecols=[0, 1, 2, 3], converters={}) learnSet = numpy.genfromtxt("flowers.csv", delimiter=",", usecols=[4], converters={4: converter_type}) # Shuffel data set. combined = list(zip(dataSet, learnSet)) shuffle(combined) shuffle(combined) shuffle(combined) shuffle(combined) dataSet[:], learnSet[:] = zip(*combined) # Run this b* nn = NN([len(dataSet[0]), 5, len(learnSet[0])]) print("Total accuracy before learn: ", end='') print(nn.test(dataSet[round(len(dataSet) / 3):], learnSet[round(len(dataSet) / 3):], False), end='%\n') nn.train(dataSet[:round(len(dataSet) / 3)], learnSet[:round(len(dataSet) / 3)], 0.1, 300, False) print("Total accuracy after learn: ", end='') print(nn.test(dataSet[round(len(dataSet) / 3):], learnSet[round(len(dataSet) / 3):], False), end='%\n') nn2 = NN() nn2.load(nn.save()) print("Total accuracy after load: ", end='') print(nn2.test(dataSet[round(len(dataSet) / 3):], learnSet[round(len(dataSet) / 3):], False), end='%\n')
1f92c964e2f0c5c5a643bb724754c8258b803b8d
Yiif4n/CodingInterviews
/020-顺时针打印矩阵/020-printMatrix.py
1,379
3.703125
4
# -*- coding:utf-8 -*- class Solution: # matrix类型为二维列表,需要返回列表 def printMatrix(self, matrix): # write code here if len(matrix)==0: return [] up=-1 down=len(matrix) left=-1 right=len(matrix[0]) ans=[] direction=1 #向右:1 向下:2 向左:3 向上:4 i=0 j=0 for n in range(down*right): ans.append(matrix[i][j]) if direction==1 and j<right: j+=1 if j==right: j-=1 i+=1 direction=2 up+=1 continue if direction==2 and i<down: i+=1 if i==down: i-=1 j-=1 direction=3 right-=1 continue if direction==3 and j>left: j-=1 if j==left: j+=1 i-=1 direction=4 down-=1 continue if direction==4 and i>up: i-=1 if i==up: i+=1 j+=1 direction=1 left+=1 continue return ans
37fc84f254b4e7243419e951199a1b97baad6265
GabrielPurper/python-poo
/conteudo/tamagotchi-terminal/tamagotchi_sprite.py
479
3.53125
4
pequeno = """ === |o o| === """ medio = """ === |o o| | u | === """ grande = """ ===== | - - | o--| O O |--o | u | ===== """ def mostrar_sprite(dias_vida: int) -> str: if dias_vida < 5: sprite = pequeno elif 5 <= dias_vida < 10: sprite = medio else: sprite = grande return sprite
46b4cf56cc6b723c3a1877beb3722243eb315e12
vsvdevua/python_basic
/009_Samples/pep8_examples.py
1,506
3.78125
4
# import this # Beautiful is better than ugly. # bad example def MyLongNameIsForToDoSomething(a, b, c, d, e, f, g, x, y, t, v): pass # good example def get_time(): return "time is ..." # Explicit is better than implicit. # bad def get_args(a, b): s = sum([a, b]) squares = [x ** 2 for x in [s, s + 2, s + 5]] print(squares, 'hello') return squares[:1] # good def get_sum(a, b): return sum([a, b]) def get_squares(sum_result): return [x ** 2 for x in [sum_result, sum_result + 2, sum_result + 5]] def print_result(result): print(result, 'hello') def main(a, b): s = get_sum(a, b) squares = get_squares(s) print_result(squares) return squares[:1] # Simple is better than complex. # Complex is better than complicated. # Flat is better than nested. # Sparse is better than dense. # Readability counts. # Special cases aren't special enough to break the rules. # Although practicality beats purity. # Errors should never pass silently. # Unless explicitly silenced. # In the face of ambiguity, refuse the temptation to guess. # There should be one-- and preferably only one --obvious way to do it. # Although that way may not be obvious at first unless you're Dutch. # Now is better than never. # Although never is often better than *right* now. # If the implementation is hard to explain, it's a bad idea. # If the implementation is easy to explain, it may be a good idea. # Namespaces are one honking great idea -- let's do more of those!
3959490e4202a1274661fc6e99d93c67d1cfcca2
ivekhov/python-project-lvl1
/brain_games/engine.py
926
3.890625
4
"""Contains functions and constants for building game logic.""" import prompt ATTEMPT_COUNTS = 3 def play(game): """ Create boilerplate for game. Args: game: function with particular game. """ print('Welcome to the Brain Games!') print(game.DESCRIPTION) name = prompt.string(prompt='\nMay I have your name? ') print('Hello, {}!'.format(name)) print() for _ in range(0, ATTEMPT_COUNTS): question, correct = game.get_question_and_answer() print('Question: {}'.format(question)) answer = prompt.string(prompt='Your answer: ') if answer != correct: print("'{}' is wrong answer ;(.".format(answer), end=' ') print("Correct answer was {}".format(correct)) print("Let's try again, {}!".format(name)) return else: print('Correct!') print('Congratulations, {}!\n'.format(name))
1ebbba25d319277b029ae929d85cf9876e8d5134
abhisheksimhadri/test2
/test1/data/biggest_using_procedure.py
215
3.90625
4
def bigger(a,b): if a > b: return a return b def biggest(x,y,z): return bigger(bigger(x,y),z) print biggest(123,234,345) print biggest(2,1,3) print biggest(9,8,7) print biggest(5,2,3) print max(345,645,298)
7cd7239d32a206337b655304e8099940d26e5584
philosophicalusername/assignment_10-1
/file_info.py
1,890
4.5
4
# This week we will create a program that performs file processing activities. # Your program this week will use the OS library in order to validate that a directory # exists before creating a file in that directory. # Your program will prompt the user for the directory they would like # to save the file in as well as the name of the file. # The program should then prompt the user for their name, address, and phone number. # Your program will write this data to a comma separated line in a file and store # the file in the directory specified by the user. # Once the data has been written your program should read the file you # just wrote to the file system and display the file contents to the user for validation purposes. import os import csv user_filepath = input('Where would you like to store the file?') user_filename = input('What would you like to name the file?') full_filepath_filename = user_filepath + user_filename user_name = input('What is your name? ') user_address = input('What is your address? ') user_phone = input('What is your phone number? ') with open(user_filename, mode='a') as user_filename: fieldnames = ['Name', 'Address', 'Phone'] user_writer = csv.DictWriter(user_filename, fieldnames=fieldnames) user_writer.writeheader() user_writer = csv.writer(user_filename, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL) user_writer.writerow([user_name, user_address, user_phone]) print("Your information has been save in: ", full_filepath_filename) with open(full_filepath_filename, mode='r') as csv_file: csv_reader = csv.DictReader(csv_file) line_count = 0 for row in csv_reader: if line_count == 0: print(f'Column names are {", ".join(row)}') line_count += 1 print(f'\t{row["Name"]} lives at {row["Address"]} and their number is {row["Phone"]}.') line_count += 1
375bbb71ee8ffb14112853b3bb7a803a9e2d58f0
sowmiyashakthi/python-prgm
/beginner/power of n number.py
245
4.53125
5
number = int(input(" Enter the positive integer ")) exponent = int(input("Enter the exponent integer ")) power = 1 for i in range(1, exponent + 1): power = power * number print("result of {0} power {1} = {2}".format(number, exponent, power))
0a7bc98ae4a29b2b343c2e9ae9574786ce9f858b
lfdyf20/Leetcode
/Reverse Linked List II.py
1,329
3.90625
4
# Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def reverseBetween(self, head, m, n): """ :type head: ListNode :type m: int :type n: int :rtype: ListNode """ if m >= n: return head ohead = dummy = ListNode(0) whead = wtail = head dummy.next = head for _ in range(n-m): wtail = wtail.next for _ in range(m-1): ohead, whead, wtail = ohead.next, whead.next, wtail.next otail, wtail.next = wtail.next, None revhead, revtail = self.reverse(whead) ohead.next, revtail.next = revhead, otail return dummy.next def reverse(self, head): pre, curr, tail = None, head, head while curr: curr.next, pre, curr = pre, curr, curr.next return pre, tail # show nodes.val in the linked list def showLinkedList(head): while head: print(head.val, end='') head = head.next print('') # generate linked list from list x = [1,2,3,4,5] if not x: head = None else: head = curr = ListNode(x[0]) for i in x[1:]: curr.next = ListNode(i) curr = curr.next m, n = 2,4 sl = Solution() head = sl.reverseBetween(head,m,n) showLinkedList(head)
25e084138f4585ddc0ad858f554f015f71f77fca
WayraLHD/SRA21
/python/0/pla.py
6,393
4.1875
4
import random as ra #Importa librerias import numpy as np #TODO ESTE CODIGO ES DIDACTICO #Tomar como ejemplo para ver la sintaxis de python class planilla: #Define una clase "Las clases proveen una forma de empaquetar datos y funcionalidad juntos.\ Al crear una nueva clase, se crea un nuevo tipo de objeto, permitiendo crear \ nuevas instancias de ese tipo. Cada instancia de clase puede tener atributos \ adjuntos para mantener su estado. Las instancias de clase también pueden tener\ métodos (definidos por su clase) para modificar su estado . \ En Python todo es un objeto. Cuando creas una variable y le \ asignas un valor entero, ese valor es un objeto; una función es un objeto;\ las listas, tuplas, diccionarios, conjuntos, … son objetos; \ una cadena de caracteres es un objeto. " "En este caso esta clase crea objetos que tienen un diccionario como variable global \ planilla.Planilla_ " "planilla.crear_planilla() es un metodo para cargar Planilla_ a mano" "etc.." # Planilla_ ={'':[]} def __init__(self,*arg): planilla.Planilla_ = dict({'':[]}) self.Planilla_ = dict(*arg) print ("iniciando: "+str(self.Planilla_)) def crear_planilla(self): #define función planilla.Planilla_={} numKeys=int(input('Cantidad de Alumnos: ')) #numeros de llaves del diccionario que devuelve for nameValuePair in range(numKeys): key = input("Nombre completo: ") # la llave puede ser el ALIAS o Nom. Comp. valList = [] #utiliza un vector y lo define. valList.append(input("alias: ")) # al vector le va agregando "valores" valList.append(input("Correo: ")) #se puede poner dentro de un loop. # valList.append(input("sim, calc o prog")) planilla.Planilla_[key] = valList #el vector["LISTA"] es el valor vinculado a la llave ##___________________________________________________________________ def guardar_planilla(self): "Guarda en un archivo .txt la planilla (diccionario) de forma directa." # open file for writing f = open(input("nombre")+".txt","w") #Abre eel archivo txt y habilita escribir "w" # write file f.write(str(self.Planilla_)) #escribe en f = (file.txt) el string del diccionario # close file f.close() def abrir_planilla(self): "Abrir el archivo .txt que se guardo el diccionario" self.Planilla_ = dict f = open(input("nombre")+'.txt', 'rt') self.Planilla_ = eval(f.read()) f.close() def abrir_datos(self): # nombre, alias, correo "Abrir un archivo que tiene guardada la info [key], [Val[0]],[Val[1] ... ]" vec =[] dicc = {} f = open(input("nombre")+'.txt', 'rt') for line in f: vec=line.strip('\n').split(', ') dicc[str(vec[0])]=list(vec[1:]) f.close() print(dicc) self.Planilla_=dict(dicc) ##___________________________________________________________________ def buscar_alia(self,alias): "busca en el diccionario el alias=value[0] donde [key:value] value=[value[0],...]" for key, value in self.Planilla_.items(): #bucle for donde i = [key, value] dentro de [k,v]=planilla_.items() if (alias) == (value[0]): return key return "no existe registro" def buscar_valor(self,palabra_,index_): "busca en el diccionario cualquier pablra dentro de value[index_], \ hay que indicarle el index_ \ donde index_=0 -> alias ; index_=1 -> Correo" for key, value in self.Planilla_.items(): if palabra_ == value[index_]: return key return "no existe registro" def crear_lista(self): "Crea una lista con los ALIAS" participantes_= [] for key, value in self.Planilla_.items(): participantes_.append(str(value[0])) self.Participantes_=participantes_ return self.Participantes_ def llamar(self): "Crea una lista con participantes, elije al ganador y \ devuelve una lista de participantes sin el ganador" self.llamar_a=ra.sample(self.Participantes_,1)[0] self.Participaron_=list(self.Participantes_) self.Participantes_.remove(self.llamar_a) return [self.Participaron_ , self.llamar_a , self.Participantes_] def crear_grupo(self, cant_): "crear_grupo(cant_) crea una cant_ de grupos conformado aleatoriamente" self.crear_lista() #Llama el metodo crear lista para tener la lista Participantes_ actualizada listaC_ = list(ra.sample(self.Participantes_,len(self.Participantes_))) #listaC_ es una lista como self.Grupos_= {} for i in range(cant_): key = str("Grupo: "+str(i)) datos = [[],[]] self.Grupos_[key] = datos #Resetea self.Grupos_ while listaC_ != []: #Mantiene este boclet hasta que listaC_ se quede sin elementos for ikey, ivalue in self.Grupos_.items(): if listaC_ != []: elegido_=listaC_.pop() ivalue[0].append(elegido_) ivalue[1].append(self.Planilla_[self.buscar_alia(elegido_)][1]) else: break return self.Grupos_ def escribir_lista(self,lista_): string="" ultima = len(lista_) j = 0 for i in lista_: j += 1 if j<ultima: string = string + i +", " else : string = string + i return string def caritafeliz(self,dia): self.Planilla_[self.buscar_alia(self.llamar_a)].append(str(dia)) print("Felicitaciónes %s \U0001f600 ! "%(self.llamar_a)) def medallero(self): lista =[] val : int for key, value in self.Planilla_.items(): if (len(value) > 2): lista.append(len(value)) lista.sort() while True: val=int(lista.pop()) for key, value in self.Planilla_.items(): if (len(value)==val): print(value[0]+": " + " ".join("\U0001f600" for i in range(len(value)-2))+"\n") if len(lista)==0: break
058e53e2b130a7cfac90b204f11cf06b03261b45
ahmedkrmn/Competitive-Programming
/Codeforces/1104B.py
210
3.578125
4
s = input() stack = [] c = 0 for i in range(len(s)): if len(stack) == 0 or s[i] != stack[-1]: stack.append(s[i]) else: stack.pop() c += 1 print("YES" if c % 2 else "NO")
339e0fa926e4b158746da57b23ed8bdcd2b55903
bwajteam/ThucTap-VCCorp
/Task1/Bai4/Bai4_C2.py
1,074
3.625
4
#!/usr/bin/python import threading import time lock = threading.Lock() summ = 0 threads = [] n = 1000 numOfThreads = 10 data = [] class my_thread (threading.Thread): def __init__(self,name, data, lock): threading.Thread.__init__(self) self.name = name self.data = data self.lock = lock def run(self): global summ while len(self.data)> 0: lock.acquire() n= self.data.pop() lock.release() summ+= n print(self.name + " n = " + str(n) + " summ = "+ str(summ)) time.sleep(0.01) for i in range(1001): data.append(i) for i in range(numOfThreads-1): thread = my_thread("Thread {}".format(i+1), data, lock) threads.append(thread) thread = my_thread("Thread {}".format(i+1), data, lock) threads.append(thread) for t in threads: t.start() for t in threads: t.join() print(summ)
3c97645e5ea2a31400052a9a75ca459b075616eb
jack-robs/networks_projects
/simpleping/TCPClientServer/tests.py
720
3.578125
4
''' Test file for Project 1, Part1: TCP client/server Jack Robertson Selected functions tested ''' from server import reverse def testReverse(inStr, expected): ''' Fxn: testReverse() Does: testst reverse(), server.py Params: * inStr: input string, 'a dog', 'A dog' * expected: expected result, 'god a', 'god A' returns: success 1/fail -1 ''' result = reverse(inStr) print('Res:', result) if result == expected: return 1 else: return -1 def main(): res = testReverse('dog', 'GOD') res1 = testReverse('a dog', 'GOD A') res2 = testReverse('a dOg', 'GoD A') res3 = testReverse('a dOg 1', '1 GoD A') print(res, res1, res2, res3) main()
e2c0f415cdb3e564c39443ffddf9e4d66bb7cff7
rflappo/Blogpost-data
/Idiomatic python/join_strings.py
222
3.875
4
words = ['Hello', 'world', 'my', 'name', 'is', 'Ramiro', "and", 'I', 'live', 'in', 'Argentina'] # Non-pythonic concatenated = '' for word in words: concatenated += word # Pythonic concatenated = "".join(words)
da935d8471a799777a288cf45f76234640f81bcf
hbhowmick/Hangman
/Hangman.py
4,240
3.6875
4
from IPython.display import clear_output import time import random class Hangman(): def __init__(self): self.categories = {'sports':['baseball','football','hockey','softball','soccer','cricket','rugby','lacrosse'], 'colors':['red','orange','yellow','green','blue','purple','black'], 'flowers':['daisy', 'tulip', 'rose', 'iris', 'hydrangea', 'snapdragon', 'lily', 'carnation'], 'cities':['Boston', 'London', 'Paris', 'Singapore', 'Delhi', 'Dublin', 'Berlin', 'Bogota', 'Havana', 'Miami', 'Chicago', 'Beijing', 'Rome', 'Cairo', 'Sydney', 'Melbourne', 'Moscow', 'Tokyo', 'Dubai', 'Johannesburg'] } self.category = '' self.word_to_guess = '' self.guesses = [] self.lives = 5 self.flag = True def printInstructions(self): print('Welcome to Hangman! Guess a word - you have 5 lives before you are hung out to dry!') def printCategories(self): print('\n\nHere are the categories:') for k in self.categories.keys(): print(k.title()) def pickCategory(self): self.flag=True while True: self.printCategories() self.category = input('What category would you like to pick? ') if self.category in self.categories: clear_output() print('\nYou\'ve chosen {}!\nLet\'s play!'.format(self.category.upper())) break else: clear_output() if self.category.lower() == 'quit': break else: print('\n***{} is not a valid category***'.format(self.category)) def chooseWord(self): self.word_to_guess = random.choice(self.categories[self.category]) def showSpaces(self): self.string = (('_ ')*len(self.word_to_guess)) print(self.string) def showStatus(self, aList): self.guesses=aList guessed_status = '' for i in range(len(self.word_to_guess)): letter_to_guess = self.word_to_guess[i].lower() if letter_to_guess in self.guesses: guessed_status += letter_to_guess + ' ' else: guessed_status += '_ ' self.guessed_status = guessed_status print('\nCategory: {}\n'.format(self.category.upper())) print(self.guessed_status) print('\nGuesses: ') print(''.join(self.guesses)) if '_' not in self.guessed_status: print('\nYOU WIN!!!') self.flag=False def checkLetter(self): time.sleep(0.02) while self.flag==True: time.sleep(0.02) letter = input('\nGuess a letter: ') if letter == 'quit': break elif len(letter) > 1: print('Guess one letter at a time...') continue elif letter in self.word_to_guess.lower(): self.guesses.append(letter) clear_output() print('\nCorrect! Remaining lives: {}\n'.format(self.lives)) else: self.guesses.append(letter) self.lives -= 1 if self.lives==0: clear_output() print('\nGame over :(\n') print(self.guessed_status) print('\nGuesses: ') print(''.join(self.guesses)) break else: clear_output() print('\nSorry, try again! Remaining lives: {}\n'.format(self.lives)) self.showStatus(self.guesses) def checkComplete(self): if '_' in self.string: self.checkLetter() game = Hangman() while True: game.guesses = [] game.lives = 5 game.printInstructions() time.sleep(0.02) game.pickCategory() game.chooseWord() game.showSpaces() game.checkLetter() time.sleep(0.02) ans = input('Play another game?(y/n) ') if ans == 'n': break else: clear_output()
e938014fcd8bfba97982c75881a4f7ba2edf20ce
zhypopt/Python-100-Days
/Day01-15/code/Day05/craps_gamble.py
4,490
3.984375
4
""" Craps赌博游戏 玩家摇两颗色子 如果第一次摇出7点或11点 玩家胜 如果摇出2点 3点 12点 庄家胜 其他情况游戏继续 玩家再次要色子 如果摇出7点 庄家胜 如果摇出第一次摇的点数 玩家胜 否则游戏继续 玩家继续摇色子 玩家进入游戏时有1000元的赌注 全部输光游戏结束 Version: 0.1 Author: Nick Date: 2020-04-05 """ from random import randint def print_the_fig(num): if num == 1: print(" —————————") print("| |") print("| * |") print("| |") print(" —————————") elif num == 2: print(" —————————") print("| |") print("| * * |") print("| |") print(" —————————") elif num == 3: print(" —————————") print("| * |") print("| * |") print("| * |") print(" —————————") elif num == 4: print(" —————————") print("| * * |") print("| |") print("| * * |") print(" —————————") elif num == 5: print(" —————————") print("| * * |") print("| * |") print("| * * |") print(" —————————") elif num == 6: print(" —————————") print("| * * |") print("| * * |") print("| * * |") print(" —————————") def game_help(): print("The rule of this game:") print(" ---玩家第一次摇骰子如果摇出了7点或11点,玩家胜;") print(" ---玩家第一次如果摇出2点、3点或12点,庄家胜;") print(" ---其他点数玩家继续摇骰子:") print(" ---如果玩家摇出了7点,庄家胜;") print(" ---如果玩家摇出了第一次摇的点数,玩家胜;") print(" ---其他点数,玩家继续要骰子,直到分出胜负") def main_game(money): """ the money now have return the money current have """ print("===> Start a new round >===") while True: str_in = input('Please set your debt (0, %d]:' % money) try: debt = int(str_in) if 0 < debt <= money: break except ValueError: if "n" in str_in.lower(): return money elif "h" in str_in.lower(): game_help() else: continue roll_str = input("----> roll a dice >----") first = randint(1, 6) second = randint(1, 6) num_tot1 = first + second print('You have points %d here' % num_tot1) print_the_fig(first) print_the_fig(second) needs_go_on = False if num_tot1 == 7 or num_tot1 == 11: print('You win %d !' % debt) money += debt elif num_tot1 == 2 or num_tot1 == 3 or num_tot1 == 12: print('The banker win, you lose %d !' % debt) money -= debt else: needs_go_on = True while needs_go_on: roll_str = input("----> roll a dice >----") first = randint(1, 6) second = randint(1, 6) current = first + second print('You have points %d here' % current) print_the_fig(first) print_the_fig(second) if current == 7: print('The banker win, you lose %d !' % debt) money -= debt needs_go_on = False elif current == num_tot1: print('You win %d !' % debt) money += debt needs_go_on = False return money if __name__ == "__main__": money = 1000 print("************* Small gambling game ******************") game_help() print("***===>begin game, you have money: %d >===***" % money) continue_flag = True while money > 0 and continue_flag: money = main_game(money) print('You still have money: %d ' % money) str_in = str(input("Will you continue(Y/N)?")) if "n" in str_in.lower(): continue_flag = False if "h" in str_in.lower(): game_help() if not continue_flag: print("You have quited the game. You still have money: %d" % money) elif money <= 0: print("You have break down! Game over!")