blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
545k
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
545k
3c337c5a29d43444e3b4c51af2dc22ea4284c5e7
theguythatdoes/coding-assignments
/EatingGood.py
499
3.953125
4
# -*- coding: utf-8 -*- """ Created on Tue Oct 27 15:43:53 2020 @author: reube """ def howMany(meals,restaurant): wyt=[] rest=[] numrest=0 for bob in range(len(meals)): if meals[bob] not in rest: rest+=[meals[bob] ] for k in range (len(rest)): wyt+=rest[k].split(":") y=wyt.count(restaurant) return y if __name__==("__main__"): print(howMany(["Sue:Elmos", "Sue:Elmos", "Sue:Pitchforks"],"Elmos"))
a3908afeefdba6d570fdbea0dd5a5b20112a1593
hugessen/Advent-of-Code-2016
/Code/d3q1.py
628
3.53125
4
def is_valid(vals): max_side = max(vals) return sum(vals) > (2 * max_side) pinput = open('Inputs/d3.txt').read().split('\n') num_triangles = 0 for line in pinput: sides = [int(side) for side in line.split()] if is_valid(sides): num_triangles += 1 print num_triangles
17d9bf545ec17e744a53e7adc120100d293f3f40
hugessen/Advent-of-Code-2016
/Code/d1q1.py
951
3.609375
4
def turn(left_or_right): global c_dir if c_dir[X] == 1: c_dir = [0, -1*left_or_right] elif c_dir[X] == -1: c_dir = [0, 1*left_or_right] elif c_dir[Y] == 1: c_dir = [1*left_or_right, 0] elif c_dir[Y] == -1: c_dir = [-1*left_or_right, 0] pinput = open('Inputs/d1.txt').read().split(", ") X = 0 Y = 1 LEFT = -1 RIGHT = 1 c_dir = [0,1] pos = [0,0] visited = dict() for move in pinput: if move[0] == 'L': turn(LEFT) elif move[0] == 'R': turn(RIGHT) for i in range(int(move[1:])): pos[X] += c_dir[X] pos[Y] += c_dir[Y] key = str(pos[X] + pos[Y]) if key in visited: found = False for visited_pos in visited[key]: if visited_pos == tuple(pos): found = True print "Distance to closest double visit = %d" % (abs(pos[X]) + abs(pos[Y])) break if found is False: visited[key].append( (pos[X], pos[Y]) ) else: visited[key] = [(pos[X], pos[Y])] print "Distance = %d" % (abs(pos[X]) + abs(pos[Y]))
c4a724e06eda95e28c9ad081698f1c08f0272467
tsixit/python
/PycharmProjects/formation/poo.py
10,517
3.75
4
unite1 = { 'nom': 'méchant', 'x': 12, 'y': 7, 'vie': 42, 'force': 9 } unite2 = { 'nom': 'gentil', 'x': 11, 'y': 7, 'vie': 8, 'force': 3 } def attaque(attaquant, cible): print("{} attaque {} !".format(attaquant['nom'], cible['nom'])) cible['vie'] -= attaquant['force'] attaque(unite1, unite2) print(unite2) class CategorieOuModele: pass class Unite(object): """ Cette classe représente une unité dans un jeu que nous vendons 1 milliards d'euros / pièce. """ # nom = None # x = None # y = None # vie = None # force = None VIE_MAX = 100 def __init__(self, nom, x, y, vie, force): """ Constructeur de la classe unité. :param nom: nom de l'unité :type nom: str :param x: abscisse de l'unité :type x: int :param y: ordonnée de l'unité :type y: int :param vie: points de vie de l'unité :type vie: int :param force: force de l'unité :type force: int """ super().__init__() self._nom = nom # attribut protégé self.x = x self.y = y self.vie = vie self.force = force self.__fichier = 'unite.json' # attribut privé def attaque(self, cible): """ Cette méthode sert à attaquer une unité. :param cible: cible de l'attaque :type cible: Unite """ print("{} attaque {} !".format(self._nom, cible._nom)) cible.vie -= self.force def se_repose(self): """ Sert à regagner un point de vie. """ print("{} se repose et regagne 1 point de vie.".format(self._nom)) self.vie += 1 def __str__(self): """ Renvoie une représentation de l'unité sous forme de chaîne de caractères. :return: la chaîne de caractère représentant l'unité :rtype: str """ return "<Unite nom:{} x:{} y:{} vie:{} force:{}>".format(self._nom, self.x, self.y, self.vie, self.force) def __lt__(self, autre): # lt = lower than < return self.vie < autre.vie def __gt__(self, autre): # gt = greater than > return self.vie > autre.vie def __le__(self, autre): # le = lower or equal <= return self.vie <= autre.vie def __ge__(self, autre): # ge = greater or equal >= return self.vie >= autre.vie def __eq__(self, autre): # eq = equals return self.vie == autre.vie def __ne__(self, autre): # ne = not equals return self.vie != autre.vie mechant = Unite('méchant', 12, 7, 42, 9) # instanciation de l'objet # mechant est une instance de la classe Unite # mechant.nom = 'méchant' # mechant.x = 12 # mechant.y = 7 # mechant.vie = 42 # mechant.force = 9 mechant.defense = 5 print(mechant.defense) gentil = Unite('gentil', 11, 7, 8, 3) # print(gentil.defense) gentil.attaque(mechant) print(mechant.vie) Unite.attaque(gentil, mechant) print(mechant.vie) mechant.se_repose() # méchant se repose et regagne 1 point de vie. print(mechant.vie) print(mechant) print(str(mechant)) print(mechant.__str__()) chaine = mechant.__str__() # gentil.attaque(123) # >>> import poo # >>> help(poo) # >>> help(poo.Unite) # >>> help(poo.Unite.attaque) # >>> help(print) # >>> poo.Unite.__doc__ # >>> poo.Unite.attaque.__doc__ print(dir()) # liste de toutes les variables de notre programme print(dir(mechant)) print(Unite.__lt__) print(mechant < gentil) print(mechant.__dict__) # Héritage # ======== # class Guerrier(Unite, Tank, Affichable): class Guerrier(Unite): # Unite est la superclasse de Guerrier def __init__(self, nom, x, y, vie, force, rage=100): # super().__init__(nom, x, y, vie, force) # Python 3 # Tank.__init__(self) # Affichable.__init__(self) Unite.__init__(self, nom, x, y, vie, force) self.rage = rage # self.__fichier = 'guerrier.json' # print("***", dir(self)) # print(self.__fichier) # print(self._Unite__fichier) # déconseillé def __str__(self): return "<Guerrier nom:{} x:{} y:{} vie:{} force:{} rage:{}>".format(self._nom, self.x, self.y, self.vie, self.force, self.rage) def frappe_heroique(self, cible): """ Exécute une frappe héroïque. :param cible: cible de la frapep :type cible: Unite """ # if not isinstance(cible, Unite): # print("*** La cible n'est pas une Unite !") # return if self.rage < 20: print("*** Echec de la frappe héroïque !") return print("{} exécute une frappe héroïque sur {} !".format(self._nom, cible._nom)) cible.vie -= self.force * 2 self.rage -= 20 conan = Guerrier('Conan', 11, 8, 10000, 20, 50) conan.attaque(mechant) print(mechant) print(conan) conan.frappe_heroique(mechant) conan.frappe_heroique(mechant) conan.frappe_heroique(mechant) print(mechant) # Une frappe héroïque consomme 20 de rage # 1) Si le guerrier n'a pas assez de rage pour exécuter la frappe # héroïque, afficher un message d'erreur, et annuler la frappe. # 2) Gérer la consommation de la rage. # 3) Afficher la rage dans __str__ # 4) Par défaut, un guerrier a 100 de rage. # Attributs publics, protégés, privés # =================================== print(conan._nom) # déconseillé #conan._nom = 'fichier.json' print(conan._Unite__fichier) # déconseillé hercule = Guerrier('Hercule', 1, 2, 3, 4) hercule.frappe_heroique(conan) print(conan) # isinstance # ========== print(isinstance(gentil, Unite)) # permet de tester l'héritage print(isinstance(gentil, Guerrier)) print(isinstance(conan, Unite)) print(isinstance(conan, Guerrier)) print(type(conan)) print(type(conan) is Guerrier) # test s'ils sont de même type print(type(conan) is Unite) # Classe de service # ================= # Sert à grouper les fonctions class TextFormat: def souligner(self, texte): print(texte) print('=' * len(texte)) @staticmethod # permet de ne pas mettre self def encadrer(texte): print('#' * (len(texte) + 4)) print('#', texte, '#') print('#' * (len(texte) + 4)) def espacer(self, texte): caracteres = list(texte) # print(caracteres) print(' '.join(caracteres)) t = TextFormat() t.souligner("Appel de souligner()") t.encadrer("Est-ce que ça marche ?") TextFormat.encadrer("Texte à encadrer") # Agrégation # ========== class Familier: proprietaire = None # agrégation chien = Familier() chien.proprietaire = conan class Personnage: inventaire = [] # agrégation def ramasse(self, accessoire): self.inventaire.append(accessoire) class Accessoire: pass harry = Personnage() baguette = Accessoire() harry.ramasse(baguette) # Les exceptions : sont des class # =============== # 1/0 # ZeroDivisionError: division by zero # l = [1, 2, 3] # l[100] # IndexError: list index out of range try: print("On va faire quelque chose de mal :") 1 / 0 print("Ceci ne s'affiche jamais.") except ArithmeticError as e: print("*** Vous avez fait une erreur arithmétique !") print(e) print(type(e)) # except ZeroDivisionError: # print("*** Vous avez divisé par zéro !") except: print("*** Une exception s'est déclenchée, ceci capture toute les excéptions !") # protocole = 'gsfdgfsdgsd' protocole = 'http' if protocole not in ('http', 'https', 'ftp', 'ssh'): raise ValueError("Protocole non supporté !") # Déclenche une exception crée à la main # Le bubbling avec les exceptions # =============================== def a(): b() def b(): c(10, 0) def c(dividende, diviseur): f = None try: f = open('fichier.txt') # dans try s'il y a une excéption, alors les autres blocs ne seront pas exécute, dividende / diviseur # direcement dans except, try, except et finally vont ensemble # f.close() except IndexError: print("*** Cette fois-ci, vous avez dépassé les bornes !") else: print("Tout s'est bien passé, aucune exception n'a été déclenchée.") finally: print("Ceci s'exécute tout le temps à la sortie du bloc de capture d'exception.") f.close() try: a() except ZeroDivisionError: print("*** Vous avez divisé par zéro !") # Créer nos propres exceptions # ============================ class ProblemeMajeurError(Exception): # Exception est une class de base python pass try: raise ProblemeMajeurError() except ProblemeMajeurError: print("*** Un problème grave est survenu !!!") # Les accesseurs (getter, setter) # =============================== # C'est pour accéder aux attibuts privée class Personnage: def __init__(self, nom, age): self.__nom = nom self.__age = age # Accesseurs façon Java et PHP : def set_nom(self, valeur): if type(valeur) is not str: raise ValueError("Cher collègue, tu as écrit n'importe quoi !") self.__nom = valeur def get_nom(self): return "Monsieur " + self.__nom # Accesseur façon Python : @property # decorateur de base de python def age(self): print("Appel du getter de age...") return self.__age @age.setter def age(self, valeur): print("Appel du setter de age...") self.__age = valeur harry = Personnage('Harry Potter', 12) harry.set_nom('Voldemort') print(harry.get_nom()) # harry.set_nom(123) print(harry.age) harry.age = 13 # Décorateurs #============ from time import time def decorateur(autre_fonction): def fonction_de_remplacement(): print("Exécuter quelque chose avant...") start = time() autre_fonction() end = time() print("Exécuter quelque chose après...") print("Nombre de secondes pour exécuter la fonction :", end - start) return fonction_de_remplacement @decorateur # appel du decorateur sur la fonction compteur def compteur(): for i in range(5): print(i) #compteur = decorateur(compteur) # une autre facon d'appeler le décorateur compteur() # Contextes # ========= class Chrono: def __enter__(self): self.start = time() def __exit__(self, *exc): self.end = time() print(self.end - self.start) with Chrono() as c: for i in range(1000000): print(i)
38c35c919afd61c749c0c521943d9fd821a44818
Tcake/py_leetcode
/leetcode/Guess Number Higher or Lower II.py
686
3.5
4
class Solution: def getMoneyAmount(self, n): """ :type n: int :rtype: int """ left = 1 right = n result = 0 while right - left >= 6: left = (right + left) // 2 result += left if left is not 1: left += 1 tmp = right - left if tmp == 1: result += left elif tmp == 2: result += left + 1 elif tmp == 3: result += left * 2 + 2 elif tmp == 4: result += left * 2 + 4 elif tmp == 5: result += left * 2 + 6 return result a = Solution() print(a.getMoneyAmount(7))
599b529c6e4cfc0e0ce04753c26c2bd543ef3dcb
logotip123/py_merge
/merge.py
799
4.03125
4
"""Two list sort module""" from typing import List def merge(array1: List[int], array2: List[int]) -> List[int]: """ Two list sort function :param array1: first list for sort :param array2: second list for sort :return: array1 + array2 sorted list """ array1index = 0 array2index = 0 result = [] while True: if array1index >= len(array1): result.extend(array2[array2index:]) break if array2index >= len(array2): result.extend(array1[array1index:]) break if array1[array1index] < array2[array2index]: result.append(array1[array1index]) array1index += 1 else: result.append(array2[array2index]) array2index += 1 return result
95ecfbc9b444f09586e7fa1dbc8a752e846ef8f7
jaaaaaaaaack/xpilot-bots
/old-files/evstrat/neuralNet.py
5,221
3.734375
4
# Jack Beal and Lydia Morneault # COM-407 CI # 2018-05-07 Final project # Based on neuralnet.py by Jessy Quint and Rishma Mendhekar from random import* import math def sigmoid(x): return (1/(1+math.exp(-1*x))) def perceptron(thing, weights): summation = 0 # initialize sum counter = 0 # variable to assign correct weight to correct bit for digit in thing: # for each bit summation += (int(digit)*weights[counter]) # calculate weighted sum counter += 1 summation += (-1 * weights[-1]) # subtract the threshold in order to shift the decision boundary output = sigmoid(summation) # keep output between 0 and 1 return output # perceptron for hidden layer to output neuron # inputs into output neuron are float values that we do not want to round to integers def perceptron2(thing, weights): summation = 0 # initialize sum counter = 0 # variable to assign correct weight to correct bit for digit in thing: # for each bit summation += digit*weights[counter] # calculate sum based on weights counter += 1 summation += (-1 * weights[-1]) # subtract the threshold in order to shift the decision boundary output = sigmoid(summation) return output def trainingPercepton(iterations): learningRate = 0.1 # Epsilon weightsA = [] # weights for each input for neuron A weightsB = [] # '' for neuron B weightsC = [] # '' for neuron C # Weights from hidden layer to output neuron and threshold weightFinal = [round(uniform(-0.48, 0.48), 2), round(uniform(-0.48, 0.48), 2), round(uniform(-0.48, 0.48), 2), round(uniform(-0.48, 0.48), 2)] # Assign random initial weights, with values between -r and +r where r = 2.4/# of inputs see p.179 for w in range(4): weightsA.append(round(uniform(-0.48, 0.48), 2)) weightsB.append(round(uniform(-0.48, 0.48), 2)) weightsC.append(round(uniform(-0.48, 0.48), 2)) #print(weightsA) #print(weightsB) trainingInput = [ ['000', 1], ['025', 1], ['050', 1], ['075', 0.9], ['100', 0.8], ['125', 0.7], ['150', 0.7], ['175', 0.6], ['200', 0.6], ['225', 0.5], ['250', 0.5], ['275', 0.4], ['300', 0.3], ['325', 0.2], ['350', 0.1], ['375', 0], ['400', 0], ['425', 0], ['450', 0], ['500', 0]] for j in range(iterations): # Loop through the list, number of loops depends on user input outputList = [] # Print output list to see accuracy for train in trainingInput: outputA = perceptron(train[0],weightsA) # output for neuron A outputB = perceptron(train[0],weightsB) # output for neuron B outputC = perceptron(train[0],weightsC) # output for neuron C outputsABC = [outputA, outputB, outputC] # inputs for the final neuron finalOutput = perceptron2(outputsABC, weightFinal) # Error is calculated by subtracting the program output from the desired output error = train[1] - finalOutput # Calculate error gradients # error gradient for output layer based on formula errorGradient = finalOutput * (1-finalOutput) * error # Add the previous neuron's weight to (learning rate * input * error gradient) for i in range(len(weightFinal)-1): weightFinal[i] += (learningRate * outputsABC[i] * errorGradient) weightFinal[3] = weightFinal[3] + (learningRate * -1 * errorGradient) # for threshold # Error gradient for hidden layer # Don't have desired outputs for hidden layer, therefore cannot calculate error # Instead of error, use sumGradient = error gradient for output neuron * weight of the input sumGradientA = (errorGradient * weightFinal[0]) sumGradientB = (errorGradient * weightFinal[1]) sumGradientC = (errorGradient * weightFinal[2]) hiddenGradientA = (outputA * (1-outputA) * sumGradientA) hiddenGradientB = (outputB * (1-outputB) * sumGradientB) hiddenGradientC = (outputC * (1-outputC) * sumGradientC) # Using error gradients, update the weights for i in range(len(weightsA)-1): weightsA[i] += (learningRate * int(train[0][i]) * hiddenGradientA) weightsB[i] += (learningRate * int(train[0][i]) * hiddenGradientB) weightsC[i] += (learningRate * int(train[0][i]) * hiddenGradientC) weightsA[3] += (learningRate * -1 * hiddenGradientA) weightsB[3] += (learningRate * -1 * hiddenGradientB) weightsC[3] += (learningRate * -1 * hiddenGradientC) outputList.append([]) outputList[-1].append(train[0]) outputList[-1].append(finalOutput) # for temp in outputList: # print(temp[0], "->", temp[1])
9e0cd81ea1e65c22f141d4d08e4177860876a5c6
kutakieu/AI-class
/Assignment-1-Search-master-63318a771170bfa64d905052bc0e733cfd3b576e/code/heuristics.py
4,813
3.828125
4
# heuristics.py # ---------------- # COMP3620/6320 Artificial Intelligence # The Australian National University # For full attributions, see attributions.txt on Wattle at the end of the course """ This class contains heuristics which are used for the search procedures that you write in search_strategies.py. The first part of the file contains heuristics to be used with the algorithms that you will write in search_strategies.py. In the second part you will write a heuristic for Q4 to be used with a MultiplePositionSearchProblem. """ #------------------------------------------------------------------------------- # A set of heuristics which are used with a PositionSearchProblem # You do not need to modify any of these. #------------------------------------------------------------------------------- def null_heuristic(pos, problem): """ The null heuristic. It is fast but uninformative. It always returns 0. (State, SearchProblem) -> int """ return 0 def manhattan_heuristic(pos, problem): """ The Manhattan distance heuristic for a PositionSearchProblem. ((int, int), PositionSearchProblem) -> int """ # print("mahattan") return abs(pos[0] - problem.goal_pos[0]) + abs(pos[1] - problem.goal_pos[1]) def euclidean_heuristic(pos, problem): """ The Euclidean distance heuristic for a PositionSearchProblem ((int, int), PositionSearchProblem) -> float """ return ((pos[0] - problem.goal_pos[0]) ** 2 + (pos[1] - problem.goal_pos[1]) ** 2) ** 0.5 #Abbreviations null = null_heuristic manhattan = manhattan_heuristic euclidean = euclidean_heuristic #------------------------------------------------------------------------------- # You have to implement the following heuristics for Q4 of the assignment. # It is used with a MultiplePositionSearchProblem #------------------------------------------------------------------------------- #You can make helper functions here, if you need them def bird_counting_heuristic(state, problem) : position, yellow_birds = state heuristic_value = 0 """ *** YOUR CODE HERE *** """ heuristic_value = len(yellow_birds) # print(heuristic_value) return heuristic_value bch = bird_counting_heuristic def MHdis(pos1, pos2): return abs(pos1[0] - pos2[0]) + abs(pos1[1] - pos2[1]) def ECdis(pos1, pos2): return ((pos1[0] - pos2[0]) ** 2 + (pos1[1] - pos2[1]) ** 2) ** 0.5 def every_bird_heuristic(state, problem): """ (((int, int), ((int, int))), MultiplePositionSearchProblem) -> number """ position, yellow_birds = state yellow_birds = list(yellow_birds) heuristic_value = 0 if len(yellow_birds) == 0: return heuristic_value """ *** YOUR CODE HERE *** """ #find nearest yellow bird and add the distance to the heuristic value nearest_yb_distance = 10000 nearest_yb = None for yb in yellow_birds: distance = problem.maze_distance(yb, position) if distance < nearest_yb_distance: nearest_yb = yb nearest_yb_distance = distance heuristic_value += nearest_yb_distance """calculate Minimum Spanning Tree as a heuristic function""" #prepare a dictionary {yellow_bird : [distances_between_other_yellow_birds, yellow_bird_position]} dis_YandYs = {} for yb1 in yellow_birds: dis_YandY = [] for yb2 in yellow_birds: if yb1 != yb2: distance = problem.maze_distance(yb1, yb2) dis_YandY.append([distance, yb2]) dis_YandY.sort() dis_YandYs[yb1] = dis_YandY # choose yellow_birds until the tree covers the all unvisited yellow_birds YB_set = set() YB_set.add(nearest_yb) """repeat finding nearest yellow bird from YB_set which is a set of yellow bird already achieved a path to go, until you get minimun edeges to go to all yellow birds""" while len(YB_set) < len(yellow_birds): nearest_yb_distance = 10000 nearest_yb = None from_yb = None for yb in YB_set: dis_YandY = dis_YandYs[yb] temp_yb_distance, temp_yb = dis_YandY[0] if temp_yb_distance < nearest_yb_distance: nearest_yb_distance = temp_yb_distance nearest_yb = temp_yb from_yb = yb if nearest_yb not in YB_set: YB_set.add(nearest_yb) heuristic_value += nearest_yb_distance # print("yb = " + str(from_yb) + "TO" + str(nearest_yb) + " dis = " + str(nearest_yb_distance)) dis_YandY = dis_YandYs[nearest_yb] dis_YandY.remove([nearest_yb_distance, from_yb]) dis_YandY = dis_YandYs[from_yb] dis_YandY.remove([nearest_yb_distance, nearest_yb]) return heuristic_value every_bird = every_bird_heuristic
ab79b8c878f465cac0131bf55f802a6b64cfdfb5
MatejBabis/AdventOfCode2k18
/day5/part1.py
799
3.765625
4
def read_input(filename): f = open(filename) # only one line, and remove '\n' output = f.readline().strip() f.close() return output # helper function that checks if two letters are equal are diffent case def conflict(a, b): return a.lower() == b.lower() and ((a.isupper() and b.islower()) or (a.islower() and b.isupper())) # recation function def polymer_reaction(string, ignored=None): stack = [] for c in string: if c.lower() == ignored: continue # skip if len(stack) == 0: stack.append(c) elif conflict(stack[-1], c): stack.pop() else: stack.append(c) return stack if __name__ == "__main__": s = read_input("input.txt") print("Answer:", len(polymer_reaction(s)))
d5273f7320cae0c86a36327e9defa268b7bca045
MatejBabis/AdventOfCode2k18
/day4/part1.py
2,591
3.5
4
import re import numpy as np # strings to match ASLEEP = 'falls asleep' AWAKE = 'wakes up' GUARD = 'Guard' # process the input file def process_file(filename): f = open(filename) records_list = [] for line in f.readlines(): raw = line[6:-1] # first six letter carry no information month = int(raw[:2]) day = int(raw[3:5]) hour = int(raw[6:8]) minute = int(raw[9:11]) message = raw[13:] records_list += [(month, day, hour, minute, message)] f.close() # sort the items based on timestamps records_list.sort(key=lambda x: (x[0], x[1], x[2], x[3])) return records_list # create a dictionary with data for each guard def organise_records(array): output = {} # sleeping = False # flag # initialise variable guard_id = None asleep_from = None asleep_to = None for log in array: msg = log[4] # only minutes as sleep happens between 00:00 and 00:59 time = log[3] # initialise if guard_id not in output: output[guard_id] = [] # get ID from string 'Guard #X begins shift' if msg.startswith(GUARD): guard_id = int(re.findall(r'\d+', msg)[0]) # get 'falls asleep' time elif msg == ASLEEP: # sleeping = True asleep_from = time # get 'wakes up' time and stores in dictionary elif msg == AWAKE: asleep_to = time # store datum output[guard_id] += [(asleep_from, asleep_to)] # unexpected input else: raise ValueError('Unexpected input: ', log) return output # return a triple used to computer answers: # 1. minutes asleep, # 2. the minute the guard is asleep most often # 3. the maximum value at 2. def count_sleeps(g, data): asleep_at_minute = np.zeros(60) for timestamp in data[g]: for minute in range(timestamp[0], timestamp[1]): asleep_at_minute[minute] = asleep_at_minute[minute] + 1 return np.sum(asleep_at_minute), np.argmax(asleep_at_minute), max(asleep_at_minute) if __name__ == "__main__": sorted_data = process_file("input.txt") dataset = organise_records(sorted_data) # hold the record (GuardID, how much sleep, "most asleep" minute) maximum = (None, 0, None) for guard in dataset: time_asleep, most_sleepy_minute, _ = count_sleeps(guard, dataset) if time_asleep > maximum[1]: maximum = (guard, time_asleep, most_sleepy_minute) print("Answer:", maximum[0] * maximum[2])
bc7b865e579f10ee6632e9b10099d106727bdd14
petrakov1/foodbot
/dataAnal.py
3,617
3.546875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- import _json import math def valueByTag(place,arrPerson): value = 0 for tag in arrPerson: if (tag in place): value += place[tag]*arrPerson[tag] return (value) def sortByValue(arr): for i in range(len(arr)): for j in range(len(arr)-1, i, -1): if arr[j][1] > arr[j - 1][1]: test1 = arr[j][0] test2 = arr[j][1] test3 = arr[j][2] arr[j][0] = arr[j - 1][0] arr[j][1] = arr[j - 1][1] arr[j][2] = arr[j - 1][2] arr[j - 1][0] = test1 arr[j - 1][1] = test2 arr[j - 1][2] = test3 def getTopPlaces (json_Plase, json_Person,clientPoint): arrPerson = json_Person["tags"] personPrise = json_Person["price"] arrPlaces = [] for place in json_Plase: distance = distance_([place["location"]["lon"], place["location"]["lat"]], clientPoint) if (distance < 3): arrPlaces.append([place["id"], valueByTag(place["tags"], arrPerson), distance]) #print (arrPlaces) sortByValue(arrPlaces) if (arrPlaces.__len__()==0): arrPlaces.append([0,0,0]) if (arrPlaces[0][1] != 0): for i in range(1, arrPlaces.__len__()): arrPlaces[i][1] = arrPlaces[i][1] / float(arrPlaces[0][1]) arrPlaces[0][1] = 1 arrValueOfPrices = [] for place in json_Plase: arrValueOfPrices.append([place["id"], place["price"]]) for i in range(0, arrValueOfPrices.__len__()): arrValueOfPrices[i][1] = (personPrise - arrValueOfPrices[i][1]) / 2.0 for i in range(0, arrPlaces.__len__()): for j in range(0, arrValueOfPrices.__len__()): if (arrPlaces[i][0]==arrValueOfPrices[j][0]): arrPlaces[i][1] = 2 * arrPlaces[i][1] + arrValueOfPrices[j][1] sortByValue(arrPlaces) while arrPlaces.__len__()>5: arrPlaces.pop() #print (arrPlaces) return (arrPlaces) def distance_(point1, point2): R = 6371 dLat = math.radians(point2[0] - point1[0]) dLon = math.radians(point2[1] - point1[1]) a = math.sin(dLat / 2) * math.sin(dLat / 2) + math.cos(math.radians(point1[0])) * math.cos(math.radians(point2[0])) * math.sin(dLon / 2) * math.sin(dLon / 2) c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a)) d = R * c return d #jsonPlaces = [{"name": "\u0422\u0435\u0441\u0442", "tags": {"burger": 1}, "price": 1, "location": {"lat":59.9317145,"lon":30.3457811}, "id": 1, "desc": "@"}, # {"name": "\u0422\u0435\u0441\u0442", "tags": {"burger": 1}, "price": 1, "location": {"lat":59.9317405,"lon":30.3457811}, "id": 2, "desc": "@"}, # {"name": "\u0422\u0435\u0441\u0442", "tags": {"burger": 1}, "price": 1, "location": {"lat":59.9317145,"lon":30.3456811}, "id": 3, "desc": "@"}, # {"name": "Pizaa", "tags": {"pasta": 1}, "price": 1, "location": {"lat":59.9317145,"lon":30.3457854}, "id": 4, "desc": ""}, # {"name": "a", "tags": {"pasta": 1, "fri": 1}, "price": 2, "location": {"lat":59.9317405,"lon":30.3457811}, "id": 5, "desc": ""}, # {"name": "Pizaa", "tags": {"fri": 2}, "price": 1, "location": {"lat":59.9317405,"lon":30.3457811}, "id": 6, "desc": ""}, # {"name": "a", "tags": {"burger": 1, "fri": 1}, "price": 2, "location": {"lat":59.9317405,"lon":30.3457811}, "id": 7, "desc": ""}] #jsonPerson = {"tags": {"burger":1,"pizza":2}, "price": 1, "places": 0} #clientPoint = (59.9368993,30.3154044) #getTopPlaces(jsonPlaces,jsonPerson,clientPoint)
158450f4cb59c6890e6de4931de18e66a4f5ef48
FraserTooth/python_algorithms
/01_balanced_symbols_stack/stack.py
865
4.21875
4
class Stack: def __init__(self): self.items = [] def push(self, item): """Adds an item to end Returns Nothing Time Complexity = O(1) """ self.items.append(item) def pop(self): """Removes Last Item Returns Item Time Complexity = O(1) """ if self.items: return self.items.pop() return None def peek(self): """Returns Last Item Time Complexity = O(1) """ if self.items: return self.items[-1] return None def size(self): """Returns Size of Stack Time Complexity = O(1) """ return len(self.items) def is_empty(self): """Returns Boolean of whether list is empty Time Complexity = O(1) """ return self.items == []
9ea5c9748f2a37bf51ed41905b601704b629c2d8
Alver23/CursoPython
/clase1/EjerciciosHechosClase/eres.py
191
4.09375
4
nombre = input("Cual es tu nombre") if nombre == "Alver": print ("Que man tan chevere") elif nombre == "Jorge": print ("Que Onda Jorge") else: print ("Eres Otro que no es Alver o Jorge")
462662bb1d616d434d6df18dabe53e424ac5b297
habc0d3r/100-Days-Of-Code
/Day-5/highest-score/main.py
323
3.75
4
student_scores = input("Input a list of student scores ").split() for n in range(0, len(student_scores)): student_scores[n] = int(student_scores[n]) print(student_scores) heighest = 0 for score in student_scores: if score > heighest: heighest = score print(f"The heighest score in the class is: {heighest}")
98b239868170d72f40abdf73dc38172bfaf24f1d
habc0d3r/100-Days-Of-Code
/Day-18/challenge4.py
483
3.5
4
import turtle from turtle import Turtle, Screen import random as rd tim = Turtle() # tim.hideturtle() turtle.colormode(255) def random_color(): r = rd.randint(0, 255) g = rd.randint(0, 255) b = rd.randint(0, 255) final_color = (r, g, b) return final_color directions = [0, 90, 180, 270] tim.speed(0) tim.pensize(10) for _ in range(200): tim.color(random_color()) tim.fd(20) tim.seth(rd.choice(directions)) screen = Screen() screen.exitonclick()
aac8aac901bd84af8b37b384aae3f0607e023c34
habc0d3r/100-Days-Of-Code
/Day-18/challenge3.py
571
3.890625
4
from turtle import Turtle, Screen import random as rd colors = ['chartreuse', 'deep sky blue', 'sandy brown', 'medium orchid', 'magenta', 'royal blue', 'burlywood'] tim = Turtle() tim.shape("arrow") def change_color(): tim.color(rd.random(), rd.random(), rd.random()) def draw_shape(num_of_sides): angle = 360/num_of_sides for _ in range(num_of_sides): tim.forward(100) tim.right(angle) change_color() # tim.color(rd.choice(colors)) for side in range(3, 11): draw_shape(side) screen = Screen() screen.exitonclick()
66c93a7b70637fd2ebbabe192b10d52cca68ee1c
karthikyadav09/deep_learning_for_vision
/ASN3/Solution/ASN3/lstmMNISTStarterCode.py
2,867
3.546875
4
import tensorflow as tf import numpy as np import matplotlib.pyplot as plt from tensorflow.examples.tutorials.mnist import input_data from tensorflow.contrib import rnn mnist = input_data.read_data_sets("MNIST_data/", one_hot=True) #call mnist function learningRate = 0.0025 trainingIters = 100000 batchSize = 256 displayStep = 10 nInput =28 #we want the input to take the 28 pixels nSteps =28 #every 28 nHidden =256 #number of neurons for the RNN nClasses =10 #this is MNIST so you know x = tf.placeholder('float', [None, nSteps, nInput]) y = tf.placeholder('float', [None, nClasses]) weights = { 'out': tf.Variable(tf.random_normal([nHidden, nClasses])) } biases = { 'out': tf.Variable(tf.random_normal([nClasses])) } def RNN(x, weights, biases): x = tf.transpose(x, [1,0,2]) x = tf.reshape(x, [-1, nInput]) x = tf.split(x, nSteps, 0) #configuring so you can get it as needed for the 28 pixels lstmCell = rnn.BasicLSTMCell(nHidden, forget_bias=1.0) #find which lstm to use in the documentation rnnCell = rnn.BasicRNNCell(nHidden) gruCell = rnn.GRUCell(nHidden) outputs, states = rnn.static_rnn(lstmCell, x, dtype=tf.float32) #for the rnn where to get the output and hidden state return tf.matmul(outputs[-1], weights['out'])+ biases['out'] pred = RNN(x, weights, biases) #optimization #create the cost, optimization, evaluation, and accuracy #for the cost softmax_cross_entropy_with_logits seems really good cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y, logits=pred)) optimizer = tf.train.AdamOptimizer(learningRate).minimize(cost) correctPred = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1)) accuracy = tf.reduce_mean(tf.cast(correctPred, tf.float32)) init = tf.global_variables_initializer() train_accuracy = [] train_loss = [] idx = [] with tf.Session() as sess: sess.run(init) step = 1 while step* batchSize < trainingIters: batchX, batchY = mnist.train.next_batch(batchSize) #mnist has a way to get the next batch batchX = batchX.reshape((batchSize, nSteps, nInput)) sess.run(optimizer, feed_dict={x: batchX, y: batchY}) if step % displayStep == 0: acc = sess.run(accuracy, feed_dict={x: batchX, y: batchY}) loss = sess.run(cost, feed_dict={x: batchX, y: batchY}) train_accuracy.append(acc) train_loss.append(loss) print("Iter " + str(step*batchSize) + ", Minibatch Loss= " + \ "{:.6f}".format(loss) + ", Training Accuracy= " + \ "{:.5f}".format(acc)) step +=1 print('Optimization finished') testData = mnist.test.images.reshape((-1, nSteps, nInput)) testLabel = mnist.test.labels print("Testing Accuracy:", \ sess.run(accuracy, feed_dict={x: testData, y: testLabel})) print "Training Accuracy :" print train_accuracy print "Train Loss" print train_loss
447204f56fb361002c5d1ad231d25d8aaef4ff80
lerandc/project-euler
/python/p29.py
2,179
3.765625
4
""" Luis RD April 12, 2020 ------------------------------------------------ Consider all integer combinations of ab for 2 ≤ a ≤ 5 and 2 ≤ b ≤ 5: 22=4, 23=8, 24=16, 25=32 32=9, 33=27, 34=81, 35=243 42=16, 43=64, 44=256, 45=1024 52=25, 53=125, 54=625, 55=3125 If they are then placed in numerical order, with any repeats removed, we get the following sequence of 15 distinct terms: 4, 8, 9, 16, 25, 27, 32, 64, 81, 125, 243, 256, 625, 1024, 3125 How many distinct terms are in the sequence generated by ab for 2 ≤ a ≤ 100 and 2 ≤ b ≤ 100? """ from algorithms import factorize def prod(vals): """ List product """ product = 1 for i in vals: product *= i return product def countDuplicates(vals): """ Count duplicates in sorted tuple list """ count = 0 for i in range(1,len(vals)): if vals[i] == vals[i-1]: count+=1 return count def main(): #strategy is to reduce numbers to their prime factorizations #keep prime factors in one list, ordered; exponents in corresponding list, also ordered #generate prime factors for 2-100 factors = [] exponents = [] for i in range(2,101): f, e = factorize(i) if len(f) > 0: factors.append(f) if len(e) > 0: exponents.append(e) else: exponents.append([1]) else: factors.append([i]) exponents.append([1]) factors_a = [] exponents_b = [] for i in range(0,len(factors)): for b in range(2,101): factors_a.append(factors[i]) exponents_b.append([j*b for j in exponents[i]]) #join lists union = [] for i in range(0,len(factors_a)): union.append((factors_a[i],exponents_b[i])) # print(union[0:100]) union = sorted(union, key=lambda x: (prod(x[0]),x[1])) # count = countDuplicates(union) new_union = [union[0]] for i in range(1,len(union)): if union[i] != union[i-1]: new_union.append(union[i]) print(len(union)) print(len(new_union)) print(new_union) if __name__ == '__main__': main()
1f2bf332f201dbede1ce368cb977533ff440bc0d
forest-data/luffy_py_algorithm
/算法入门/merge_sort.py
1,934
3.65625
4
#归并排序 时间复杂度 O(nlogn) # 假设左右已排序 def merge(li, low, mid, high): i = low j = mid + 1 ltmp = [] while i<=mid and j<=high: if li[i] < li[j]: ltmp.append(li[i]) i += 1 else: ltmp.append(li[j]) j += 1 # while 执行完,肯定有一部分没数了 while i <= mid: ltmp.append(li[i]) i+=1 while j <= high: ltmp.append(li[j]) j+=1 li[low:high+1] = ltmp # def merge_sort(li, low, high): if low < high: mid = (low + high) //2 merge_sort(li, low, mid) # 递归左边 merge_sort(li, mid+1, high) # 递归右边 merge(li, low, mid, high) print(li[low:high+1]) li = list(range(10)) import random random.shuffle(li) print(li) merge_sort(li, 0, len(li)-1) print(li) ''' # def merge_sort(li): n = len(li) # 递归结束条件 if n<=1: return li # 中间位置 mid = n // 2 # 递归拆分左侧 left_li = merge_sort(li[:mid]) # 递归拆分右侧 right_li = merge_sort(li[mid:]) # 需要2个游标, 分别指向左列表和右列表第一个元素 left_point, right_point = 0, 0 # 定义最终返回的结果集 result = [] # 循环合并数据 while left_point < len(left_li) and right_point < len(right_li): # 谁小放前面 if left_li[left_point] <= right_li[right_point]: # 放进结果集 result.append(left_li[left_point]) left_point += 1 else: result.append(right_li[right_point]) right_point += 1 # 退出循环是,形成左右两个序列 result += left_li[left_point:] result += right_li[right_point:] return result if __name__ == '__main__': li = [53, 26, 93, 17, 77, 31, 44, 55, 21] print(li) print(merge_sort(li)) '''
dc55a27810a351d729e80b1ad96d09c5de314db3
forest-data/luffy_py_algorithm
/数据结构/stack.py
1,214
4.0625
4
# 栈: 是一个数据集合,只能在一段进行插入或删除操作 class Stack: def __init__(self): self.stack = [] def push(self, element): self.stack.append(element) # 删除栈顶元素 def pop(self): return self.stack.pop() # 获取栈顶元素 def get_top(self): if len(self.stack) > 0: return self.stack[-1] else: return None def is_empty(self): return len(self.stack) == 0 stack = Stack() stack.push(1) stack.push(2) stack.push(3) print(stack.get_top()) # 3 print(stack.pop()) # 3 # 匹配字符串问题 # def brace_match(s): match = {')':'(', ']':'[', '}':'{'} stack = Stack() for ch in s: if ch in {'(','[','{'}: stack.push(ch) else: if stack.get_top() == match[ch]: # ({}[]) stack.pop() elif stack.is_empty(): # 首次进来的是 ] ) } return False elif stack.get_top() != match[ch]: # ({)} return False if stack.is_empty(): #解决无结尾情况 ({}[] return True else: return False print(brace_match('{{}()[]}'))
0e63b36d3102607cbc9735009e6bb07796d67e20
forest-data/luffy_py_algorithm
/算法入门/quick_sort.py
2,049
3.71875
4
# # 快速排序 def partition(li,left,right): tmp = li[left] while left < right: while left < right and li[right] >= tmp: # 找比左边tmp小的数,从右边找 right -= 1 # 往左走一步 li[left] = li[right] # 把右边的值写到左边空位上 while left < right and li[left] <= tmp: left += 1 li[right] = li[left] #把左边的值写到右边空位上 li[left] = tmp # 把tmp归位 return left def quick_sort(data, left, right): if left < right: mid = partition(data, left, right) quick_sort(data, left, mid-1) quick_sort(data, mid+1, right) # li = [5,7,4,6,3,1,2,9,8] # print(li) # partition(li, 0, len(li)-1) # quick_sort(li, 0, len(li)-1) ''' # 快排 # first 第一索引位置, last 最后位置索引 # 时间复杂度 最坏O(n^2) 最优O(nlogn) def quick_sort(li, first, last): # 递归终止条件 if first >= last: return # 设置第一个元素为中间值 mid_value = li[first] # low指向first low = first # high指向last high = last # 只要low < high 就一直走 while low < high: # high 大于中间值, 则进入循环 while low < high and li[high] >= mid_value: # high往左走 high -= 1 # 出循环后,说明high < mid_value, low指向该值 li[low] = li[high] # high走完了,让low走 # low小于中间值,则进入循环 while low < high and li[low] < mid_value: low += 1 # 出循环后,说明low > mid_value, high 指向该值 li[high] = li[low] # 退出整个循环后, low和high相等 li[low] = mid_value # 递归 # 先对左侧快排 quick_sort(li, first, low-1) # 对右侧快排 quick_sort(li, low+1, last) ''' if __name__ == '__main__': li = [54, 26, 93, 17, 77, 31, 44, 55, 20] print(li) quick_sort(li, 0, len(li)-1) print(li)
0a953197aa82f1ee8ddfb16a4d8a12bb3977f9a0
forest-data/luffy_py_algorithm
/算法入门/查找算法/search.py
958
3.53125
4
import random # 查找: 目的都是从列表中找出一个值 # 顺序查找 > O(n) 顺序进行搜索元素 from 算法入门.cal_time import cal_time @cal_time def linear_search(li, val): for ind, v in enumerate(li): if v == val: return ind else: return None # 二分查找 > O(logn) 应用于已经排序的数据结构上 @cal_time def binary_search(li, val): left = 0 # 坐下标 right = len(li) - 1 #右下标 while left <= right: # 候选区有值 mid = (left + right)//2 # 对2进行整除,向下取整 if li[mid] == val: return mid elif li[mid] > val: right = mid - 1 else: left = mid + 1 else: return None # 测试 # li = [i for i in range(10)] # random.shuffle(li) # print(li) # # print(binary_search(li, 3)) # 性能比较 li = list(range(10000000)) linear_search(li, 3890) binary_search(li, 3890)
e737daceec599900b8e22c001f9288b5fb70ac25
karakorakura/Data-Structures-Practice
/btree.py
3,787
3.5
4
# Shivam Arora # 101403169 # Assignment 4 # Avl tree # COE7 #GlObal #degree t=2; class Node: def __init__(self,data=None,parent = None,pointers = None,leaf = True): self.keys = [] self.pointers=[] self.keysLength = 0 self.parent=parent self.leaf = leaf if data!=None : for d in data: self.keys.append(d) self.keysLength+=1 if pointers!=None : for p in pointers: self.pointers.append(p) def search(self,data): i = 0 while i < self.keysLength and data > self.keys[i]: i += 1 if self.keys[i] == data: return self if self.leaf: return None return self.pointers[i].search(data) def insert(self,data,node1=None,node2=None): i = 0 while i < self.keysLength and data > self.keys[i]: i += 1 self.keys.insert(i,data) self.keysLength+=1 if i < len(self.pointers) : self.pointers[i]=node1 else: self.pointers.append(node1) self.pointers.insert(i+1,node2) class Btree: def __init__(self,root=None): global t self.degree=t self.maxKeyLength = self.degree*2 - 1 self.minKeyLength = self.degree - 1 # self.root=Node(root) self.root=None def printTree(self,node=None): if node==None: node= self.root if node.leaf: for key in node.keys: print key, else : i=0 for key in node.keys: self.printTree(node.pointers[i]) print key, i+=1 self.printTree(node.pointers[i]) def preorder(self,node=None): if node==None: node= self.root if node.leaf: for key in node.keys: print key, else : i=0 for key in node.keys: print key, # printTree(pointers[i+1]) i+=1 pass def split(self,node=None): parent = node.parent #mid element keys[t-1] node1 = Node(data = node.keys[:t-1], pointers = node.pointers[:t] ) node2 = Node(data = node.keys[t:], pointers = node.pointers[t+1:] ) if parent==None: self.root = Node([node.keys[t-1]],pointers=[node1,node2],leaf=False) parent = self.root parent.leaf = False else : parent.insert(node.keys[t-1],node1,node2) node1.parent=parent node2.parent=parent #Insertion at node def insertAtNode(self,data,node): i = 0 while i < node.keysLength and data > node.keys[i]: i += 1 if node.leaf: node.insert(data) if node.keysLength>=2*t-1: self.split(node) else: self.insertAtNode(data,node.pointers[i]) # Insertion start def insert(self,data=None): if self.root==None: self.root=Node([data]) else: self.insertAtNode(data,self.root) # Search element # Deletion start unfinished def delete(self,data): pass ############################################## main code test code below b = Btree() # b.insert(1) # b.insert(2) # b.insert(3) # b.insert(4) # b.insert(5) # b.insert(6) x=0 x=int(raw_input('enter value to insert -1 to exit')) while x!=-1: b.insert(x) x=int(raw_input('enter value to insert -1 to exit')) b.printTree(); # b.preorder();
5d003bd13085125d781ca29eb8060b3db3bfe3a3
kesicigida/python_example
/find_student_number.py
1,973
3.59375
4
def printLine(x): for i in range(0, x): print "=", print(" ") def isEven(x): if x%2 == 0: return True else: return False ''' x[len(x)] overflows array x[len(x) - 1] equals newline <ENTER> x[len(x) - 2] is what is desired ''' def isLastUnknown(x): if x[len(x)-2] == "n": return True else: return False ''' x[len(x)] overflows array x[len(x) - 1] equals newline <ENTER> x[len(x) - 2] equals last digit We check all digits except the last digit ''' def isOneDigitUnknown(x): number_of_ns = 0 for i in range (0, len(x)-2): if x[i] == "n": number_of_ns = number_of_ns + 1 if number_of_ns == 0: print("no unknown") return False elif number_of_ns > 1: print("more than 1 unknown") return False else: return True def getDigit(x): printLine(len(x)) print(x) pos_of_n = 0 for i in range (0, len(x)-2): if x[i] == "n": pos_of_n = i for j in range (0, 10): xList = list(x) xList[pos_of_n] = str(j) x = "".join(xList) tSum = 1 for i in range (0, len(x)-2): if isEven(i): tSum = tSum + int(x[i]) else: tSum = tSum + 2*int(x[i]) if tSum%10 == 10 - int(x[len(x)-2]): print "n =", j return True ''' len(x) includes newline <ENTER> len(x) - 1 includes "n" len(x) - 2 is what is desired ''' def getLast(x): printLine(len(x)) print(x) tSum = 1 for i in range (0, len(x)-2): if isEven(i): tSum = tSum + int(x[i]) else: tSum = tSum + 2*int(x[i]) lastn = 10 - tSum%10 if lastn == 10: lastn = 0 print "n =", lastn return True mFile = open("student_number_samples.txt", "r") for line in mFile: a = line if isLastUnknown(a): getLast(a) elif isOneDigitUnknown(a): getDigit(a)
14d98d23d3617c08a2aefd1b4ced2d80c5a9378c
168959/Datacamp_pycham_exercises2
/Creat a list.py
2,149
4.40625
4
# Create the areas list areas = ["hallway", 11.25, "kitchen", 18.0, "living room", 20.0, "bedroom", 10.75, "bathroom", 9.50] "# Print out second element from areas" print(areas[1]) "# Print out last element from areas" print(areas[9]) "# Print out the area of the living room" print(areas[5]) "# Create the areas list" areas = ["hallway", 11.25, "kitchen", 18.0, "living room", 20.0, "bedroom", 10.75, "bathroom", 9.50] "# Sum of kitchen and bedroom area: eat_sleep_area" eat_sleep_area = areas[3] + areas[-3] "# Print the variable eat_sleep_area" print(eat_sleep_area) "#Subset and calculate" "# Create the areas list" areas = ["hallway", 11.25, "kitchen", 18.0, "living room", 20.0, "bedroom", 10.75, "bathroom", 9.50] "# Sum of kitchen and bedroom area: eat_sleep_area" eat_sleep_area = areas[3] + areas[-3] "# Print the variable eat_sleep_area" print(eat_sleep_area) "#Slicing and dicing" "# Create the areas list" areas = ["hallway", 11.25, "kitchen", 18.0, "living room", 20.0, "bedroom", 10.75, "bathroom", 9.50] "# Use slicing to create downstairs" downstairs = areas[0:6] "# Use slicing to create upstairs" upstairs = areas[6:10] "# Print out downstairs and upstairs" print(downstairs) print(upstairs) "# Alternative slicing to create downstairs" downstairs = areas[:6] "# Alternative slicing to create upstairs" upstairs = areas[-4:] "#Replace list elements" "# Create the areas list" areas = ["hallway", 11.25, "kitchen", 18.0, "living room", 20.0, "bedroom", 10.75, "bathroom", 9.50] "# Correct the bathroom area" areas[-1] = 10.50 # Change "living room" to "chill zone" areas[4] = "chill zone" "#Extend a list" areas = ["hallway", 11.25, "kitchen", 18.0, "chill zone", 20.0, "bedroom", 10.75, "bathroom", 10.50] "# Add poolhouse data to areas, new list is areas_1" areas_1 = areas + ["poolhouse", 24.5] "# Add garage data to areas_1, new list is areas_2" areas_2 = areas_1 + ["garage", 15.45] "#Inner workings of lists" "# Create list areas" areas = [11.25, 18.0, 20.0, 10.75, 9.50] "# Create areas_copy" areas_copy = list(areas) "# Change areas_copy" areas_copy[0] = 5.0 "# Print areas" print(areas)
cdae0b35f271a30def8b69d9cb1f93731a10e99b
shane-kerr/pythonmeetup-bmazing
/players/astarplayer.py
9,728
4.4375
4
""" This player keeps a map of the maze as much as known. Using this, it can find areas that are left to explore, and try to find the nearest one. Areas left to explore are called "Path" in this game. We don't know where on the map we start, and we don't know how big the map is. We could be lazy and simply make a very large 2-dimensional array to hold the map; this will probably work fine since we know that the map is loaded from a text file. However, we will go ahead and do it all sweet and sexy-like and make a map that resizes itself to allow for any arbitrary position. This player will use the A* algorithm to find the number of steps to get to any path that we have not yet explored. """ import heapq import pprint import sys from game import moves from game.mazefield_attributes import Path, Finish, Wall, Start from players.player import Player DEBUG = False def dist(x0, y0, x1, y1): """distance between two positions using only cardinal movement""" return abs(x1-x0) + abs(y1-y0) class Map: """ Implements a rectangular 2-dimensional map of unknown size. """ def __init__(self): self.pos_x = 0 self.pos_y = 0 self.map_x0 = self.map_x1 = 0 self.map_y0 = self.map_y1 = 0 self.map = [[Path]] # we must have started on a Path def move_left(self): self.pos_x -= 1 def move_right(self): self.pos_x += 1 def move_up(self): self.pos_y += 1 def move_down(self): self.pos_y -= 1 def _map_height(self): return self.map_y1 - self.map_y0 + 1 def _map_width(self): return self.map_x1 - self.map_x0 + 1 def _grow_map_left(self): """ To grow the map to the left, we have to add a new column. """ new_column = [None] * self._map_height() self.map = [new_column] + self.map self.map_x0 -= 1 def _grow_map_right(self): """ To grow the map to the right, we have to add a new column. """ new_column = [None] * self._map_height() self.map.append(new_column) self.map_x1 += 1 def _grow_map_up(self): """ To grow the map up, we add an unknown value to each column. """ for column in self.map: column.append(None) self.map_y1 += 1 def _grow_map_down(self): """ To grow the map down, we have to add a new unknown value to the bottom of every column. There is no simple way to add an item to the start of a list, so we create a new map using new columns and then replace our map with this one. """ new_map = [] for column in self.map: column = [None] + column new_map.append(column) self.map = new_map self.map_y0 -= 1 def remember_surroundings(self, surroundings): if DEBUG: print("---- before ---") pprint.pprint(vars(self)) if self.pos_x == self.map_x0: self._grow_map_left() if self.pos_x == self.map_x1: self._grow_map_right() if self.pos_y == self.map_y0: self._grow_map_down() if self.pos_y == self.map_y1: self._grow_map_up() x = self.pos_x - self.map_x0 y = self.pos_y - self.map_y0 self.map[x-1][y] = surroundings.left self.map[x+1][y] = surroundings.right self.map[x][y-1] = surroundings.down self.map[x][y+1] = surroundings.up if DEBUG: print("---- after ---") pprint.pprint(vars(self)) def dump(self): if DEBUG: pprint.pprint(vars(self)) chars = {None: " ", Path: ".", Wall: "#", Finish: ">", Start: "<", } for y in range(self._map_height()-1, -1, -1): for x in range(self._map_width()): if (((y + self.map_y0) == self.pos_y) and ((x + self.map_x0) == self.pos_x)): sys.stdout.write("@") else: sys.stdout.write(chars[self.map[x][y]]) sys.stdout.write("\n") def is_interesting(self, x, y): x_idx = x - self.map_x0 y_idx = y - self.map_y0 # if we do not know if the place is a path, then it is not interesting if self.map[x_idx][y_idx] != Path: return False # if it is on the edge then it is interesting if x in (self.map_x0, self.map_x1): return True if y in (self.map_y0, self.map_y1): return True # if it has an unknown square next to it then it is interesting if self.map[x_idx-1][y_idx] is None: return True if self.map[x_idx+1][y_idx] is None: return True if self.map[x_idx][y_idx-1] is None: return True if self.map[x_idx][y_idx+1] is None: return True # everything else is uninteresting return False def all_interesting(self): interesting = [] for x in range(self.map_x0, self.map_x1+1): for y in range(self.map_y0, self.map_y1+1): if self.is_interesting(x, y): interesting.append((x, y)) return interesting def _moves(self, x, y): result = [] x_idx = x - self.map_x0 y_idx = y - self.map_y0 if (x > self.map_x0) and (self.map[x_idx-1][y_idx] in (Path, Start)): result.append((x-1, y)) if (x < self.map_x1) and (self.map[x_idx+1][y_idx] in (Path, Start)): result.append((x+1, y)) if (y > self.map_y0) and (self.map[x_idx][y_idx-1] in (Path, Start)): result.append((x, y-1)) if (y < self.map_y1) and (self.map[x_idx][y_idx+1] in (Path, Start)): result.append((x, y+1)) return result @staticmethod def _cur_priority(p, pos): """ This is a very inefficient way to see if we are in the priority queue already. However, for this program it is good enough. """ for n, node in enumerate(p): if node[1] == pos: return n return -1 def find_path_to(self, x, y): """ We can use Djikstra's algorithm to find the shortest path. This won't be especially efficient, but it should work. The algorithm is described here: http://www.roguebasin.com/index.php?title=Pathfinding """ v = {} # previously visited nodes p = [] # priority queue node = (0, (self.pos_x, self.pos_y)) p.append(node) while p: cost, pos = heapq.heappop(p) # if we've reached our target, build our path and return it node_x, node_y = pos if (node_x == x) and (node_y == y): path = [] path_pos = pos while path_pos != (self.pos_x, self.pos_y): path.append(path_pos) path_pos = v[path_pos][1] path.reverse() return path # otherwise check our possible moves from here cost_nxt = cost + 1 for (x_nxt, y_nxt) in self._moves(node_x, node_y): enqueue = False est_nxt = cost_nxt + dist(x_nxt, y_nxt, x, y) if not (x_nxt, y_nxt) in v: enqueue = True else: cost_last = v[(x_nxt, y_nxt)][0] if cost_last > est_nxt: enqueue = True else: priority_idx = self._cur_priority(p, (x_nxt, y_nxt)) if priority_idx != -1: if p[priority_idx][0] > est_nxt: del p[priority_idx] enqueue = True if enqueue: p.append((est_nxt, (x_nxt, y_nxt))) heapq.heapify(p) v[(x_nxt, y_nxt)] = (est_nxt, (node_x, node_y)) return None class AStarPlayer(Player): name = "A* Player" def __init__(self): self.map = Map() def turn(self, surroundings): # TODO: save the path between turns # hack to handle victory condition if surroundings.left == Finish: return moves.LEFT if surroundings.right == Finish: return moves.RIGHT if surroundings.up == Finish: return moves.UP if surroundings.down == Finish: return moves.DOWN self.map.remember_surroundings(surroundings) if DEBUG: self.map.dump() shortest_path = None for candidate in self.map.all_interesting(): path = self.map.find_path_to(candidate[0], candidate[1]) if path is None: # this should never happen, but... continue if (shortest_path is None) or (len(path) < len(shortest_path)): shortest_path = path if DEBUG: print(shortest_path) next_pos = shortest_path[0] if DEBUG: input() if self.map.pos_x+1 == next_pos[0]: self.map.move_right() return moves.RIGHT if self.map.pos_x-1 == next_pos[0]: self.map.move_left() return moves.LEFT if self.map.pos_y+1 == next_pos[1]: self.map.move_up() return moves.UP if self.map.pos_y-1 == next_pos[1]: self.map.move_down() return moves.DOWN return "pass"
1aa7609aca58c9f7546ab422239493c0d3a3b0a4
mmsolovev/python-basics
/Solovev_Mikhail_dz_3.3.py
271
3.625
4
def thesaurus(*args): people = {} for name in args: people.setdefault(name[0], []) people[name[0]].append(name) return people print(thesaurus("Иван", "Мария", "Петр", "Илья", "Михаил", "Алексей", "Павел"))
57dbfca3f3ddf3eaf18353b599fad9670b081ad2
longsube/longsube.github.io
/HVN_gitlab/exercises/07_module_class/LONGLQ_7.1.py
1,411
3.59375
4
class Trading: def __init__(self, **goods): #goods{name:(price, quantity, size)} self.goods = goods def buyer(self,money, bags): return (money,bags) def buy(self, buyer, **goods_quantity): #goods_quantity{name:quantity} amount_money = 0 amount_size = 0 for k,v in goods_quantity.iteritems(): if v > self.goods[k][1]: return "Not enough %s"%(k) break else: amount_money += (self.goods[k][0]*v) amount_size += (self.goods[k][2]*v) if amount_money > buyer[0]: return "Not enough money to buy" # break elif amount_size > buyer[1]: return "Not enough bags for carrying" # break else: #for i in return "Buying success" if __name__ == '__main__': trading = Trading(apple=(10000, 4, 3), milks=(40000, 3, 4), beef=(100000, 3, 5)) bm = int(raw_input("Buyer money: >")) bb = int(raw_input("Buyer bags: >")) buyer = trading.buyer(bm, bb) a = int(raw_input("apple_amount: >")) m = int(raw_input("milks_amount: >")) b = int(raw_input("beef_amount: >")) print trading.buy(buyer, apple=a, milks=m, beef=b) # Buyer money: >1000000 # Buyer bags: >100 # apple_amount: >2 # milks_amount: >2 # beef_amount: >2 # Buying success
15f3f55bed1b55968cb3000d1abfe46952757031
jimohafeezco/nlp_ws
/bots/src/prayer_time.py
1,540
3.609375
4
# import required modules import requests, json from datetime import datetime # Enter your API key here def get_prayer(user_message): api_key = "0c42f7f6b53b244c78a418f4f181282a" # base_url variable to store url base_url = "http://api.aladhan.com/v1/calendarByCity?" city = "Innopolis" country = "Russia" # Give city name # city_name = input("Enter city name : ") complete_url = "http://api.aladhan.com/v1/calendarByCity?city=Innopolis&country=Russia&method=1" # get method of requests module # return response object response = requests.get(complete_url) current_date =datetime.date(datetime.now()) x = response.json() if x["code"] != "404": y = x["data"][1]["timings"] l=['Fajr', 'Dhuhr', 'Asr', 'Maghrib', 'Isha'] prayer_time= {key: y[key] for key in l} # for prayer in prayer_time.keys(): # prayers = Fajr if user_message.capitalize() in l : # print(prayer_time) prayer= user_message.capitalize() return "The time for {} on {} is {}".format(prayer, current_date, prayer_time[prayer]) elif user_message.lower() =="magrib": prayer ="Maghrib" return "The time for {} is {}".format(prayer, current_date, prayer_time[prayer]) else: return "the time for prayers today : {}, are {}".format(current_date, prayer_time) # return prayer_time else: # print(" City Not Found ") return "City not found" # print(get_prayer())
f6e5c5eaa503f06c40806736159dd6b238943c35
sohanmithinti/p-1071
/correlation.py
679
3.5
4
import numpy as np import pandas as pd import plotly.express as px import csv def getdatasource(): icecream = [] temperature = [] with open("icecreamsales.csv") as f: reader = csv.DictReader(f) print(reader) for row in reader: icecream.append(float(row["IcecreamSales"])) temperature.append(float(row["Temperature"])) print(icecream) print(temperature) return {"x":icecream, "y":temperature} def findcorrelation(datasource): correlation = np.corrcoef(datasource["x"], datasource["y"]) print(correlation[0, 1]) data = getdatasource() findcorrelation(data)
a65aa34ef32d7fced8a91153dae77e48f5cc1176
2019-fall-csc-226/a02-loopy-turtles-loopy-languages-henryjcamacho
/Camachoh- A02.py
1,133
4.15625
4
###################################################################### # Author: Henry Camacho TODO: Change this to your name, if modifying # Username: HenryJCamacho TODO: Change this to your username, if modifying # # Assignment: A02 # Purpose: To draw something we lie with loop ###################################################################### # Acknowledgements: # # original from # # licensed under a Creative Commons # Attribution-Noncommercial-Share Alike 3.0 United States License. ###################################################################### import turtle wn = turtle.Screen() circle = turtle.Turtle() circle.speed(10) circle.fillcolor("yellow") circle.begin_fill() for face in range(75): circle.forward(10) circle.right(5) circle.end_fill() eyes = turtle.Turtle() eyes.speed(10) eyes.penup() eyes.setpos(50, -50) eyes.shape("triangle") eyes.stamp() eyes.setpos (-50, -50) mouth = turtle.Turtle() mouth.speed(10) mouth.penup() mouth.setpos(-50, -100) mouth.pendown() mouth.right(90) for smile in range(30): mouth.forward(5) mouth.left(5) wn.exitonclick()
9aaf6c575136295abbec00c59b5ce50fd0a02b7d
harishkumarhm/Python-Learning
/firstScript.py
146
3.515625
4
first_number = 1+1 print(first_number) second_number = 100 +1 print(second_number) total = first_number + second_number print(total) x = 3
c1facc994bca79947e20fe4adf7890d15ee16f41
zqhappyday/myleetcode
/hard/42接雨水.py
849
3.5
4
''' 经典题目,当初是通过这个题目学会了双指针 这题只要想到到了双指针就一点也不难 这题同样可以使用二分法来做,速度会快很多 ''' class Solution: def trap(self, height: List[int]) -> int: n = len(height) left = 0 right = n - 1 res = 0 leftmax = 0 rightmax = 0 while right > left + 1 : if height[left] <= height[right]: leftmax = max(height[left],leftmax) if height[left + 1] <= leftmax: res = leftmax - height[left+1] + res left += 1 else: rightmax = max(height[right],rightmax) if height[right-1] <= rightmax: res += rightmax - height[right-1] right -= 1 return res
fbf1f445e45e174cc971321ab3f92adaa3de702b
DevRyu/Daliy_Code
/DataStructure/graph(DFS).py
1,896
3.765625
4
# 23-18 깊이우선 탐색 # BFS(Breadth First Search) : 노드들과 같은 레벨에 있은 노드들 큐방식으로 # DFS(Depth First Search) : 노드들의 자식들을 먼저 탐색하는 스택방식으로 # 스택 방식으로 visited, need_visited 방식으로 사용한다. # 방법 : visited 노드를 체우는 작업 # 1) 처음에 visited에 비어있으니 시작 노드의 키를 넣고 # 2) 시작 노드의 값에 하나의 값(처음또는마지막 인접노드들)을 need_visit에 넣는다, # 2-1) 인접노드가 2개 이상이면 둘 중 원하는 방향애 따라서 순서대로 데이터를 넣으면 된다. # 3) need_visit의 추가한 노드 키를 visited에 넣고 해당 값들을 need_visited에 넣는다. # 4) visited에 있으면 패스한다. # 5) need_visited는 스택임으로 마지막의 값을 pop해서 key값은 visited need_visited에 value를 넣음 # 6) 반복 # 예시) graph = dict() graph['A'] = ['B', 'C'] graph['B'] = ['A', 'D'] graph['C'] = ['A', 'G', 'H', 'I'] graph['D'] = ['B', 'E', 'F'] graph['E'] = ['D'] graph['F'] = ['D'] graph['G'] = ['C'] graph['H'] = ['C'] graph['I'] = ['C', 'J'] graph['J'] = ['I'] def dfs(graph,start): visited = list() need_visit = list() # 시작값 need_visit.append(start) count = 0 # need_visit == 0 이될때까지 while need_visit: count += 1 # need_visit에 마지막 값을 pop(삭제)후 node에 넣어주고 (temp역할) node = need_visit.pop() # 방문한 값에 ㅇ벗다면 if node not in visited: #방문 값에 넣어주고 visited.append(node) # node의 값을 need_visit 에 추가 need_visit.extend(graph[node]) return visited dfs(graph,'A') # 시간 복잡도 # BFS 시간복잡도 # Vertex(노드) 수 : V # Edge(간선) 수 : E # 시간 복잡도 O(v+E)
4f11d9065d690ab960835e56cb56788487d6aa3b
DevRyu/Daliy_Code
/Python/baekjoon_2920.py
1,293
3.65625
4
# 문제 # 다장조는 c d e f g a b C, 총 8개 음으로 이루어져있다. 이 문제에서 8개 음은 다음과 같이 숫자로 바꾸어 표현한다. c는 1로, d는 2로, ..., C를 8로 바꾼다. # 1부터 8까지 차례대로 연주한다면 ascending, 8부터 1까지 차례대로 연주한다면 descending, 둘 다 아니라면 mixed 이다. # 연주한 순서가 주어졌을 때, 이것이 ascending인지, descending인지, 아니면 mixed인지 판별하는 프로그램을 작성하시오. # 입력 # 첫째 줄에 8개 숫자가 주어진다. 이 숫자는 문제 설명에서 설명한 음이며, 1부터 8까지 숫자가 한 번씩 등장한다. # 출력 # 첫째 줄에 ascending, descending, mixed 중 하나를 출력한다. # 정답 def solution(data): type_ = ["ascending", "descending", "mixed"] asc = True desc = True for i in range(len(data)-1): if data[i] < data[i+1]: asc = False elif data[i] > data[i+1]: desc = False if asc: return type_[0] elif desc: return type_[1] else: return type_[2] print(solution([1, 2, 3, 4, 5, 6, 7, 8])) print(solution([8, 7, 6, 5, 4, 3, 2, 1])) print(solution([8, 1, 7, 2, 6, 3, 5, 4])) # 총 풀이 시간 및 설정 7분
b30bbbdaad7f749a52eab049027fed4ccbb881d3
DevRyu/Daliy_Code
/Python/bubble_sort.py
441
3.5625
4
def bubble(data): for i in range(len(data) -1): result = False for j in range(len(data) -i-1): if data[j] > data[j+1]: data[j], data[j+1] = data[j+1], data[j] result = True if result == False: break return data import random random_list = random.sample(range(100), 50) print(bubble(random_list)) # [0, 1, 3, 4, 6, 10, 12, 13, 14, 15, 18 ...]
aee0c755f6cc99568b1d0d258b800f91afa9c5c8
JenySadadia/Assignments-of-Python
/calc.py
685
3.984375
4
while True: op=int(input('''Enter the operation which you would like to b performed :- 1.Addition 2.Subtraction 3.Multiplication 4.Division''')) if op==1: x=int(input("enter x")) y=int(input("enter y")) print(x+y) elif op==2: x=int(input("enter x")) y=int(input("enter y")) print(x-y) elif op==3: x=int(input("enter x")) y=int(input("enter y")) print(x*y) elif op==4: x=int(input("enter x")) y=int(input("enter y")) print(x/y) else: print("invalid choice")
0e49ff158c9aacce1854660e39d4ef8c28266cc5
thewchan/python_crash_course
/python_basic/pizza1.py
477
4.09375
4
def make_pizza(*toppings): """Print the list of toppings that have been requested.""" print(toppings) make_pizza('pepperoni') make_pizza('mushrooms', 'green peppers', 'extra cheese') def make_pizza1(*toppings): """Summarize the pizza we are about to make""" print("\nMaking a pizza with the following toppings:") for topping in toppings: print(f"- {topping}") make_pizza1('pepperoni') make_pizza1('mushrooms', 'green peppers', 'extra cheese')
790c7add244f5bed8e7b70a400cfc61f6e82f1ad
thewchan/python_crash_course
/python_basic/admin.py
673
4.03125
4
usernames = ['admin', 'jaden', 'will', 'willow', 'jade'] if usernames: for username in usernames: if username == 'admin': print(f"Hello {username.title()}, would you like to see a status "+ "report?") else: print(f"Hello {username.title()}, thank you for logging in again.") else: print("We need to find some users!\n") current_users = usernames[:] new_users = ['jaden', 'john', 'hank', 'Will', 'cody'] for new_user in new_users: if new_user.lower() in current_users: print(f"{new_user}, you will need a differnt username.") else: print(f"{new_user}, this username is available.")
b8ac3fd6403e0903d4cee84188d0066548a26593
thewchan/python_crash_course
/python_basic/counting_lists.py
551
3.90625
4
#list exercises numbers = range(1, 21) #for number in numbers: # print(number) numbers = range(1, 1_000_001) #for number in numbers: # print(number) million_list = list(range(1, 1_000_001)) print(min(million_list)) print(max(million_list)) print(sum(million_list)) odd_numbers = range(1, 21, 2) for number in odd_numbers: print(number) threes = range(3, 31, 3) for three in threes: print(three) numbers = range(1,11) for number in numbers: print(number ** 3) cubes = [number ** 3 for number in range(1,11)] print(cubes)
91ea218914b1e1e678308f8f2dce8f2422e8af38
thewchan/python_crash_course
/python_basic/movie_tickets.py
341
4.09375
4
age = "" while age != 'quit': age = input("What is your age?\n(Enter 'quit' to exit program) ") if age == 'quit': continue elif int(age) < 3: print("Your ticket is free!") elif int(age) < 12: print("Your ticket price is $10.") elif int(age) >= 12: print("Your ticket price is $15.")
084d8fa68428b070de38472353b3517f5d0cdfa0
Shobhit05/Linux-and-Python-short-scripts
/csvfilereader.py
503
3.75
4
import csv with open('something.csv') as csvfile: readcsv=csv.reader(csvfile,delimiter=',') dates=[] colors=[] for row in readcsv: print row color=row[3] date=row[1] colors.append(color) dates.append(date) print dates print colors try: #some of ur code if it gives the error now except Exception,e: print(e) print('sahdias') print(''' so this is a perfect exapmple of printing the code in another line ''')
5c703ed90acda4eaba3364b6f510d28622ddc4a0
ndenisj/web-dev-with-python-bootcamp
/Intro/pythonrefresher.py
1,603
4.34375
4
# Variables and Concatenate # greet = "Welcome To Python" # name = "Denison" # age = 6 # coldWeather = False # print("My name is {} am {} years old".format(name, age)) # Concatenate # Comment: codes that are not executed, like a note for the programmer """ Multi line comment in python """ # commentAsString = """ # This is more like # us and you can not do that with me # or i will be mad # """ # print(commentAsString) # If statement # if age > 18: # print("You can VOTE") # elif age < 10: # print("You are a baby") # else: # print("You are too young") # FUNCTIONS # def hello(msg, msg2=""): #print("This is a function - " + msg) # hello("Hey") # hello("Hey 2") # LIST - Order set of things like array # names = ["Dj", "Mike", "Paul"] # names.insert(1, "Jay") # # print(names[3]) # # del(names[3]) # # print(len(names)) # length # names[1] = "Peter" # print(names) # LOOPS # names = ["Dj", "Mike", "Paul"] # for name in names: # #print(name) # for x in range(len(names)): # print(names[x]) # for x in range(0, 5): # print(x) # age = 2 # while age < 3: # print(age) # age += 1 # DICTIONARY # allnames = {'Paul': 23, 'Patrick': 32, 'Sally': 12} # print(allnames) # print(allnames['Sally']) # CLASSES # class Dog: # dogInfo = 'Dogs are cool' # # Constructor of the class # def __init__(self, name, age): # self.name = name # self.age = age # def bark(self): # print('Bark - ' + self.dogInfo) # myDog = Dog("Denis", 33) # create an instance or object of the Dog Class # myDog.bark() # print(myDog.age)
590ea704b57b48282c9b8af409c5c5076244a434
ndenisj/web-dev-with-python-bootcamp
/Intro/listDict.py
436
3.90625
4
# LIST names = ['Patrick', 'Paul', 'Maryann', 'Daniel'] # # print(names) # # print(names[1]) # # print(len(names)) # del (names[3]) # names.append("Dan") # print(names) # names[2] = 'Mary' # print(names) for x in range(len(names)): print(names[x]) # DICTIONARY # programmingDict = { # "Name": "Tega", # "Problem": "Thumb Issue", # "Solution": "Go home and rest" # } # print("NAME {}".format(programmingDict['Name'],))
6a34f3d820de100c471e0a8e82cb5372e2eced85
regi18/offset-chiper
/offset-chiper.py
1,914
4.03125
4
""" Decode and Encode text by changing each char by the given offset Created by: regi18 Version: 1.0.4 Github: https://github.com/regi18/offset-chiper """ import os from time import sleep print(""" ____ __ __ _ _____ _ _ / __ \ / _|/ _| | | / ____| | (_) | | | | |_| |_ ___ ___| |_ ______ | | | |__ _ _ __ ___ _ __ | | | | _| _/ __|/ _ \ __| |______| | | | '_ \| | '_ \ / _ \ '__| | |__| | | | | \__ \ __/ |_ | |____| | | | | |_) | __/ | \____/|_| |_| |___/\___|\__| \_____|_| |_|_| .__/ \___|_| | | |_| Created by regi18 """) while True: # reset variables plaintext = "" answer = input("\nDecode(d), Encode(e) or Quit(q)? ").upper() print("\n") # Change every char into his decimal value, add (or subtract) the offset and than save it in plain text. try: if answer == "D": offset = int(input("Enter the offset: ")) text = input("Enter the text to decode: ") for i in text: plaintext += chr((ord(i) - offset)) elif answer == "E": offset = int(input("Enter the offset: ")) text = input("Enter the text to encode: ") for i in text: plaintext += chr((ord(i) + offset)) elif answer == "Q": break else: raise ValueError except ValueError: # handle errors print("\nError, the entered value is not correct\n") sleep(1.2) os.system('cls') continue print("The text is: {}".format(plaintext)) print("") os.system("pause") os.system('cls')
23bdbbe3a731836ff6897d7d15a9feebd191dea2
yongjoons/test1
/019.py
149
3.765625
4
try : num=int(input('enter : ')) print(10/num) except ZeroDivisionError : print('zero') except ValueError: print('num is not int')
d0ee097dd1a70c65be165d7911acfbc09659f199
dokurin/dokushokai
/season2-DDD/cargo-system/sample/customer.py
346
3.5
4
from typing import NewType ID = NewType("CustomerID", str) class Customer(object): """顧客Entity Args: id (ID): 顧客ID name (str): 氏名 Attrubutes: id (ID): 顧客ID name (str): 氏名 """ def __init__(self, id: str, name: ID) -> None: self.id = id self.name = name
313575eca38588d312890f248e02831afcdc65bb
yeming0923/12
/zh_即时标记/002_PYthon callable()函数.py
882
4.03125
4
''' 描述 callable() 函数用于检查一个对象是否是可调用的。如果返回 True,object 仍然可能调用失败;但如果返回 False,调用对象 object 绝对不会成功。 对于函数、方法、lambda 函式、 类以及实现了 __call__ 方法的类实例, 它都返回 True。 语法 callable()方法语法: callable(object) >> > callable(0) False >> > callable("runoob") False >> > def add(a, b): ... return a + b ... >> > callable(add) # 函数返回 True True >> > class A: # 类 ... def method(self): ... return 0 ... >> > callable(A) # 类返回 True True >> > a = A() >> > callable(a) # 没有实现 __call__, 返回 False False >> > class B: ... def __call__(self): ... return 0 ''' ... >> > callable(B) True >> > b = B() >> > callable(b) # 实现 __call__, 返回 True True
4dedc11bbcb4cf48033088f8cb65e49f59faa0ed
budidino/AoC-python
/2020-d9.py
930
3.515625
4
INPUT = "2020-d9.txt" numbers = [int(line.rstrip('\n')) for line in open(INPUT)] from itertools import combinations def isValid(numbers, number): for num1, num2 in combinations(numbers, 2): if num1 + num2 == number: return True return False def findSuspect(numbers, preamble): for index, number in enumerate(numbers[preamble:], preamble): num = numbers[index-preamble:index] if not isValid(num, number): return number return 0 def findWeakness(numbers, suspect): low, high = 0, 1 setSum = numbers[low] + numbers[high] while setSum != suspect: if setSum < suspect: high += 1 setSum += numbers[high] else: setSum -= numbers[low] low += 1 return min(numbers[low:high+1]) + max(numbers[low:high+1]) suspect = findSuspect(numbers, 25) print(f"part 1: {suspect}") # 257342611 weakness = findWeakness(numbers, suspect) print(f"part 2: {weakness}") # 35602097
019b895273e8298815a4547eb0dde193fd71b8a3
budidino/AoC-python
/2019-d3.py
1,152
3.640625
4
INPUT = "2019-d3.txt" wires = [string.rstrip('\n') for string in open(INPUT)] wire1 = wires[0].split(',') wire2 = wires[1].split(',') from collections import defaultdict path = defaultdict() crossingDistances = set() # part 1 crossingSteps = set() # part 2 def walkTheWire(wire, isFirstWire): x, y, steps = 0, 0, 0 for step in wire: direction = step[0] distance = int(step[1:]) while distance > 0: steps += 1 distance -= 1 if direction == "L": x -= 1 elif direction == "R": x += 1 elif direction == "U": y += 1 else: y -= 1 key = (x, y) if isFirstWire and not key in path: path[key] = steps elif not isFirstWire and key in path: crossingDistances.add(abs(x) + abs(y)) crossingSteps.add(path[key] + steps) walkTheWire(wire1, True) walkTheWire(wire2, False) print(f"part 1: {min(crossingDistances)}") print(f"part 2: {min(crossingSteps)}")
e9812329ff0bf1398fe67004e49a79a1d0075b6c
budidino/AoC-python
/2020-d2.py
443
3.5625
4
INPUT = "2020-d2.txt" strings = [string.strip('\n') for string in open(INPUT)] part1, part2 = 0, 0 for string in strings: policy, password = string.split(': ') numbers, letter = policy.split(' ') minVal, maxVal = map(int, numbers.split('-')) part1 += minVal <= password.count(letter) <= maxVal part2 += (password[minVal-1] == letter) != (password[maxVal-1] == letter) print(f"part 1: {part1}\npart 2: {part2}") # 548 # 502
53c640630c6f2bdfc7199cbe241af57b58e77652
budgiena/domaci_projekty_ZuzkaV
/ukol4_13.py
854
3.765625
4
# --- domaci projekty 4 - ukol 13 --- pocet_radku = int(input("Zadej pocet radku (a zaroven sloupcu): ")) """ # puvodni varianta ##for cislo_radku in range(pocet_radku): ## if cislo_radku in (0,pocet_radku-1): ## for prvni_posledni in range(pocet_radku): ## print ("X", end = " ") ## print ("") ## else: ## for cislo_sloupce in range (pocet_radku): ## if cislo_sloupce in (0,pocet_radku-1): ## print ("X", end = " ") ## else: ## print (" ", end = " ") ## print ("") ## """ for cislo_radku in range(pocet_radku): for cislo_sloupce in range(pocet_radku): if (cislo_radku in (0, pocet_radku-1)) or (cislo_sloupce in (0, pocet_radku-1)): print ("X", end = " ") else: print (" ", end = " ") print ("")
847cf25b568b9ced3123114bafa3e4088c5fb8ef
limiteddays/Programming-tips
/node.py
1,618
3.8125
4
class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: temp1 = "" temp2 = "" current_node_1 = l1 current_node_2 = l2 while True: if current_node_1.next == None: temp1 = str(current_node_1.val) + temp1 break else: temp1 = str(current_node_1.val) + temp1 current_node_1 = current_node_1.next while True: if current_node_2.next == None: temp2 = str(current_node_2.val) + temp2 break else: temp2 = str(current_node_2.val) + temp2 current_node_2 = current_node_2.next # ans_list = (list(val1 + val2)).reverse() temp3 = int(temp1) + int(temp2) temp3 = str(temp3)[::-1] i = 0 for x in temp3: if i == 0: ans_node = ListNode(int(x),None) current_node = ans_node else: new_node = ListNode(int(x),None) current_node.next = new_node current_node = new_node i += 1 return ans_node if __name__ == '__main__': c = ListNode(1,None) b = ListNode(2,c) a = ListNode(3,b) sol = Solution() print(sol.addTwoNumbers(a,a))
461af0dc439dfcf33b2dd0bfcf6d4a684949171d
limiteddays/Programming-tips
/forge_rever.py
473
3.796875
4
class Tree(object): x = 0 l = None r = None def traverse(sub_tree, height): left_height = 0 right_height = 0 if sub_tree.l: left_height = traverse(sub_tree.l, height + 1) if sub_tree.r: right_height = traverse(sub_tree.r, height + 1) if sub_tree.l or sub_tree.r: return max(left_height, right_height) else: return height def solution(T): # write your code in Python 3.6 return traverse(T, 0)
6929627ac4b226a8364a5708b8243b2f9eddf454
jaydeu/Python-Programs
/Aug_12_2015.py
2,815
3.65625
4
######################################################## ### Daily Programmer 226 Intermediate - Connect Four ### ######################################################## # Source: r/dailyprogrammer ''' This program tracks the progress of a game of connect-four, checks for a winner, then outputs the number of moves and position of four winning pieces. ''' import pandas as pd from pandas import DataFrame from math import floor import sys ### Read in the list of moves from a text file f = open('inputs\226_int_2.txt', 'r') ### Create a game board board = DataFrame(index=range(1,7), columns=list('ABCDEFG')) board = board.fillna('.') ### Initialize next free space and move count dictionaries next_free_space = {'A':6, 'B':6, 'C':6, 'D':6, 'E':6, 'F':6, 'G':6} move_count = {'X':0, 'O':0} ### Function that adds a move to the board def add_move(col, player): global board, next_free_space, move_count board[col][next_free_space[col]] = player next_free_space[col] -= 1 move_count[player] += 1 ### Create our sequences to check for winners sequences = [] # rows for i in range(0,6): sequences.append(range(7*i, 7+7*i)) # columns for i in range(0,7): sequences.append([7*j + i for j in range(0,6)]) # diagonals diag_length = [4,5,6,6,5,4] # diagonals right diags_right = [14,7,0,1,2,3] for i in range(0,len(diags_right)): sequences.append([8*j + diags_right[i] for j in range(0, diag_length[i])]) # diagonals left diags_left= [3,4,5,6,13,20] for i in range(0,len(diags_left)): sequences.append([6*j + diags_left[i] for j in range(0, diag_length[i])]) ### Function that changes an index number to coordinates def num_to_coord(n): row = int(floor(n/7))+1 col = list('ABCDEFG')[n%7] return str(col)+str(row) ### Function to be run when a winner is found. Prints number of moves, winning positions and the final board. def winner_found(player,code, vector, line): print "%s is a winner in %d moves!" % (player, move_count[player]) start = line.find(code) for i in range(0,4): print num_to_coord(vector[start+i]) print board f.close() sys.exit() ### Function that checks for winners def check_winners(): boardList = board.values.flatten() for s in sequences: check_line = "".join([boardList[i] for i in s]) if "XXXX" in check_line: winner_found('X','XXXX', s, check_line) if "OOOO" in check_line: winner_found('O','OOOO', s, check_line) ########################################## for line in f: next = line.split(" ") move_X = next[0] move_O = next[1].upper().rstrip() #Add an X add_move(move_X, 'X') check_winners() #Add an O add_move(move_O, 'O') check_winners() f.close() print "Nobody won!"
1c32272ef45f6e6958cee58d95088c5b475269b1
srgiola/UniversidadPyton_Udemy
/Fundamentos Python/Tuplas.py
808
4.28125
4
# La tupla luego de ser inicializada no se puede modificar frutas = ("Naranja", "Platano", "Guayaba") print(frutas) print(len(frutas)) print(frutas[0]) # Acceder a un elemento print(frutas[-1]) # Navegación inversa #Tambien funcionan los rangos igual que en las listas print(frutas[0:2]) # Una Lista se puede inicializar con una tubpla frutasLista = list(frutas) frutasLista[1] = "Platanito" # Una tupla se puede modificar, metiendo una lista que sustituye su valor frutas = tuple(frutasLista) # Iterar sobre la tupla, esto se realiza de igual manera que con las listas for fruta in frutas: print(fruta, end=" ") #El end=" " indica como queremos que finalize el imprimir fruta #Tarea tupla = (13, 1, 8, 3, 2, 5, 8) lista = [] for t in tupla: if t < 5: lista.append(t) print(lista)
236756b3ed86fc33bb38ab279c03792e6aa312a6
srgiola/UniversidadPyton_Udemy
/Fundamentos Python/Clases.py
2,012
3.953125
4
class Persona: #Contructor def __init__(self, nombre, edad): self.nombre = nombre self.edad = edad class Aritmetica: #Constructor def __init__(self, num1, num2): self.num1 = num1 self.num2 = num2 def suma(self): return self.num1 + self.num2 class Retangulo: #Constructor def __init__(self, base, altura): self.base = base self.altura = altura def calcularArea(self): return self.base * self.altura class Caja: #Contructor def __init__(self, largo, ancho, alto): self.largo = largo self.ancho = ancho self.alto = alto def Volumen(self): return self.largo * self.ancho * self.alto #El parametro self se puede cambiar por cualquier otro palabra siempre y # cuando se utilice de la misma manera, asi mismo se puede colocar otros # nombres a los parametros y lo que quedaran como nombres de los atributos # son los que esten con self class Carro: #Constructor def __init__(this, n, e, *v, **d): #El "*" significa que el parametro es una tupla y es opcional this.marca = n # el "**" significa que el parametro es un diccionario y es opcional this.modelo = e this.valores = v this.diccionario = d def desplegar(this): print("Marca:", this.marca) print("Modelo:", this.modelo) print("Valores (Tupla):", this.valores) print("Dicionario:", this.diccionario) carro = Carro("Toyota", "Yaris", 2,4,5) print(carro.desplegar()) carro2 = Carro("Volvo", "S40", 4,9,5, m="Manzana", p="Pera", j="Jicama") print(carro2.desplegar()) #Instanciar una clase persona = Persona("Sergio", 22) print(persona.nombre, persona.edad) aritmetica = Aritmetica(2, 4) print("Resultado suma:", aritmetica.suma()) base = int(input("Ingrese base del Retangulo: ")) altura = int(input("Ingrese altura del retangulo: ")) retangulo = Retangulo(base, altura) print(retangulo.calcularArea())
3c004f1b944ab083ef565a4e48106303ee124904
srgiola/UniversidadPyton_Udemy
/Fundamentos Python/Metodos Privados.py
500
3.53125
4
class Persona: def __init__(self, nombre, apellido, apodo): self.nombre = nombre #Atributo public self._apellido = apellido #Atributo protected "_" self.__apodo = apodo #Atributo privado "__" def metodoPublico(self): self.__metodoPrivado() def __metodoPrivado(self): print(self.nombre) print(self._apellido) print(self.__apodo) p1 = Persona("Sergio", "Lara", "Chejo") print(p1.nombre) print(p1._apellido)
5ad72e3d56246bc745fb208eb7e8a74860c66a3d
srgiola/UniversidadPyton_Udemy
/Fundamentos Python/Manejo de Archivos.py
1,214
3.78125
4
#Abre un archivo # open() tiene dos parametros, el primero el archivo y el segundo lo que se desea hacer # r - Read the default value. Da error si no existe el archivo # a - Agrega info al archivo. Si no existe lo crea # w - Escribir en un archivo. Si no existe lo crea. Sobreescribe el archivo # x - Crea un archivo. Retorna error si el archivo ya existe try: archivo = open("File_Manejo_Archivos.txt", "w") archivo.write("Agregando información al archivo \n") archivo.write("Agregando linea 2") archivo = open("File_Manejo_Archivos.txt", "r") ''' Formas de leer un archivo print(archivo.read()) # Leer archivo completo print(archivo.read(5)) # Numero de caracteres a leer print(archivo.readline()) # Leer una linea print(archivo.readlines()) # Lee todas las linea, agrega todo a una lista print(archivo.readlines()[1]) # Lee solo la linea con indice 1 for linea in archivo: print(linea) ''' # Copiando un archivo a otro archivo2 = open("File_Copia.txt", "w") archivo2.write(archivo.read()) except Exception as e: print(e) finally: archivo.close() # No es obligatorio archivo2.close()
409574344dcb3ca84b2da297f0dfa35d721fd7b2
gitter-badger/cayenne
/cayenne/results.py
7,558
3.625
4
""" Module that defines the `Results` class """ from collections.abc import Collection from typing import List, Tuple, Iterator from warnings import warn import numpy as np class Results(Collection): """ A class that stores simulation results and provides methods to access them Parameters ---------- species_names : List[str] List of species names rxn_names : List[str] List of reaction names t_list: List[float] List of time points for each repetition x_list: List[np.ndarray] List of system states for each repetition status_list: List[int] List of return status for each repetition algorithm: str Algorithm used to run the simulation sim_seeds: List[int] List of seeds used for the simulation Notes ----- The status indicates the status of the simulation at exit. Each repetition will have a status associated with it, and these are accessible through the ``status_list``. 1: Succesful completion, terminated when ``max_iter`` iterations reached. 2: Succesful completion, terminated when ``max_t`` crossed. 3: Succesful completion, terminated when all species went extinct. -1: Failure, order greater than 3 detected. -2: Failure, propensity zero without extinction. """ def __init__( self, species_names: List[str], rxn_names: List[str], t_list: List[np.ndarray], x_list: List[np.ndarray], status_list: List[int], algorithm: str, sim_seeds: List[int], ) -> None: self.species_names = species_names self.rxn_names = rxn_names self.x_list = x_list self.t_list = t_list self.status_list = status_list self.algorithm = algorithm self.sim_seeds = sim_seeds if not self._check_consistency(): raise ValueError("Inconsistent results passed") def _check_consistency(self) -> bool: """ Check consistency of results Returns ------- bool True if results are consistent False otherwise """ if ( len(self.x_list) == len(self.t_list) == len(self.status_list) == len(self.sim_seeds) ): pass else: return False for x, t, status in self: if x.shape[0] != t.shape[0]: return False if x.shape[1] != len(self.species_names): return False if not isinstance(status, int): return False return True def __repr__(self) -> str: """ Return summary of simulation. Returns ------- summary: str Summary of the simulation with length of simulation, algorithm and seeds used. """ summary = f"<Results species={self.species_names} n_rep={len(self)} " summary = summary + f"algorithm={self.algorithm} sim_seeds={self.sim_seeds}>" return summary def __str__(self) -> str: """ Return self.__repr__() """ return self.__repr__() def __iter__(self) -> Iterator[Tuple[np.ndarray, np.ndarray, int]]: """ Iterate over each repetition """ return zip(self.x_list, self.t_list, self.status_list) def __len__(self) -> int: """ Return number of repetitions in simulation Returns ------- n_rep: int Number of repetitions in simulation """ n_rep = len(self.x_list) return n_rep def __contains__(self, ind: int): """ Returns True if ind is one of the repetition numbers """ if ind < len(self): return True else: return False def __getitem__(self, ind: int) -> Tuple[np.ndarray, np.ndarray, int]: """ Return sim. state, time points and status of repetition no. `ind` Parameters ---------- ind: int Index of the repetition in the simulation Returns ------- x_ind: np.ndarray Simulation status of repetition no. `ind` t_ind: np.ndarray Time points of repetition no. `ind` status_ind Simulation end status of repetition no. `ind` """ if ind in self: x_ind = self.x_list[ind] t_ind = self.t_list[ind] status_ind = self.status_list[ind] else: raise IndexError(f"{ind} out of bounds") return x_ind, t_ind, status_ind @property def final(self) -> Tuple[np.ndarray, np.ndarray]: """ Returns the final times and states of the system in the simulations Returns ------- Tuple[np.ndarray, np.ndarray] The final times and states of the sytem """ final_times = np.array([v[1][-1] for v in self]) final_states = np.array([v[0][-1, :] for v in self]) return final_times, final_states def get_state(self, t: float) -> List[np.ndarray]: """ Returns the states of the system at time point t. Parameters ---------- t: float Time point at which states are wanted. Returns ------- List[np.ndarray] The states of the system at `t` for all repetitions. Raises ------ UserWarning If simulation ends before `t` but system does not reach extinction. """ states: List[np.ndarray] = [] e = np.finfo(float).eps * t t = t + e for x_array, t_array, s in self: ind = np.searchsorted(t_array, t) ind = ind - 1 if ind > 0 else ind if ind == len(t_array) - 1: states.append(x_array[-1, :]) if s != 3: warn(f"Simulation ended before {t}, returning last state.") else: x_interp = np.zeros(x_array.shape[1]) if self.algorithm != "direct": for ind2 in range(x_array.shape[1]): x_interp[ind2] = np.interp( t, [t_array[ind], t_array[ind + 1]], [x_array[ind, ind2], x_array[ind + 1, ind2]], ) states.append(x_interp) else: states.append(x_array[ind, :]) return states def get_species(self, species_names: List[str]) -> List[np.ndarray]: """ Returns the species concentrations only for the species in species_names Parameters --------- species_names : List[str] The names of the species as a list Returns ------ List[np.ndarray] Simulation output of the selected species. """ x_list_curated = [] species_inds = [self.species_names.index(s) for s in species_names] for rep_ind in range(len(self)): x_list_curated.append(self[rep_ind][0][:, species_inds]) return x_list_curated
10194946199773e708b6a020c01dd7f01af2efee
FlyingSparkie/Raspberry-Pi-stuff
/gpioLed.py
1,582
3.75
4
import RPi.GPIO as GPIO #import the gpio library from time import sleep #import time library redLed=22 #what pin greenLed=23 blinkTimes=[0,1,2,3,4] button=17 inputButton=False range(5) GPIO.setmode(GPIO.BCM) #set gpio mode BCM, not BOARD GPIO.setup(greenLed, GPIO.OUT) #make it an output GPIO.setup(redLed, GPIO.OUT) #make it an output GPIO.setup(button, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) #GPIO.output(yellowLed, False) #turn on(True) off(False) #GPIO.cleanup() #reset the pins #GPIO.setmode(GPIO.BCM) #while True: # GPIO.output(yellowLed, True) # sleep(1) # GPIO.output(yellowLed, False) # sleep(1) #iterate list to blink variable #for i in blinkTimes: # GPIO.output(yellowLed, True) # sleep(1) # GPIO.output(yellowLed, False) # sleep(1) try: while True: # inputButton=GPIO.input(button) #if inputButton==True: # print("Buttun pressed") sleep(3) #range example for i in range(5): GPIO.output(greenLed, True) sleep(1) GPIO.output(greenLed, False) sleep(1) for i in range(5): GPIO.output(greenLed, True) sleep(.25) GPIO.output(greenLed, False) sleep(.25) for i in range(3): GPIO.output(redLed, True) sleep(4) GPIO.output(redLed, False) sleep(.25) except KeyboardInterrupt: print("Finished") GPIO.cleanup()
fefc1ce3e2a8afcb32c09d05242089acfba1d567
ZahedAli97/Py-DataStructures
/circularlinkedlist.py
1,829
3.75
4
class Node: def __init__(self, data): self.data = data self.next = None class CircularLinkedList: def __init__(self): self.head = None def taverse(self): temp = self.head if self.head is not None: while True: print(temp.data, end="") print("->", end="") temp = temp.next if temp == self.head: break print("") def addNode(self, data): new = Node(data) temp = self.head new.next = temp if self.head: while temp.next != self.head: temp = temp.next temp.next = new else: new.next = new self.head = new def deleteNode(self, data): temp = self.head prev = self.head while temp.next.data != data: prev = temp.next temp = temp.next temp = temp.next prev.next = temp.next def reverseList(self): prev = None current = self.head # post = current.next # current.next = prev # current = post back = current while current.next != self.head: post = current.next current.next = prev prev = current current = post current.next = prev self.head = current back.next = self.head if __name__ == "__main__": cll = CircularLinkedList() cll.addNode(1) cll.addNode(2) cll.addNode(3) cll.taverse() cll.deleteNode(2) cll.taverse() cll.addNode(7) cll.addNode(10) cll.addNode(29) cll.addNode(32) cll.taverse() cll.deleteNode(10) cll.taverse() cll.reverseList() cll.taverse() cll.reverseList() cll.taverse()
ba2ac685e5bb3fa8a3632b8ddf46fb804113c8ca
Elmuti/tools
/downloader/downloader.py
346
3.5625
4
# File downloader - downloads files from a list # Usage: # python downloader.py links.txt /downloaddir/ import urllib, sys links = sys.argv[1] dldir = sys.argv[2] for line in open(links, "r"): filename = line.split("/")[-1].rstrip('\n') filepath = dldir+filename print "Downloading: ",filename urllib.urlretrieve(line, filepath)
d343dd2b8da73751e837c98ec58ec0fb7b734080
AYSEOTKUN/my-projects
/python/hands-on/flask-04-handling-forms-POST-GET-Methods/Flask_GET_POST_Methods_1/app.py
1,011
3.5625
4
# Import Flask modules from flask import Flask,render_template,request # Create an object named app app = Flask(__name__) # Create a function named `index` which uses template file named `index.html` # send three numbers as template variable to the app.py and assign route of no path ('/') @app.route('/') def index(): return render_template('index.html') # calculate sum of them using inline function in app.py, then sent the result to the # "number.hmtl" file and assign route of path ('/total'). # When the user comes directly "/total" path, "Since this is GET # request, Total hasn't been calculated" string returns to them with "number.html" file @app.route('/',methods=["GET","POST"]) def total(): if request.method =="POST": value1 = request.form.get("value1") value2 = request.form.get("value2") value3 = request.form.get("value3") return render_template("number.html") if __name__ == '__main__': #app.run(debug=True) app.run(host='0.0.0.0', port=80)
f02b8bd1b982abd5bfa37caba9922ae191d9f551
tejashrikelhe/Collatz-conjecture
/collatez conjecture.py
1,214
3.8125
4
# -*- coding: utf-8 -*- """ Created on Wed Jun 17 22:46:10 2020 @author: TEJASHRI """ import matplotlib.pyplot as plt y=[] x=[] a=1 while(a==1): i=0 n=int(input("enter a no=")) x.append(n) while(n!=1): if(n%2==0): n=n/2 print(n) else: n=(3*n)+1 print(n) i=i+1 y.append(i) print("Number of itteration for given ip=") print(i) a=int(input("do you want to continue? If yes enter 1, else enter 0=")) #plot for number of iterations needed for a given input plt.plot(x,y) # naming the x axis plt.xlabel('input value') # naming the y axis plt.ylabel('number of itterations') plt.title('number of iterations needed for a given input') plt.show() #Histogram # setting the ranges and no. of intervals range = (0,100) bins = 10 # plotting a histogram #plt.hist(x, bins, range, color = 'blue', histtype = 'bar', rwidth = 0.8) plt.hist(x,bins,range) # x-axis label plt.xlabel('Input Number') # frequency label plt.ylabel('No. of itterations') plt.title('histogram of Number and itterations') plt.show()
4776ee86a215e14e367a14b74073c1c712233dc6
suyash248/ds_algo
/Array/flipZeroesMaximizeOnes.py
2,484
3.703125
4
# Time complexity: O(n) # Using sliding window strategy. from typing import List def flip_m_zeroes_largest_subarray_with_max_ones(arr, m): """ Algorithm - - While `zeroes_count` is no more than `m` : expand the window to the right (w_right++) and increment the zeroes_count. - While `zeroes_count` exceeds `m`, shrink the window from left (w_left++), decrement `zeroes_count`. - Update the widest window(`best_w_left`, `best_w_size`) along the way. The positions of output 0's are inside the best window. :param arr: Input array. :param m: Maximum number of 0's that can be flipped in `arr` in order to get largest window/sub-array of 1's. :return: """ w_left = w_right = best_w_left = best_w_size = zeroes_count = 0 while w_right < len(arr): if zeroes_count <= m: if arr[w_right] == 0: zeroes_count += 1 w_right += 1 if zeroes_count > m: if arr[w_left] == 0: zeroes_count -= 1 w_left += 1 curr_w_size = w_right - w_left if curr_w_size > best_w_size: best_w_left = w_left best_w_size = curr_w_size best_w_right = best_w_left + best_w_size - 1 best_w = (best_w_left, best_w_right) flip_zero_at_indices = [] for i in range(best_w_left, best_w_right+1): # for i=0; i < best_w_size; i++ if arr[i] == 0: flip_zero_at_indices.append(i) return { "largestWindow": best_w, "largestWindowSize": best_w_size, "flipZeroAtIndices": flip_zero_at_indices } if __name__ == '__main__': ################### TC - 1 ################### nums = [1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0] threshold = 2 window_details = flip_m_zeroes_largest_subarray_with_max_ones(nums, threshold) print("Flip 0's at indices {flipZeroAtIndices} to get the maximum window/sub-array of size {largestWindowSize} " \ "where window start & end indices are {largestWindow}".format(**window_details)) ################### TC - 2 ################### nums = [0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1] threshold = 3 window_details = flip_m_zeroes_largest_subarray_with_max_ones(nums, threshold) print("Flip 0's at indices {flipZeroAtIndices} to get the maximum window/sub-array of size {largestWindowSize} " \ "where window start & end indices are {largestWindow}".format(**window_details))
8212efa038c42c118856cb6a50b0d7e9ce1844d2
suyash248/ds_algo
/Tree/traversals.py
2,036
3.921875
4
from Tree.commons import insert, print_tree, is_leaf def preorder(root): if root: print(root.key, end=',') preorder(root.left) preorder(root.right) def inorder(root): if root: inorder(root.left) print(root.key, end=',') inorder(root.right) def postorder(root): if root: postorder(root.left) postorder(root.right) print(root.key, end=',') def level_order(root): from queue import Queue q = Queue() q.put(root) while not q.empty(): popped_elt = q.get() print(popped_elt.key, end=',') if popped_elt.left: q.put(popped_elt.left) if popped_elt.right: q.put(popped_elt.right) def spiral(root): stack1 = [root] stack2 = [] while len(stack1) or len(stack2): while len(stack1): popped_node = stack1.pop() print(popped_node.key, end=',') # left first then right if popped_node.left is not None: stack2.append(popped_node.left) if popped_node.right is not None: stack2.append(popped_node.right) while len(stack2): popped_node = stack2.pop() print(popped_node.key, end=',') # right first then left if popped_node.right is not None: stack1.append(popped_node.right) if popped_node.left is not None: stack1.append(popped_node.left) # Driver program to test above function if __name__ == "__main__": """ Let us create following BST 50 / \ 30 70 / \ / \ 20 40 60 80 """ root = None root = insert(root, 50) insert(root, 30) insert(root, 20) insert(root, 40) insert(root, 70) insert(root, 60) insert(root, 80) print("In-Order is - ") inorder(root) print("\nPre-Order is - ") preorder(root) print("\nPost-Order is - ") postorder(root) print("\nLevel-Order is - ") level_order(root) print("\nSprial(zig-zag)-Order is - ") spiral(root)
57bade1fd06c0bf6e9814bea60b5e4e6a8d35163
suyash248/ds_algo
/Queues/queueUsingStack.py
1,364
4.15625
4
class QueueUsingStack(object): __st1__ = list() __st2__ = list() def enqueue(self, elt): self.__st1__.append(elt) def dequeue(self): if self.empty(): raise RuntimeError("Queue is empty") if len(self.__st2__) == 0: while len(self.__st1__) > 0: self.__st2__.append(self.__st1__.pop()) return self.__st2__.pop() def size(self): return len(self.__st1__) + len(self.__st2__) def empty(self): return len(self.__st1__) == 0 and len(self.__st2__) == 0 if __name__ == '__main__': q = QueueUsingStack() choices = "1. Enqueue\n2. Dequeue\n3. Size\n4. Is Empty?\n5. Exit" while True: print choices choice = input("Enter your choice - ") if choice == 1: elt = raw_input("Enter element to be enqueued - ") q.enqueue(elt) elif choice == 2: try: elt = q.dequeue() print "Dequeued:", elt except Exception as e: print "Error occurred, queue is empty?", q.empty() elif choice == 3: print "Size of queue is", q.size() elif choice == 4: print "Queue is", "empty" if q.empty() else "not empty." elif choice == 5: break else: print "Invalid choice"
589fe67c8ae98e36a621432ab7abb275156172cd
suyash248/ds_algo
/Misc/sliding_window/count_good_strings.py
2,108
3.875
4
''' A string is good if there are no repeated characters. Given a string s and integer k, return the number of good substrings of length k in s​​​​​​. Note that if there are multiple occurrences of the same substring, every occurrence should be counted. A substring is a contiguous sequence of characters in a string. Example 1: Input: s = "xyzzaz", k = 3 Output: 1 Explanation: There are 4 substrings of size 3: "xyz", "yzz", "zza", and "zaz". The only good substring of length 3 is "xyz". Example 2: Input: s = "aababcabc", k = 3 Output: 4 Explanation: There are 7 substrings of size 3: "aab", "aba", "bab", "abc", "bca", "cab", and "abc". The good substrings are "abc", "bca", "cab", and "abc". Constraints: 1 <= s.length <= 100 s​​​​​​ consists of lowercase English letters. ''' from typing import List def count_good_strings(chars: List[str], k: int) -> int: l, gc, r = 0, 0, k substr = dict() for i in range(min(k, len(chars))): substr[chars[i]] = substr.get(chars[i], 0) + 1 if len(substr) == k: gc += 1 while r < len(chars): substr[chars[r]] = substr.get(chars[r], 0) + 1 if substr[chars[l]] > 1: substr[chars[l]] -= 1 else: substr.pop(chars[l]) if len(substr) == k: gc += 1 r += 1 l += 1 return gc def brute_force(chars: List[str], k: int) -> int: gc = 0 for i in range(len(chars)): sub_str = chars[i: i + k] if len(set(sub_str)) == 3: gc += 1 return gc if __name__ == '__main__': k = 3 chars = ['a', 'a', 'b', 'a', 'b', 'c', 'a', 'b', 'c'] # ['a', 'b', 'c', 't'] gc = count_good_strings(chars, k) print(chars, gc) gc = brute_force(chars, k) print(chars, gc) chars = ['o', 'w', 'u', 'x', 'o', 'e', 'l', 's', 'z', 'b'] gc = count_good_strings(chars, k) print(chars, gc) gc = brute_force(chars, k) print(chars, gc) chars = ['x'] gc = count_good_strings(chars, k) print(chars, gc) gc = brute_force(chars, k) print(chars, gc)
61e6633eeadf4384a18603640e30e0fa0a6998c8
suyash248/ds_algo
/Array/stockSpanProblem.py
959
4.28125
4
from Array import empty_1d_array # References - https://www.geeksforgeeks.org/the-stock-span-problem/ def stock_span(prices): # Stores index of closest greater element/price. stack = [0] spans = empty_1d_array(len(prices)) # Stores the span values, first value(left-most) is 1 as there is no previous greater element(price) available. spans[0] = 1 # When we go from day i-1 to i, we pop the days when the price of the stock was less than or equal to price[i] and # then push the value of day i back into the stack. for i in range(1, len(prices)): cur_price = prices[i] while len(stack) != 0 and prices[stack[-1]] <= cur_price: stack.pop() spans[i] = (i+1) if len(stack) == 0 else (i-stack[-1]) stack.append(i) return spans if __name__ == '__main__': prices = [10, 4, 5, 90, 120, 80] spans = stock_span(prices) print("Prices:", prices) print("Spans:", spans)
6e8ee71a88eb45d5849993481a375a0d6a625afa
suyash248/ds_algo
/DynamicProgramming/minJumpsToReachEndOfArray.py
960
3.65625
4
from Array import empty_1d_array, MAX # Time complexity: O(n^2) # https://www.youtube.com/watch?v=jH_5ypQggWg def min_jumps(arr): n = len(arr) path = set() jumps = empty_1d_array(n, MAX) jumps[0] = 0 for i in xrange(1, n): for j in xrange(0, i): if i <= j + arr[j]: # Checking if `i` can be reached from `j` if jumps[j] + 1 < jumps[i]: jumps[i] = jumps[j] + 1 # jumps[i] = min(jumps[i], jumps[j] + 1) path.add(j) path.add(arr[-1]) # adding last element(destination) to path #print jumps, path return path if __name__ == '__main__': arr = [2, 3, 1, 1, 2, 4, 2, 0, 1, 1] path = min_jumps(arr) minimum_jumps = len(path) - 1 path = " -> ".join(map(lambda x: str(x), path)) print "To reach at the end, at least {} jump(s) are required and path(indices): {}".format(minimum_jumps, path)
2439116226bb241f4f6d138e4725607724c6e343
suyash248/ds_algo
/Tree/segment_tree/base_segment_tree.py
599
3.6875
4
from Array import empty_1d_array from math import pow, log, ceil """ Height of segment tree is log(n) #base 2, and it will be full binary tree. Full binary tree with height h has at most 2^(h+1) - 1 nodes. Segment tree will have exactly n leaves. """ class SegmentTree(object): def __init__(self, input_arr): self.input_arr = input_arr self.n = len(input_arr) self.height = ceil(log(self.n, 2)) # 2^(h+1) - 1, where h = log(n) // base 2 self.seg_tree_size = int(pow(2, self.height + 1) - 1) self.seg_tree_arr = empty_1d_array(self.seg_tree_size)
dad7df39a66de05b8743e5b6a8e52de20b24531f
suyash248/ds_algo
/Array/nextGreater.py
1,602
3.90625
4
""" Algorithm - 1) Push the first element to stack. 2) for i=1 to len(arr): a) Mark the current element as `cur_elt`. b) If stack is not empty, then pop an element from stack and compare it with `cur_elt`. c) If `cur_elt` is greater than the popped element, then `cur_elt` is the next greater element for the popped element. d) Keep popping from the stack while the popped element is smaller than `cur_elt`. `cur_elt` becomes the next greater element for all such popped elements. g) If `cur_elt` is smaller than the popped element, then push the popped element back to stack. 3) After the loop in step 2 is over, pop all the elements from stack and print -1 as next greater element for them. """ # Time Complexity: O(n) def next_greater(arr): stack = list() stack.append(arr[0]) for cur_elt in arr[1:]: if len(stack) > 0: popped_elt = stack.pop() if popped_elt < cur_elt: while popped_elt < cur_elt: print "{} -> {}".format(popped_elt, cur_elt) # Keep popping element until either stack becomes empty or popped_elt >= cur_elt if len(stack) == 0: break popped_elt = stack.pop() else: # If popped_elt >= cur_elt, push it back to stack and continue stack.append(popped_elt) # Push cur_elt to stack stack.append(cur_elt) while len(stack) > 0: print "{} -> {}".format(stack.pop(), -1) if __name__ == '__main__': arr = [4, 5, 2, 25] next_greater(arr)
c26340df6acd4f7cbe5fa2060212013b618b7f43
suyash248/ds_algo
/Tree/distanceBetweenNodes.py
1,301
3.984375
4
from Tree.commons import insert def distance_between_nodes(root, key1, key2): """ Dist(key1, key2) = Dist(root, key1) + Dist(root, key2) - 2*Dist(root, lca) Where lca is lowest common ancestor of key1 & key2 :param root: :param key1: :param key2: :return: """ from Tree.distanceFromRoot import distance_from_root_v1 from Tree.lowestCommonAncestor import lca_v2 d1 = distance_from_root_v1(root, key1) d2 = distance_from_root_v1(root, key1) lca = lca_v2(root, key1, key2) if lca is None: return 0 # When either of key1 or key2 is not found, distance is 0 d_lca = distance_from_root_v1(root, lca.key) return (d1 + d2 - 2*d_lca) # Driver program to test above function if __name__ == "__main__": """ Let us create following BST 50 / \ 30 70 / \ / \ 20 40 60 80 / \ 15 25 """ root = None root = insert(root, 50) insert(root, 30) insert(root, 20) insert(root, 15) insert(root, 25) insert(root, 40) insert(root, 70) insert(root, 60) insert(root, 80) key1= 60; key2 = 30 d = distance_between_nodes(root, key1, key2) print("Distance between {key1} & {key2} is {d}".format(key1=key1, key2=key2, d=d))
a8e3dc574a5a78960baaf96994c73f8ea5df4269
suyash248/ds_algo
/Tree/treeSerialization.py
1,906
3.53125
4
from commons.commons import insert, Node, print_tree class BinaryTreeSerialization(object): def __init__(self, delimiter=None): self.delimiter = delimiter self.index = 0 def __preorder__(self, root, serialized_tree=[]): if root is None: serialized_tree.append(self.delimiter) return None serialized_tree.append(root.key) self.__preorder__(root.left, serialized_tree) self.__preorder__(root.right, serialized_tree) def serialize(self, root): serialized_tree = [] self.__preorder__(root, serialized_tree) return serialized_tree def deserialize(self, serialized_tree): self.index = 0 root = self.__deserialize__(serialized_tree) return root def __deserialize__(self, serialized_tree): if self.index >= len(serialized_tree) or serialized_tree[self.index] == self.delimiter: self.index += 1 return None root = Node(serialized_tree[self.index]) self.index += 1 root.left = self.__deserialize__(serialized_tree) root.right = self.__deserialize__(serialized_tree) return root if __name__ == '__main__': root = Node(7, left=Node(2, left=Node(1) ), right=Node(5, left=Node(3), right=Node(8) ) ) print "\nInput Tree - \n" print_tree(root) print "\n************* SERIALIZATION *************\n" obj = BinaryTreeSerialization() serialized_tree = obj.serialize(root) print "Serialized Tree (Preorder) -", serialized_tree print "\n************* DE-SERIALIZATION *************\n" deserialized_tree_root = obj.deserialize(serialized_tree) print "\nOutput Tree - \n" print_tree(deserialized_tree_root)
576f7c47da643057c2643ba703b65e917a6597d4
suyash248/ds_algo
/Array/factorial.py
238
3.765625
4
def fact_rec(n): if n <= 1: return 1 return n * fact_rec(n-1) def fact_itr(n): fact = 1 for i in range(2, n+1): fact *= i return fact if __name__ == '__main__': print (fact_rec(5)) print (fact_itr(5))
d21394227d4390b898fc1588593e43616ed7e502
suyash248/ds_algo
/Misc/sliding_window/substrings_with_distinct_elt.py
2,324
4.125
4
''' Given a string s consisting only of characters a, b and c. Return the number of substrings containing at least one occurrence of all these characters a, b and c. Example 1: Input: s = "abcabc" Output: 10 Explanation: The substrings containing at least one occurrence of the characters a, b and c are "abc", "abca", "abcab", "abcabc", "bca", "bcab", "bcabc", "cab", "cabc" and "abc" (again). Example 2: Input: s = "aaacb" Output: 3 Explanation: The substrings containing at least one occurrence of the characters a, b and c are "aaacb", "aacb" and "acb". Example 3: Input: s = "abc" Output: 1 Constraints: 3 <= s.length <= 5 x 10^4 s only consists of a, b or c characters. ''' def __num_substrings_brute_force__(s: str) -> int: k = 3 res = 0 substr = dict() for i in range(min(k, len(s))): substr[s[i]] = substr.get(s[i], 0) + 1 if len(substr) == k: res += 1 for i in range(0, len(s) - k): left_elt = s[i] right_elt = s[i + k] substr[right_elt] = substr.get(right_elt, 0) + 1 if substr.get(left_elt) > 0: substr[left_elt] -= 1 else: substr.pop(left_elt) if len(substr) == k: res += 1 return res def num_substrings_brute_force(s: str) -> int: res = 0 for i in range(len(s)): res += __num_substrings_brute_force__(s[i:]) return res ############################################################################### def num_substrings_sliding_window(s: str) -> int: left = 0 right = 0 end = len(s) - 1 hm = dict() count = 0 while right != len(s): hm[s[right]] = hm.get(s[right], 0) + 1 while hm.get('a', 0) > 0 and hm.get('b', 0) > 0 and hm.get('c', 0) > 0: count += 1 + (end - right) hm[s[left]] -= 1 left += 1 right += 1 return count if __name__ == '__main__': s = "abcabc" res = num_substrings_brute_force(s) print(s, res) res = num_substrings_sliding_window(s) print(s, res) s = "aaacb" res = num_substrings_brute_force(s) print(s, res) res = num_substrings_sliding_window(s) print(s, res) s = "abc" res = num_substrings_brute_force(s) print(s, res) res = num_substrings_sliding_window(s) print(s, res)
447b5ce60dbe48b380de406540702ef28d034e84
suyash248/ds_algo
/Backtracking/allCombinations.py
2,187
3.53125
4
from Array import empty_1d_array # Time Complexity: O(2^n) def all_combinations(input_seq, combinations): for elt in input_seq: comb_len = len(combinations) for si in range(0, comb_len): combinations.append(combinations[si] + elt) """ {} a {} ab a b {} abc ab ac a bc b c {} """ # Time Complexity: O(2^n) def all_combinations_v2(input_seq, res, level): if level == len(input_seq): all_combinations_v2.combinations.add(res) return all_combinations_v2(input_seq, res, level + 1) all_combinations_v2(input_seq, res+input_seq[level], level + 1) # This solution takes care of duplicates as well. # https://www.youtube.com/watch?v=xTNFs5KRV_g # Time Complexity: O(2^n) def all_combinations_v3(input_seq, count, pos, combinations, level): # print till pos print_till_pos(combinations, level) for i in range(pos, len(input_seq)): if count[i] == 0: continue combinations[level] = input_seq[i] count[i] -= 1 all_combinations_v3(input_seq, count, i, combinations, level+1) count[i] += 1 def print_till_pos(arr, pos): res = "" for elt in arr[:pos]: res += elt print res, if __name__ == '__main__': input_seq = "aabc" print "\n------------------- Using V1 -------------------\n" combinations = [""] # empty list all_combinations(input_seq, combinations) print "All the combinations of {} are -\n".format(input_seq), ' '.join(combinations) print "\n------------------- Using V2 -------------------\n" all_combinations_v2.combinations = set() all_combinations_v2(input_seq, "", 0) print "All the combinations of {} are - ".format(input_seq) for c in all_combinations_v2.combinations: print c, print "" print "\n------------------- Using V3 -------------------\n" ch_counts = {ch: input_seq.count(ch) for ch in input_seq} print "All the combinations of {} are - ".format(input_seq) all_combinations_v3(ch_counts.keys(), ch_counts.values(), 0, empty_1d_array(len(input_seq)), 0)
bb174384697c54d507e314d4df23a66f32f10d0a
suyash248/ds_algo
/DynamicProgramming/stiver/climbingStairs.py
503
3.59375
4
def climbStairs(n: int) -> int: # dp = [-1 for i in range(n+1)] # def f(i, dp): # if i <= 1: # return 1 # if dp[i] != -1: # return dp[i] # dp[i] = f(i-1, dp) + f(i-2, dp) # return dp[i] # return f(n, dp) dp = [0 for i in range(n + 1)] for i in range(n + 1): if i <= 1: dp[i] = 1 else: dp[i] = dp[i - 1] + dp[i - 2] return dp[n] if __name__ == '__main__': print(climbStairs(2))
8df5ea6094331a9249b66ab3f1dd129d9f84957f
suyash248/ds_algo
/Tree/sumOfNodes.py
907
3.828125
4
from Tree.commons import insert, print_tree, is_leaf # fs(50) - 50, fs(30) # fs(30) - 80, fs(20) # fs(20) - 100 def find_sum_v1(root): if root is None: return 0 return root.key + find_sum_v1(root.left) + find_sum_v1(root.right) son = 0 def find_sum_v2(root): global son if root is None: return son son += root.key find_sum_v2(root.left) find_sum_v2(root.right) return son # Driver program to test above function if __name__ == "__main__": """ Let us create following BST 50 / \ 30 70 / \ / \ 20 40 60 80 """ root = None root = insert(root, 50) insert(root, 30) insert(root, 20) insert(root, 40) insert(root, 70) insert(root, 60) insert(root, 80) print("Sum of all nodes is", find_sum_v1(root)) print("Sum of all nodes is", find_sum_v2(root))
a23e6eb9e35e685b36de1e108a1734c750dfc093
suyash248/ds_algo
/Queues/PriorityQueue/pq.py
4,722
3.859375
4
from Heap.BinaryHeap.maxHeap import MaxHeap from copy import deepcopy class PriorityQueue(object): def __init__(self, pq_capacity=10): self._pq_capacity_ = pq_capacity self._pq_size_ = 0 self._pq_heap_ = MaxHeap(pq_capacity) # Time Complexity : O(log(n)) def insert(self, item, priority): res = False if self.is_full(): print("Priority queue is full, please delete older items in order to insert newer ones.") return res e = Entry(item, priority) res = self._pq_heap_.insert(e) if res: self._pq_size_ += 1 return res # Time Complexity : O(log(n)) def delete_item_with_highest_priority(self): res = False if self.is_empty(): print("Priority queue is empty") return res res = self._pq_heap_.delete_max() if isinstance(res, bool) and res == False: pass else: self._pq_size_ -= 1 return res # Time Complexity : O(1) def get_item_with_highest_priority(self): if self.is_empty(): print("Priority queue is empty") return False return self._pq_heap_.get_max() def is_full(self): return self._pq_size_ >= self._pq_capacity_ def is_empty(self): return self._pq_size_ <= 0 def pq_print(self): return deepcopy(self._pq_heap_.heap_arr()[0:self.pq_size()]) def pq_size(self): return self._pq_size_ def pq_capacity(self): return self._pq_capacity_ class Entry(object): """ Represents an entry(combination of item & priority) of priority queue. """ def __init__(self, item, priority): self.item = item self.priority = priority def __str__(self): return "({}:{})".format(self.item, self.priority) def __repr__(self): return "({}:{})".format(self.item, self.priority) def __le__(self, other): return self.priority <= other.priority def __lt__(self, other): return self.priority < other.priority def __ge__(self, other): return self.priority >= other.priority def __gt__(self, other): return self.priority > other.priority def __eq__(self, other): return self.priority == other.priority def __ne__(self, other): return self.priority != other.priority def test(): pq_arr_test = ["5 2", "6 1", "2 7", "4 3", "7 0", "8 5", "9 6"] pq_capacity = len(pq_arr_test) pq = PriorityQueue(pq_capacity) mh_test = MaxHeap(pq_capacity) for item_priority in pq_arr_test: item_priority = item_priority.split(" ") item = int(item_priority[0].strip()) priority = int(item_priority[1].strip()) mh_test.insert(priority) pq.insert(item, priority) print(pq.pq_arr()) print(mh_test.heap_arr()) print("Element with highest priority: ", pq.get_item_with_highest_priority()) if __name__ == '__main__': pq_capacity = input("Please enter the size/capacity of priority queue - ") pq = PriorityQueue(pq_capacity) menu = """ Menu: 1. Insert. 2. Print priority queue. 3. Get item with maximum priority. 4. Delete item with maximum priority. 5. Get the size and capacity of priority queue. 6. Stop. """ print(menu) while True: try: choice = input("Please enter your choice - ") except: print("Incorrect choice, please select from menu.") continue try: if choice == 1: item_priority = input("Enter item & priority separated by a white-space - ") item_priority = item_priority.split(" ") item = item_priority[0].strip() priority = item_priority[1].strip() res = pq.insert(item, priority) print(res) continue if choice == 2: print(pq.pq_print()) continue if choice == 3: res = pq.get_item_with_highest_priority() print(res) continue if choice == 4: res = pq.delete_item_with_highest_priority() print(res) continue if choice == 5: print("Size : {} | Capacity: {}".format(pq.pq_size(), pq.pq_capacity())) continue if choice == 6: break except Exception as ex: print("Error occurred while performing last operation(choice: {}):".format(choice)) print(ex.message, ex.args) print(menu)
23f3e33d6028d9aaad652432996ff2570df7490c
DineshDDi/full-python
/hash.py
582
3.71875
4
''' my_dict = dict(dini='001',divi='002') print(my_dict) ''' ''' emp_details = {'employees':{'divi':{'ID':'001','salary':'1000','designation':'team leader'},'dini':{'ID':'002', 'salary':'2000','designation':'associate'}}} print(emp_details) ''' import pandas as pd emp_details = {'employees':{'divi':{'ID':'001','salary':'1000','designation':'team leader'},'dini':{'ID':'002', 'salary':'2000','designation':'associate'}}} df = pd.DataFrame(emp_details['employees']) print(df)
700a4945fee532f3f8e9c9ea6be562cb597a8d69
DineshDDi/full-python
/ATM.py
2,187
3.859375
4
print("Welcome to ICICI Bank ATM") Restart = 'Q' Chance = 3 Balance = 1560.45 while Chance >= 0: pin = int(input("Please enter your PIN: ")) if pin == (1004): while Restart not in ('NO:1', 'NO:2', 'NO:3', 'NO:4'): print('Press 1 for your Bank Balance \n') print('Press 2 to make withdrawl \n') print('Press 3 to Deposit in \n') print('Press 4 to Return Card \n') Option = int(input('What Would like to choose : ')) if Option == 1: print('Your Account Balance is $', Balance, '\n') Restart = input('Go Back : ') if Restart in ('NO:1', 'NO:2', 'NO:3', 'NO:4'): print('Thank You') break elif Option == 2: Option2 = ('Q') withdrawl = float(input('How much you like to withdrawl? \n$100/$200/$500$2000')) if withdrawl in [100, 200, 500, 2000]: Balance = Balance - withdrawl print('\n Your Account Balance is now: ', Balance) Restart = input('Go Back : ') if Restart in ('NO:1', 'NO:2', 'NO:3', 'NO:4'): print('Thank You') break elif withdrawl != [100, 200, 500, 2000]: print('Invaild Amount, Please re-try \n') Restart = ('Q') elif Option == 3: Deposit_in = float(input('Please! enter the Deposit Amount: ')) Balance = Balance + Deposit_in print('\n Your Balance is now $: ', Balance) Restart = input('Go Back : ') if Restart in ('NO:1', 'NO:2', 'NO:3', 'NO:4'): print('Thank You') break elif Option == 4: print('Please wait your card as been return \n') print('Thank You') break elif pin != ('1004'): print('Incorect Password') Chance = Chance-1 if Chance == 0: print('\n NO more Chances, Please collect your Card') break
4d1f4252ebf1d0956f72f99824b1939e7741164c
DineshDDi/full-python
/mat.py
254
3.609375
4
import numpy as np #import pandas as pd import matplotlib.pyplot as plt time = np.arange(100) delta = np.random.uniform(10,10,size=100) y = 3*time - 7+delta plt.plot(time,y) plt.title("matplotlib") plt.xlabel("time") plt.ylabel("function") plt.show()
179bccd8b2796ea4c23ab39ccb490b7f59fb3689
DineshDDi/full-python
/Py_Tkinder/Dx_T1_S0028a(Tkinder_Horizontal Scale widget).py
575
3.65625
4
# Python program to demonstrate # scale widget from tkinter import * root = Tk() root.geometry("400x300") v1 = DoubleVar() def show1(): sel = "Horizontal Scale Value = " + str(v1.get()) l1.config(text=sel, font=("Courier", 14)) s1 = Scale(root, variable=v1, from_=0, to=100, orient=HORIZONTAL) l3 = Label(root, text="Horizontal Scaler") b1 = Button(root, text="Display Horizontal", command=show1, bg="yellow") l1 = Label(root) s1.pack(anchor=CENTER) l3.pack() b1.pack(anchor=CENTER) l1.pack() root.mainloop()
a7475e64d4c78ab644791db9a969b0ad9e4025b7
ninkle/cracking-the-coding-interview
/fibonnaci.py
182
4.03125
4
#prints the fibonnaci sequence for length n def fib(n): seq = [1, 1] while len(seq) < n+1: next = seq[-1] + seq[-2] seq.append(next) print(seq) fib(8)
d9313b97da54f2393f533ab9ba382be423f1b486
gauriindalkar/nested-if-else
/exercise weather.py
373
4.09375
4
exercise=input("enter set alarm") if exercise=="6": print("wake up morning") weather=input("enter the weather") if weather=="cold": print("put on sokes,jarking,handglose") elif weather=="summer": print("don't put on sokes,jarking,handglose") else: print("i will not go down for exercise") else: print("i will go to exercise")
555d0e87fbb1e5116ecb0427737d9177bf13508a
freespace/arduino-ADS7825
/ads7825.py
9,627
3.703125
4
#!/usr/bin/env python """ Simple interface to an arduino interface to the ADS7825. For more details see: https://github.com/freespace/arduino-ADS7825 Note that in my testing, the ADS7825 is very accurate up to 10V, to the point where there is little point, in my opinion, to write calibration code. The codes produce voltages that are within 0.01V of the value set using a HP lab PSU. TODO: - Implement self test using don/doff commands. Use read function to determine if don/doff is working - Use either PWM driver or another chip to generate a clock signal and determine the maximum sampling rate of the system - It will be limited by how fast we can service interrupts, which in turn will be limited by how fast the firmware is capable of reading from the ADC """ from __future__ import division import serial import time def c2v(c, signed=True): """ If signed is True, returns a voltage between -10..10 by interpreting c as a signed 16 bit integer. This is the default behaviour. If signed is False, returns a voltage between 0..20 by interpreting c as an UNSIGNED 16 bit integer. """ if signed: return 10.0 * float(c)/(0x7FFF) else: return 20.0 * float(int(c)&0xFFFF)/(0xFFFF) def find_arduino_port(): from serial.tools import list_ports comports = list_ports.comports() for path, name, vidpid in comports: if 'FT232' in name: return path if len(comports): return comports[0][0] else: return None class ADS7825(object): # this indicates whether we interpret the integers from the arduino # as signed or unsigned values. If this is True, then voltages will be # returned in the range -10..10. Otherwise voltages will be returned # in the range 0..10. # # This is useful when doing multiple exposures with unipolar signals which # would otherwise overflow into negative values when signed. signed=True def __init__(self, port=None, verbose=False): super(ADS7825, self).__init__() self._verbose = verbose if port is None: port = find_arduino_port() self._ser = serial.Serial(port, baudrate=250000) # Let the bootloader run time.sleep(2) # do a dummy read to flush the serial pipline. This is required because # the arduino reboots up on being connected, and emits a 'Ready' string while self._ser.inWaiting(): c = self._ser.read() if verbose: print 'ads7825>>',c def _c2v(self, c): return c2v(c, signed=self.signed) def _write(self, x, expectOK=False): self._ser.write(x) self._ser.flush() if self._verbose: print '>',x if expectOK: l = self._readline() assert l == 'OK', 'Expected OK got: '+l def _readline(self): return self._ser.readline().strip() def _read16i(self, count=1): b = self._ser.read(2*count) import struct fmtstr = '<'+ 'h' * count ints = struct.unpack(fmtstr, b) if count == 1: return ints[0] else: return ints def set_exposures(self, exposures): """ Sets the exposure value, which is the number of readings per read request. This affects read and scan, and defaults to 1. """ exposures = int(exposures) aschar = chr(ord('0')+exposures) self._write('x'+aschar, expectOK=True) def read(self, raw=False): """ Returns a 4-tuple of floats, containing voltage measurements, in volts from channels 0-3 respectively. Voltage range is +/-10V """ self._write('r') line = self._readline() codes = map(float,map(str.strip,line.split(','))) if raw: return codes else: volts = map(self._c2v, codes) return volts def scan(self, nchannels=4): """ Asks the firmware to beginning scanning the 4 channels on external trigger. Note that scans do NOT block serial communication, so read_scans will return the number of scans currently available. """ self._write('s'+str(nchannels), expectOK=True) @property def buffer_writepos(self): """ Returns the write position in the buffer, which is an indirect measure of the number of scans, with the write position incremeneting by nchannels for every scan triggered. """ self._write('c') return self._read16i() def output_on(self, output): """ Turns the specified output """ assert output >= 0 and output < 10, 'Output out of range' self._write('o'+str(output), expectOK=True) def output_off(self, output): """ Turns off the specified output """ assert output >= 0 and output < 10, 'Output out of range' self._write('f'+str(output), expectOK=True) def set_trigger_divider(self, n): """ Divides the incoming trigger signal by n, triggering every nth trigger. Valid range is 1..9 currently. """ assert n > 0 and n < 10 self._write('t'+str(n), expectOK=True) def read_scans(self, nscans, binary=True, nchannels=4): """ Gets from the firmware the scans it buffered from scan(). You must supply the number of scans (nscans) to retrieve. Each scan consists of nchannels number of 16 bit ints. nchannels: the number of channels scanned per scan If binary is set to True, then 'b' is used to retrieve the buffer instead of 'p'. Defaults to True. Returns a list of voltage measurements. , e.g. [v0_0, v1_0, v2_0, v3_0, v0_1, v1_1, v2_1, v3_1 ... v0_n-1, v1_n-1, v2_n-1, v3_-1] If called before nscans have been required, you will get an exception. Just wait a bit longer, and check also that nscans does not exceed the buffer allocated in the firmware. e.g. if buffer can only hold 10 scans, and you want 20, then this method will ALWAYS throw an exception. You should NOT call this during data acquisition because if the processor is forced to handle communication then it will miss triggers because to preserve data integrity interrupts are disabled when processing commands. """ nscans = int(nscans) nchannels = int(nchannels) self._ser.flushInput() if binary: wantints = nscans * nchannels assert wantints < 63*64+63 # ask for binary print out of the required number # int samples self._write('B') ascii0 = ord('0') # we encode using our ad hoc b64 scheme self._write(chr(wantints%64 + ascii0)) self._write(chr(wantints//64 + ascii0)) # get the number of ints available nints = self._read16i() print 'Wanted %d ints, %d available'%(wantints, nints) # read them all in codes = self._read16i(count=nints) if nints < nscans*nchannels: raise Exception("Premature end of buffer. ADC probably couldn't keep up. Codes available: %d need %d"%(nints, nscans*nchannels)) return map(self._c2v, codes)[:nscans*nchannels] else: self._write('p') volts = list() done = False while not done: line = self._readline() if line == 'END': raise Exception("Premature end of buffer. ADC probably couldn't keep up. Lines read: %d"%(len(volts)//4)) ints = map(int,line.split(' ')) index = ints[0] codes = ints[1:] assert(len(codes) == 4) volts += map(self._c2v, codes) if index == nscans-1: done = True # read to the end of the buffer while self._readline() != 'END': pass return volts def close(self): self._ser.close() self._ser = None class Test(): @classmethod def setup_all(self): ardport = find_arduino_port() import readline userport = raw_input('Serial port [%s]: '%(ardport)) if len(userport) == 0: userport = ardport self.adc = ADS7825(ardport, verbose=False) def _banner(self, text): l = len(text) print print text print '-'*l def test_read(self): volts = self.adc.read() print 'Volts: ', volts assert len(volts) == 4 def test_exposures(self): self.adc.set_exposures(1) volts1 = self.adc.read() print 'Volts: ', volts1 self.adc.set_exposures(2) volts2 = self.adc.read() print 'Volts: ', volts2 for v1, v2 in zip(volts1, volts2): assert abs(v2) > abs(v1) def test_outputs(self): self._banner('Digital Output Test') for pin in xrange(8): for ch in xrange(4): e = raw_input('Connect D%d to channel %d, Enter E to end. '%((49-pin), ch+1)) if e == 'E': return self.adc.output_off(pin) voltsoff = self.adc.read() self.adc.output_on(pin) voltson = self.adc.read() print 'on=',voltson[ch], 'off=',voltsoff[ch] assert voltson[ch] > voltsoff[ch] def test_trigger(self): self._banner('Trigger Test') period_ms = 2 halfperiod_s = period_ms*0.5/1000 e = raw_input('Connect D49 to D38, enter E to end.') if e == 'E': return ntriggers = 200 for nchannels in (1,2,3,4): for trigger_div in (1,2,3,5): self.adc.set_trigger_divider(trigger_div) self.adc.scan(nchannels) assert self.adc.buffer_writepos == 0 for x in xrange(ntriggers): self.adc.output_on(0) time.sleep(halfperiod_s) self.adc.output_off(0) time.sleep(halfperiod_s) #print self.adc.buffer_writepos, x+1 writepos = self.adc.buffer_writepos print 'write pos at %d after %d scans of %d channels'%(writepos, ntriggers/trigger_div, nchannels) assert writepos == ntriggers//trigger_div * nchannels if __name__ == '__main__': import nose nose.main()
68516328653c342ca1f8fc10bd452fa86833787d
shangkh/github_python_interview_question
/54.保留两位小数.py
163
3.765625
4
a = "%.2f" % 1.3335 print(a, type(a)) """ round(数值, 保留的数位) """ b = round(float(a), 1) print(b, type(b)) b = round(float(a), 2) print(b, type(b))
b09dd9b4ee31c95569dbed4125448b6894d26b80
shangkh/github_python_interview_question
/17.pyhton中断言方法举例.py
212
3.765625
4
""" assert():断言成功,则程序继续执行,断言失败,则程序报错 """ a = 3 assert (a > 1) print("断言成功,程序继续执行") b = 4 assert (b > 7) print("断言失败,程序报错")
80ebbfd1da7c991ac5810797b90fe493ec22b654
shangkh/github_python_interview_question
/11.简述面向对象中__new__和__init__区别.py
1,384
4.21875
4
""" __init__ 是初始化方法,创建对象后,就立刻被默认调用了,可以接收参数 """ """ __new__ 1.__new__ 至少要有一个参数 cls,代表当前类,此参数在实例化时由python解释器自动识别 2.__new__ 必须要有返回值,返回实例化出来的实例,这点在自己实现__new__时要特别注意, 可以return父类(通过super(当前类名, cls))__new__出来的实例, 或者直接是object的__new__出来的实例 3.__int__有一个参数self,就是这个__new__返回的实例, __init__在__new__的基础上可以完成一些其他的初始化动作, __init__不需要返回值 4.如果__new__创建的是当前类的实例,会自动调用__init__函数, 通过return语句里面调用的__new__函数的 第一个参数是cls来保证是当前类实例,如果是其他类的类名; 那么实际创建返回的就是其他类的实例, 其实就不会调用当前类的__init__函数,也不会调用其他类的__init__函数 """ class A(object): def __int__(self): print("这是__init__方法", self) def __new__(cls, *args, **kwargs): print("这是cls的ID:", id(cls)) print("这是__new__方法", object.__new__(cls)) return object.__new__(cls) if __name__ == '__main__': A() print("这是类A的ID:", id(A))
3ea7c9fc3f2670d89546b76d94c81782face9a2f
shangkh/github_python_interview_question
/80.根据字符串的长度排序.py
111
3.53125
4
s = ["ab", "abc", "a", "asda"] b = sorted(s, key=lambda x: len(x)) print(s) print(b) s.sort(key=len) print(s)
8aebc47e8ae2b71081771c8c069292f1795bc6f2
shangkh/github_python_interview_question
/89.用两种方法去空格.py
118
3.6875
4
str = "Hello World ha ha" res = str.replace(" ", "") print(res) list = str.split(" ") res = "".join(list) print(res)
eddce67f5ecab1fef1b56b2df5c1a707b390b0da
shangkh/github_python_interview_question
/6.python实现列表去重的方法.py
138
3.65625
4
my_list = [11, 12, 13, 12, 15, 16, 13] list_to_set = set(my_list) print(list_to_set) new_list = [x for x in list_to_set] print(new_list)
eda27ec0aba10380bb4f1625ce68bfc49c62142e
shangkh/github_python_interview_question
/76.列表嵌套列表排序,年龄数字相同怎么办.py
236
3.59375
4
my_list = [["wang", 19], ["shang", 34], ["zhang", 23], ["liu", 23], ["xiao", 23]] a = sorted(my_list, key=lambda x: (x[1], x[0])) # 年龄相同添加参数,按字母排序 print(a) a = sorted(my_list, key=lambda x: x[0]) print(a)
8510c5a27d2ed435e47d615d6c9955a388f61424
shangkh/github_python_interview_question
/75.列表嵌套元祖,分别按字母和数字排序.py
223
3.53125
4
my_list = [("wang", 19), ("li", 55), ("xia", 24), ("shang", 11)] a = sorted(my_list, key=lambda x: x[1], reverse=True) # 年龄从大到小 print(a) a = sorted(my_list, key=lambda x: x[0]) # 姓名从小到大 print(a)
abae063d758cc0302f666398f6c169627f66c319
sacremendev/Project-Euler
/Q14.py
363
3.8125
4
#!/usr/bin/python def count(n): k = 0 while n != 1: if (n % 2) == 0: n = n / 2 else: n = n * 3 + 1 k = k + 1 #print n #print k return k result = 0 for i in range(1, 1000000): num = count(i) if num > result: print ("update ", i, " ", num) result = num print (result)
0c927b6c474351d757a631300070d4010d458afa
green-fox-academy/Angela93-Shi
/week-02/day-8/copy_file.py
537
3.6875
4
# Write a function that copies the contents of a file into another # It should take the filenames as parameters # It should return a boolean that shows if the copy was successful import shutil def copy_file(oldfile,newfile): shutil.copyfile(oldfile,newfile) f=open(oldfile,'r') f.seek(0) text1 = f.read() print(text1) f=open(newfile,'r') f.seek(0) text2 = f.read() print(text2) if text1 == text2: return True else: return False print(copy_file("my_file.txt","my-file.txt"))
9d3b7f05c931cceb48d7c2e53fce9dfc35ca1f79
green-fox-academy/Angela93-Shi
/week-05/day-03/change_xy.py
335
3.984375
4
# Given a string, compute recursively (no loops) a new string where all the lowercase 'x' chars # have been changed to 'y' chars. def change_xy(str): if len(str) == 0: return str if str[0] == 'x': return 'y' + change_xy(str[1:]) return str[0] + change_xy(str[1:]) print(change_xy("xxsdsfefenkefnxx"))
f41c3b2d10e43b66cf7ea4ec8c7ad8f527facd28
green-fox-academy/Angela93-Shi
/week-03/day-01/foreat_simulator.py
1,830
3.953125
4
class Tree: def __init__(self,height=0): self.height = height def irrigate(self): pass def getHeight(self): return self.height class WhitebarkPine(Tree): def __init__(self,height=0): Tree.__init__(self , height) self.height = height def irrigate(self): self.height += 2 class FoxtailPine(Tree): def __init__(self,height=0): Tree.__init__(self , height) self.height = height def irrigate(self): self.height += 2 class Lumberjack: def canCut(self,tree): if tree.height > 4: return True else: return False class Forest: def __init__(self): self.trees =[] def add_tree(self,tree): self.trees.append(tree) def rain(self): for tree in self.trees: tree.irrigate() def cutTrees(self,lumberjack): trees_cut=[] for tree in self.trees: if lumberjack.canCut(tree): trees_cut.append(tree) for i in trees_cut: for tree in self.trees: if i == tree: self.trees.remove(tree) def is_empty(self): if len(self.trees) == 0: return True else: return False def get_status(self): for tree in self.trees: # tree.__class__.__name__ get the current name of tree return f'there is a { tree.height } tall {tree.__class__.__name__}in the forest' whitebarkPine = WhitebarkPine(3) # whitebarkPine.irrigate() foxtailPine = FoxtailPine(4) # foxtailPine.irrigate() # lumberjack = Lumberjack() forest = Forest() forest.add_tree(whitebarkPine) forest.add_tree(foxtailPine) # # forest.rain() print(forest.get_status())